将ArrayList从AsyncTask传递给PagerAdapter [英] Passing ArrayList from AsyncTask to PagerAdapter

查看:94
本文介绍了将ArrayList从AsyncTask传递给PagerAdapter的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

希望你一切都好

我有以下主要课程:

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 ;

    }             
}

当我运行应用程序时,此主要活动将使用另一个类从链接中读取json数据,如下所示:

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);
        }
   }
}

此行:((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 ;

    }

现在我想要的是将此列表传递给以下类,以便在viewPager的imageView和textView中使用它,而不是在类中使用预定义的数据:

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);
    }



}

有什么主意吗?!

谢谢.

推荐答案

我想要将此列表传递给以下类,以便在viewPager的imageView和textView中使用它

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;
    }

如果要在instantiateItem方法中使用该data变量,则可以执行Student s = this.data.get(position);并在Student对象上使用各种方法来加载TextViewImageView.

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.

请注意,您需要一个图像加载库(Picasso,Glide,Fresco等)才能将URL加载到ImageView中.不过,尽管是关于库的话题,但您可以通过研究Gson进行JSON解析和Retrofit或Volley进行带有JSON数据的HTTP网络调用来节省大量开发时间.

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.

对于AsyncTask的用法,在Activity变量周围传递是不好的做法.尝试改用对Activity的异步回调.

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");
    }
}

这篇关于将ArrayList从AsyncTask传递给PagerAdapter的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