How to pass an array of java object to AsyncTask? My problem is that when I use this looping in AsyncTask pq only comes first user [0]

-1
ControlaBanco bd = new ControlaBanco(contexto);
        int indice = 0;
        indice = bd.contaUsuarios();
        Usuario[ ] tabela = bd.organizaTabela();
        String tabelaOrganizada = "";
        if ( indice > 0 ) {
            for (int i = 0; i < indice; i++) {
                tabelaOrganizada += String.valueOf(tabela[ i ].getId()) + "  ";
                tabelaOrganizada += tabela[ i ].getNome() + "  ";
                tabelaOrganizada += tabela[ i ].getTitulo() + "  ";
                tabelaOrganizada += tabela[ i ].getPTS() + "  ";
                tabelaOrganizada += tabela[ i ].getGraduacao() + "\n";
            }
        }
        int id = 4;
        TableRow.LayoutParams linhaParams = new TableRow.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        final TextView fimRank = new TextView(contexto);
        fimRank.setLayoutParams(linhaParams);
        fimRank.setId(id);
        fimRank.setTextSize(TypedValue.COMPLEX_UNIT_SP, 15);
        fimRank.setGravity(Gravity.CENTER_HORIZONTAL);
        fimRank.setText(tabelaOrganizada);
        TableRow.LayoutParams spanparams = new TableRow.LayoutParams();
        spanparams.span = 4;

        TableRow linha4Tabela = new TableRow(contexto);
        linha4Tabela.setLayoutParams(linhaParams);
        linha4Tabela.setId(id);
        linha4Tabela.addView(fimRank, spanparams);
        containertabela.addView(linha4Tabela);
    
asked by anonymous 17.05.2018 / 03:47

2 answers

0

I was able to solve the problem, first of all I would like to thank @Samuel Ives for the answer. But the problem was in the organizaTabela () method that was not returning the complete array because every object I was going to add to the array was not putting the following line of code:

table [i] = new User ();

I really wanted Samuel Ives' answer to be right for the job he had to answer but it was not the answer I used to solve the valew problem.

    
17.05.2018 / 22:40
0

As far as I know you need to specify the types that asynctask will work, pass the parameters in your asynctask.execute (the input type if it is not void is an array), and retrieve it in doInBackground (Params ...), where Params ... is an array of the type you specified, then retrieve it as an array, example String str = params[0];

Edited:

For simplicity I'll leave an example of my app

PageTask is an interface that I use to retrieve data:

package com.samuelives.videoplayer.system;

import java.util.ArrayList;

public interface PageTask {

    public void finishDownload(ArrayList<String>data);

}

PageDownloader is my Asynctask responsible for extracting data from a page:

package com.samuelives.videoplayer.system;

import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Build;
import android.util.Log;
import android.util.Patterns;
import android.webkit.MimeTypeMap;
import android.webkit.URLUtil;

import com.samuelives.videoplayer.R;

import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;

import javax.net.ssl.HttpsURLConnection;

public class PageDownloader extends AsyncTask<String, String, ArrayList<String>>{

    private PageTask mPt;
    private Context mContext;
    private ProgressDialog mProgress;

    public PageDownloader(PageTask pt, Context context){
        this.mPt = pt;
        this.mContext = context;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        Log.i("Page Downloader", "Baixando pagina da web...");
        mProgress = new ProgressDialog(mContext);
        mProgress.setTitle(mContext.getResources().getString(R.string.pageDownloader_proDlgTitle));
        mProgress.setMessage(mContext.getResources().getString(R.string.pageDownloader_proDlgInitialMessage));
        mProgress.show();
    }


    @Override
    protected ArrayList<String> doInBackground(String... strings) {

        ArrayList<String>content = new ArrayList<>();

        try{

            Document page = null;
            String ua = getUserAgent();

            Connection.Response response = Jsoup.connect(strings[0]).userAgent(ua).execute();

            if(testConnection(response)){
                page = Jsoup.connect(strings[0]).userAgent(getUserAgent()).get();

                String videoSrc = getVideoSource(page);

                content.add(0, videoSrc);
                content.add(1, getVideoTitle(page));

                if(Patterns.WEB_URL.matcher(videoSrc).matches()){
                    content.add(2, getVideoMime(videoSrc));
                }else{
                    content.add(2, "null");
                }

            }else{
                content.add(0,"null");
                content.add(1,"null");
                content.add(2,"null");
            }


        }catch (IllegalArgumentException | IOException e){
            Log.e("Could connect to page", e.getMessage());
        }

        return content;
    }

    @Override
    protected void onPostExecute(ArrayList<String> strings) {
        super.onPostExecute(strings);

        mProgress.dismiss();

        Log.i("Page Downloader", "Download completo");
        Log.i("Video src", strings.get(0));
        Log.i("Video title", strings.get(1));
        Log.i("Video MIME", strings.get(2));

        mPt.finishDownload(strings);

    }

