MSMC
MSMC

Reputation: 141

Passing ArrayList from AsyncTask to PagerAdapter

hope you fine and well,

i have the following main class :

public class MainActivity extends AppCompatActivity {
    Activity activity;

    ViewPager viewPager;
    CustomAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        viewPager=(ViewPager)findViewById(R.id.view_pager);
        adapter=new CustomAdapter(this);
        viewPager.setAdapter(adapter);

                ConnectionAsyncTask connectionAsyncTask = new
                ConnectionAsyncTask(MainActivity.this);
                connectionAsyncTask.execute("http://www.mocky.io/v2/570d3677270000f600dc29b6");
    }

    public void showUploader()
    {
       // findViewById(R.id.progressBar1).setVisibility(View.VISIBLE);
    }
    public void hideUploader()
    {
        //findViewById(R.id.progressBar1).setVisibility(View.GONE);
    }


    public void DisplyOnTextView(List< Student > students) {

        List  <Student> my = students ;

    }             
}

when i run the app, this main activity will use another class to read json data from link as follows:

public class StudentJasonParser {
    public static List<Student> getObjectFromJason(String jason)
    {
        List<Student> students;
        try {
            JSONArray jsonArray = new JSONArray(jason);
            students = new ArrayList<>();
            for(int i=0;i<jsonArray.length();i++)
            {
                JSONObject jsonObject = new JSONObject();
                jsonObject= (JSONObject) jsonArray.get(i);
                Student student = new Student();
                student.setID(jsonObject.getInt("id"));
                student.setName(jsonObject.getString("name"));
                student.setUrl(jsonObject.getString("url"));
                student.setDes(jsonObject.getString("des\n"));
                student.setRate(jsonObject.getDouble("rate"));
                student.setLon(jsonObject.getDouble("lon"));
                student.setLat(jsonObject.getDouble("lat"));
                students.add(student);
            }
        } catch (JSONException e) {
            e.printStackTrace();
            return null;
        }
        return students;
    }
}

now this class will return the data to the following class :

public class ConnectionAsyncTask extends AsyncTask<String,String,String> {
    Activity activity;
    public ConnectionAsyncTask(Activity activity) {
        this.activity=activity;
    }
    @Override
    protected void onPreExecute() {
        //((MainActivity)activity).DisplyOnTextView();
        ((MainActivity)activity).showUploader();
    }
    @Override
    protected String doInBackground(String... params) {
        String content =HttpManager.getData(params[0]);
        return content;
    }
    @Override
    protected void onProgressUpdate(String... values) {
        super.onProgressUpdate(values);
    }
    @Override
    protected void onPostExecute(String s) {
        ((MainActivity)activity).hideUploader();
        List<Student> students= StudentJasonParser.getObjectFromJason(s);
        if (students != null) {

                    ((MainActivity) activity).DisplyOnTextView(students);
        }
   }
}

this line : ((MainActivity)activity).DisplyOnTextView(students);

will return the fetched data to the main class in the following function (mentioned in the main class ! )

public void DisplyOnTextView(List< Student > students) {

        List  <Student> my = students ;

    }

now what i want is to pass this list to the following class in order to use it in the imageView and textView in the viewPager instead of the pre-defined data in the class :

public class CustomAdapter extends PagerAdapter {

    private int[] images = {R.drawable.sample_0,R.drawable.sample_1};
    private Context ctx;
    private LayoutInflater LayoutInflater;

    public CustomAdapter(Context ctx)
    {
        this.ctx=ctx;
    }

    @Override
    public int getCount() {
        return images.length;
    }

    @Override
    public boolean isViewFromObject(View view, Object object) {
        return (view==(LinearLayout)object);
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position) {



        LayoutInflater = (LayoutInflater)ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View view = LayoutInflater.inflate(R.layout.slide_layout,container,false);
        ImageView imageView =(ImageView) view.findViewById(R.id.image_view);
        TextView textView = (TextView)view.findViewById(R.id.image_count);
        imageView.setImageResource(images[position]);

        textView.setText(""+position);
        container.addView(view);
        return view;
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        container.removeView((LinearLayout) object);
    }



}

any idea ?!

thanks, regards.

Upvotes: 0

Views: 1315

Answers (1)

OneCricketeer
OneCricketeer

Reputation: 191725

what i want is to pass this list to the following class in order to use it in the imageView and textView in the viewPager

Then simply pass in the list as a parameter to the adapter and add a member variable for it. The usage of this adapter is at the bottom of this post, because I want to mention some other stuff.

class CustomAdapter extends PagerAdapter {
    private Context ctx;
    private List<Student> data;

    public CustomAdapter(Context ctx, List<Student> students) {
        this.ctx = ctx;
        this.data = students;
    }

If you want to use that data variable in the instantiateItem method, then you can do Student s = this.data.get(position); and use the various methods on the Student object to load the TextView or ImageView.


Please note that you will need an image loading library (Picasso, Glide, Fresco, etc.) to load a URL into an ImageView. While on the topic of libraries, though, you will save yourself much development time by looking into Gson for JSON parsing and Retrofit or Volley for HTTP network calls with JSON data.


As for your usage of the AsyncTask, passing around the Activity variable is bad practice. Try to use an asynchronous callback to the Activity instead.

public interface AsyncResponse<T> {
    void onResponse(T response);
} 
public class ConnectionAsyncTask extends AsyncTask<String, Void, List<Student>> {

    private AsyncResponse<List<Student>> callback;

    public ConnectionAsyncTask(AsyncResponse<List<Student>> callback) {
        this.callback = callback;
    }

    @Override
    protected List<User> doInBackground(String... params) {
        String url = params[0];
        final List<Student> students = new ArrayList<Student>();

        // TODO: JSON stuff
        return students;
    }

    @Override
    protected void onPostExecute(List<Student> result) {
        if (this.callback != null) {
            this.callback.onResponse(result);
        } else {
            Log.w("ConnectionAsyncTask", "Ignoring result");
        }
    }
}
public class SampleViewPagerActivity extends Activity {

    private ViewPager pager;
    private PagerAdapter adapter;
    private ArrayList<Student> students;
    private ProgressDialog progress;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 1. Inflate a layout
        setContentView(R.layout.viewpager_activity);

        // 2. Initialize the views
        this.pager = (ViewPager) findViewById(R.id.pager);
        this.progress = new ProgressDialog(this);
        this.progress.setTitle("Loading");
        this.progress.setMessage("Please wait");

        // 3. Populate the views with data
        this.students = new ArrayList<Student>();
        this.adapter = new CustomAdapter(this, students);
        this.pager.setAdapter(adapter);

        // This code runs later, after 'execute' is called and the response is returned
        ConnectionAsyncTask task = new ConnectionAsyncTask(new AsyncResponse<List<Student>>() {
            @Override
            public void onResponse(List<Student> response) {
                students.clear();
                students.addAll(response);
                adapter.notifyDataSetChanged();

                progress.hide();
            }
        });

        // Optionally show some progress while waiting
        this.progress.show();

        // TODO: Use real URL
        task.execute("http://www.somesite.com/data");
    }
}

Upvotes: 1

Related Questions