将ArrayList从AsyncTask传递给PagerAdapter

时间:2016-04-24 20:30:25

标签: android android-asynctask android-viewpager

希望你很好,

我有以下主要课程:

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数据,如下所示:

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

现在这个类会将数据返回到以下类:

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

会将获取的数据返回到以下函数中的主类(在主类中提到!)

public void DisplyOnTextView(List< Student > students) {

        List  <Student> my = students ;

    }

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

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



}

任何想法?!

谢谢,问候。

1 个答案:

答案 0 :(得分:1)

  

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

然后只需将列表作为参数传递给适配器并为其添加成员变量。这个适配器的用法在这篇文章的底部,因为我想提一些其他的东西。

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

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

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

请注意,您需要一个图片加载库(Picasso,Glide,Fresco等)才能将网址加载到ImageView。但是,关于库的主题,您可以通过查看Gson进行JSON解析以及使用JSON数据进行HTTP网络调用的Retrofit或Volley来节省大量开发时间。

至于AsyncTask的用法,传递Activity变量是不好的做法。尝试使用对Activity的异步回调。

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