    private boolean testConnection(Connection.Response response){


        //Check if exist response of connection
        if(response != null){

            //Check if connection is OK
            if(response.statusCode() != 200){

                Log.e("Page downloader", "Failed to connect, Response Code: " + response.statusCode());
                return false;

            }else{

                Log.i("Page downloader", "Connection OK");
                return true;

            }


        }else{

            Log.e("Page downloader", "Error, have not response of connection!");
            return false;

        }

    }

    private String getVideoSource(Document doc){

        try {

            Element videoSrc = doc.getElementsByTag("video").first();
            Element sourceSrc = null;
            if (videoSrc != null) {

                if(videoSrc.attr("src") != null){
                    return videoSrc.attr("src");
                }else{
                    sourceSrc = videoSrc.getElementsByTag("source").first();
                    if(sourceSrc != null){

                        if(sourceSrc.attr("src") != null){
                            return sourceSrc.attr("src");
                        }

                    }
                }

            }

        }catch (NullPointerException e){
            Log.e("Page downloader", "Failed to get source: " + e.getMessage());
        }

        return "null";
    }

    private String getVideoTitle(Document doc){

        String title = "videoplayback";

        try {

            Element titleTag = doc.getElementsByTag("title").first();
            if((titleTag != null) && (titleTag.text() != null)){
                title = titleTag.text();
            }

        }catch (NullPointerException e){
            Log.e("Page downloader", "Could get page title: " + e.getMessage());
        }

        return title;
    }

    private String getVideoMime(String input){

        String mimeType = "null";
        URL url = null;

        try {

            url = new URL(input);

            if(URLUtil.isHttpsUrl(input)){

                Log.d("Page downloader", "HTTPS Url source.");

                HttpsURLConnection con = (HttpsURLConnection)url.openConnection();
                con.setRequestProperty("User-Agent", getUserAgent());

                String ct = con.getContentType();

                if((ct.equals("text/html")) || (ct.equals("application/xhtml+xml")) || (ct.equals("text/php")) || (ct.equals("application/php")) || (ct.equals("application/x-php") || (ct.equals("text/x-php")))){

                    if(con.getHeaderField("Location") != null){

                        String urlLocation = con.getHeaderField("Location");
                        String extension = MimeTypeMap.getFileExtensionFromUrl(urlLocation);
                        if(extension != null){
                            mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
                        }

                    }

                }else{

                    mimeType = con.getContentType();

                }

                con.disconnect();

            }else{

                Log.d("Page downloader", "HTTPS Url source.");

                HttpURLConnection con = (HttpsURLConnection)url.openConnection();
                con.setRequestProperty("User-Agent", getUserAgent());

                String ct = con.getContentType();

                if((ct.equals("text/html")) || (ct.equals("application/xhtml+xml")) || (ct.equals("text/php")) || (ct.equals("application/php")) || (ct.equals("application/x-php") || (ct.equals("text/x-php")))){

                    if(con.getHeaderField("Location") != null){

                        String urlLocation = con.getHeaderField("Location");
                        String extension = MimeTypeMap.getFileExtensionFromUrl(urlLocation);
                        if(extension != null){
                            mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
                        }

                    }

                }else{

                    mimeType = con.getContentType();

                }

                con.disconnect();

            }

        }catch (NullPointerException | IOException e){
            Log.e("Page downloader", "Could get mimetype: " + e.getMessage());
        }

        return mimeType;
    }

    private String getUserAgent(){

        String ua = null;
        boolean isTablet = mContext.getResources().getBoolean(R.bool.isTablet);

        if(!isTablet){

            ua = "Mozilla/5.0 (Linux; Android " + Build.VERSION.RELEASE + "; Mobile; rv: 41.0) Gecko/41.0 Firefox/41.0";
            Log.d("User-Agent", ua);

        }else{

            ua = "Mozilla/5.0 (Linux; Android " + Build.VERSION.RELEASE + "; Tablet; rv: 41.0) Gecko/41.0 Firefox/41.0";
            Log.d("User-Agent", ua);

        }

        return ua;

    }

}

Note that when I extend my class to AsyncTask I specify the input and output parameters Note that String is the input parameter because it is a URL the second parameter is the data type for progress and ArrayList is the data type result with the extracted data that I retrieve in onPostExecute for my interface.

And this is the fragment in which I run asynctask:

package com.samuelives.videoplayer.fragments;

import android.content.Intent;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.preference.PreferenceManager;
import android.util.Log;
import android.util.Patterns;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.samuelives.videoplayer.R;
import com.samuelives.videoplayer.player.Player;
import com.samuelives.videoplayer.system.PageDownloader;
import com.samuelives.videoplayer.system.PageTask;

import java.util.ArrayList;

import static android.content.Context.CONNECTIVITY_SERVICE;

public class MainFragment extends Fragment implements PageTask{

    private Button btnOpenUrl = null;
    private EditText etInputUrl = null;
    private PageDownloader mPageDownloader = null;

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        mPageDownloader = new PageDownloader(this, getActivity());
        btnOpenUrl.setOnClickListener(btnListener);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);

        View layout = inflater.inflate(R.layout.fragment_main, container, false);

        etInputUrl = (EditText)layout.findViewById(R.id.etInputUrl);
        btnOpenUrl = (Button)layout.findViewById(R.id.btnOpenUrl);

        return layout;
    }

    private View.OnClickListener btnListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            if(etInputUrl.getText().toString() != null){

                if(Patterns.WEB_URL.matcher(etInputUrl.getText().toString()).matches()){

                    ConnectivityManager cm = (ConnectivityManager) getActivity().getSystemService(CONNECTIVITY_SERVICE);
                    NetworkInfo activeNetwork = cm.getActiveNetworkInfo();

                    if((activeNetwork != null) && (activeNetwork.isConnectedOrConnecting())){
                        processUrl(etInputUrl.getText().toString());
                    }else{
                        Toast.makeText(getActivity(), R.string.toastConnectionOffline, Toast.LENGTH_LONG).show();
                    }

                }else{

                    Toast.makeText(getActivity(), R.string.toastInvalidUrl, Toast.LENGTH_LONG).show();

                }

            }else{
                Toast.makeText(getActivity(), getResources().getString(R.string.toastEmptyUrl), Toast.LENGTH_LONG).show();
            }

        }
    };

    @Override
    public void finishDownload(ArrayList<String> data) {

        if((data.get(0) != null) && (data.get(0).equals("null")) && (Patterns.WEB_URL.matcher(data.get(0)).matches())) {
            Intent it = new Intent(getActivity(), Player.class);
            it.putExtra("videoSrc", data.get(0));
            it.putExtra("videoTitle", data.get(1));
            it.putExtra("videoMime", data.get(2));
            startActivity(it);
        }else{
            Toast.makeText(getActivity(), R.string.toastNoContent, Toast.LENGTH_LONG).show();
        }

    }

    private void processUrl(String url){

        if(isWatchOnlyWifi()){

            if(!connectionIsWifi()){
                Toast.makeText(getActivity(), getResources().getString(R.string.toastOnlyWatchWifi), Toast.LENGTH_LONG).show();
                return;

            }else{

                if(!url.isEmpty()) {

                    if (url.contains(".mp4") || url.contains(".3gp") || url.contains(".ogv")) {

                        Intent it = new Intent(getActivity(), Player.class);
                        it.putExtra("videoTitle", "Video Playback");
                        it.putExtra("videoSrc", url);
                        startActivity(it);

                    } else {

                        mPageDownloader = new PageDownloader(this, getActivity());
                        mPageDownloader.execute(url);

                    }

                }else{
                    Toast.makeText(getActivity(), getResources().getString(R.string.toastEmptyUrl), Toast.LENGTH_LONG).show();
                }

            }


        }else {

            if(!url.isEmpty()) {

                if (url.contains(".mp4") || url.contains(".3gp") || url.contains(".ogv")) {

                    Intent it = new Intent(getActivity(), Player.class);
                    it.putExtra("videoTitle", "Video Playback");
                    it.putExtra("videoSrc", url);
                    startActivity(it);

                } else {

                    mPageDownloader = new PageDownloader(this, getActivity());
                    mPageDownloader.execute(url);

                }

            }else{

                Toast.makeText(getActivity(), getResources().getString(R.string.toastEmptyUrl), Toast.LENGTH_LONG).show();
            }
        }

    }

    private boolean isWatchOnlyWifi(){
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
        return prefs.getBoolean("pref_key_is_watch_only_wifi", false);
    }

    private boolean connectionIsWifi(){

        try {
            ConnectivityManager manager = (ConnectivityManager) getActivity().getSystemService(CONNECTIVITY_SERVICE);
            NetworkInfo info = manager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);

            if (info.isConnected()) {
                return true;
            } else {
                return false;
            }
        }catch (NullPointerException e){
            Log.e("Main", "Error: " + e.getMessage());
        }

        return false;
    }
}

I pass the parameters and execute the task with execute () where the input value is an array of the type you specified, when the task terminates the method of my interface that I am implementing finishDownload(ArrayList<String> data) is called retrieving the data, this is it, there is not much secret, it took me a while to understand the operation as well.

This video helped me a lot to understand asynctask.

    
17.05.2018 / 12:20