将两个asynk任务组合在一个活动中,为两个viewpager共享同一个适配器

时间:2016-01-18 17:08:30

标签: android android-asynctask android-viewpager

我想为2个viewpager添加两个asynk任务,需要在主活动中将两个代码组合在一起。当我添加一个asynk任务运行时。我在xml文件名pager和pager2中添加了两个viewpager视图。

我可以为viewpager使用相同的适配器,因为json文件中的值相同吗?

    public class MainActivity extends AppCompatActivity
            implements NavigationView.OnNavigationItemSelectedListener {

        ViewPager viewPager;
        PagerAdapter pagerAdapter;

        JSONObject jsonobject;
        JSONArray jsonarray;

        ProgressDialog mProgressDialog;
        ArrayList<HashMap<String, String>> arraylist = new ArrayList<HashMap<String, String>>();

        static String FILMNAME = "film";
        static String FILMPOSTER = "poster";
    viewPager = (ViewPager) findViewById(R.id.pager);

        viewPager.setClipToPadding(false);
        viewPager.setPadding(4, 0, 4, 0);

        new DownloadJSON().execute();
// DownloadJSON AsyncTask
    private class DownloadJSON extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            mProgressDialog = new ProgressDialog(MainActivity.this);
            mProgressDialog.setTitle("eFilmsWorld");
            mProgressDialog.setMessage("Loading...");
            mProgressDialog.setIndeterminate(false);
            mProgressDialog.show();
        }

        @Override
        protected Void doInBackground(Void... params) {
            // Create an array
            arraylist = new ArrayList<HashMap<String, String>>();
            // Retrieve JSON Objects from the given URL address


jsonobject = new JSONfunctions().getJSONfromURL("/upcomingFilms.php");

            try {
                // Locate the array name in JSON
                jsonarray = jsonobject.getJSONArray("upcomingFilms");

                for (int i = 0; i < jsonarray.length(); i++) {
                    HashMap<String, String> map = new HashMap<String, String>();
                    jsonobject = jsonarray.getJSONObject(i);
                    // Retrive JSON Objects
                    map.put("film", jsonobject.getString("filmName"));
                    map.put("poster", jsonobject.getString("path"));
                    // Set the JSON Objects into the array
                    arraylist.add(map);
                }
            } catch (JSONException e) {
                Log.e("Error", e.getMessage());
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void args) {

            pagerAdapter = new ViewPagerAdapter(MainActivity.this, arraylist);
            viewPager.setAdapter(pagerAdapter);
            mProgressDialog.dismiss();
        }
    }

我想在上面的代码中添加一个asynk任务,因为我正在运行两个viewpager,一个用于即将上映的电影,第二个用于影院中的电影: 第二个asynk任务是:

// DownloadJSON2 AsyncTask
private class DownloadJSON2 extends AsyncTask<Void, Void, Void> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        mProgressDialog = new ProgressDialog(MainActivity.this);
        mProgressDialog.setTitle("eFilmsWorld");
        mProgressDialog.setMessage("Loading...");
        mProgressDialog.setIndeterminate(false);
        mProgressDialog.show();
    }

    @Override
    protected Void doInBackground(Void... params) {
        // Create an array
        arraylist = new ArrayList<HashMap<String, String>>();
        // Retrieve JSON Objects from the given URL address
        jsonobject = new JSONfunctions()
                .getJSONfromURL("/filmsIntheatres.php");

        try {
            // Locate the array name in JSON
            jsonarray = jsonobject.getJSONArray("filmsIntheatres");

            for (int i = 0; i < jsonarray.length(); i++) {
                HashMap<String, String> map = new HashMap<String, String>();
                jsonobject = jsonarray.getJSONObject(i);
                // Retrive JSON Objects
                map.put("film", jsonobject.getString("filmName"));
                map.put("poster", jsonobject.getString("path"));
                // Set the JSON Objects into the array
                arraylist.add(map);
            }
        } catch (JSONException e) {
            Log.e("Error", e.getMessage());
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(Void args) {

        pagerAdapter = new ViewPagerAdapter(MainActivity.this, arraylist);
        viewPager.setAdapter(pagerAdapter);
        mProgressDialog.dismiss();
    }
}

PagerAdapter代码:

public class ViewPagerAdapter extends PagerAdapter {
    Context context;
    LayoutInflater inflater;
    ArrayList<HashMap<String, String>> data;


HashMap<String, String> resultp = new HashMap<String, String>();

public ViewPagerAdapter(Context context,
                   ArrayList<HashMap<String, String>> arraylist) {
    this.context = context;
    this.data = arraylist;
}

@Override
public int getCount() {
    return data.size();
}

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

@Override
public Object instantiateItem(ViewGroup container, int position) {
    resultp = data.get(position);

    // Declare Variables
    TextView tvFilm;
    ImageView ivPoster;

    inflater = (LayoutInflater) context
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View itemView = inflater.inflate(R.layout.viewpager_item, container, false);

    // Locate the TextViews in viewpager_item.xml
    tvFilm = (TextView) itemView.findViewById(R.id.filmnamePager);
    ivPoster = (ImageView) itemView.findViewById(R.id.filmposterPager);
    //Log.e("filmdetails", "Item "+data.get(position).get(MainActivity.FILMNAME));
    // Capture position and set to the TextViews
    tvFilm.setText(resultp.get(MainActivity.FILMNAME));

    Uri posterUri = Uri.parse(resultp.get(MainActivity.FILMPOSTER));

    Picasso.with(ViewPagerAdapter.this.context)
            .load(posterUri)
            .placeholder(R.drawable.coming_soon_placeholder)
            .error(R.drawable.coming_soon_placeholder)
            .into(ivPoster);

    // Add viewpager_item.xml to ViewPager
    ((ViewPager) container).addView(itemView);

    return itemView;
}

@Override
public void destroyItem(ViewGroup container, int position, Object object) {
    // Remove viewpager_item.xml from ViewPager
    ((ViewPager) container).removeView((LinearLayout) object);

}
}

1 个答案:

答案 0 :(得分:0)

我使用两个asynk任务在mainactivity中使用了两个viewpager适配器。它可以帮助某人使用代码,以回答我自己的问题

此代码中使用的资源: Json asynk任务 viewpager

MainActivity

public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {

    ViewPager viewPager;
    ViewPager viewPager2;
    PagerAdapter pagerAdapter;
    PagerAdapter pagerAdapter2;

    JSONObject jsonobject;
    JSONArray jsonarray;

    ProgressDialog mProgressDialog;
    ProgressDialog mProgressDialog2;

    ArrayList<HashMap<String, String>> arraylist = new ArrayList<HashMap<String, String>>();
    ArrayList<HashMap<String, String>> arraylist2 = new ArrayList<HashMap<String, String>>();

    static String FILMNAME = "film";
    static String FILMPOSTER = "poster";

    static String FILMNAME2 = "film2";
    static String FILMPOSTER2 = "poster2";


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setLogo(R.mipmap.ic_launcher);

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);

        Button upcomingFilms = (Button)findViewById(R.id.upcomingFilms);
        upcomingFilms.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                goToUpcomingFilmsActivity();
            }
        });

        Button filmsInTheatres = (Button)findViewById(R.id.filmsInTheatres);
        filmsInTheatres.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                FilmsInTheatresActivity();
            }
        });

        viewPager = (ViewPager) findViewById(R.id.pager);
        viewPager.setClipToPadding(false);
        viewPager.setPadding(4, 0, 4, 0);

        viewPager2 = (ViewPager) findViewById(R.id.pager2);
        viewPager2.setClipToPadding(false);
        viewPager2.setPadding(4, 0, 4, 0);

        new DownloadJSON().execute();
        new DownloadJSON2().execute();
    }

    // DownloadJSON AsyncTask
    private class DownloadJSON extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            mProgressDialog = new ProgressDialog(MainActivity.this);
            mProgressDialog.setTitle("eFilmsWorld");
            mProgressDialog.setMessage("Loading...");
            mProgressDialog.setIndeterminate(false);
            mProgressDialog.show();
        }

        @Override
        protected Void doInBackground(Void... params) {
            // Create an array
            arraylist = new ArrayList<HashMap<String, String>>();
            // Retrieve JSON Objects from the given URL address
            jsonobject = new JSONfunctions()
                    .getJSONfromURL("...../upcomingFilms.php");

            try {
                // Locate the array name in JSON
                jsonarray = jsonobject.getJSONArray("upcomingFilms");

                for (int i = 0; i < jsonarray.length(); i++) {
                    HashMap<String, String> map = new HashMap<String, String>();
                    jsonobject = jsonarray.getJSONObject(i);
                    // Retrive JSON Objects
                    map.put("film", jsonobject.getString("filmName"));
                    map.put("poster", jsonobject.getString("path"));
                    // Set the JSON Objects into the array
                    arraylist.add(map);
                }
            } catch (JSONException e) {
                Log.e("Error", e.getMessage());
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void args) {

            pagerAdapter = new ViewPagerAdapter(MainActivity.this, arraylist);
            viewPager.setAdapter(pagerAdapter);
            mProgressDialog.dismiss();
        }
    }

    // DownloadJSON AsyncTask
    private class DownloadJSON2 extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            mProgressDialog2 = new ProgressDialog(MainActivity.this);
            mProgressDialog2.setTitle("eFilmsWorld");
            mProgressDialog2.setMessage("Loading...");
            mProgressDialog2.setIndeterminate(false);
            mProgressDialog2.show();
        }

        @Override
        protected Void doInBackground(Void... params) {
            // Create an array
            arraylist2 = new ArrayList<HashMap<String, String>>();
            // Retrieve JSON Objects from the given URL address
            jsonobject = new JSONfunctions()
                    .getJSONfromURL("...../filmsInTheatres.php");

            try {
                // Locate the array name in JSON
                jsonarray = jsonobject.getJSONArray("filmsInTheatres");

                for (int i = 0; i < jsonarray.length(); i++) {
                    HashMap<String, String> map = new HashMap<String, String>();
                    jsonobject = jsonarray.getJSONObject(i);
                    // Retrive JSON Objects
                    map.put("film2", jsonobject.getString("filmName"));
                    map.put("poster2", jsonobject.getString("path"));
                    // Set the JSON Objects into the array
                    arraylist2.add(map);
                }
            } catch (JSONException e) {
                Log.e("Error", e.getMessage());
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void args) {

            pagerAdapter2 = new ViewPagerAdapter2(MainActivity.this, arraylist2);
            viewPager2.setAdapter(pagerAdapter2);
            mProgressDialog2.dismiss();
        }
    }

    private void goToUpcomingFilmsActivity(){
        Intent intent = new Intent(this, UpcomingFilmsActivity.class);
        startActivity(intent);
    }
    private void FilmsInTheatresActivity(){
        Intent intent = new Intent(this, FilmsInTheatresActivity.class);
        startActivity(intent);
    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

       /* if (id == R.id.nav_camera) {
            // Handle the camera action
        } else if (id == R.id.nav_gallery) {

        } else if (id == R.id.nav_slideshow) {

        } else if (id == R.id.nav_manage) {

        } else if (id == R.id.nav_share) {

        } else if (id == R.id.nav_send) {

        }*/

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }
}

viewpager适配器1

/**
 * Created by pandeyrr on 18-Jan-16.
 */
public class ViewPagerAdapter extends PagerAdapter {
    Context context;
    LayoutInflater inflater;
    ArrayList<HashMap<String, String>> data;


HashMap<String, String> resultp = new HashMap<String, String>();

public ViewPagerAdapter(Context context,
                   ArrayList<HashMap<String, String>> arraylist) {
    this.context = context;
    this.data = arraylist;
}

@Override
public int getCount() {
    return data.size();
}

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

@Override
public Object instantiateItem(ViewGroup container, int position) {
    resultp = data.get(position);

    // Declare Variables
    TextView tvFilm;
    ImageView ivPoster;

    inflater = (LayoutInflater) context
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View itemView = inflater.inflate(R.layout.viewpager_item, container, false);
    itemView = inflater.inflate(R.layout.viewpager_item2, container, false);

    // Locate the TextViews in viewpager_item.xml
    tvFilm = (TextView) itemView.findViewById(R.id.filmnamePager);
    ivPoster = (ImageView) itemView.findViewById(R.id.filmposterPager);
    //Log.e("filmdetails", "Item "+data.get(position).get(MainActivity.FILMNAME));
    // Capture position and set to the TextViews
    tvFilm.setText(resultp.get(MainActivity.FILMNAME));

    Uri posterUri = Uri.parse(resultp.get(MainActivity.FILMPOSTER));

    Picasso.with(ViewPagerAdapter.this.context)
            .load(posterUri)
            .placeholder(R.drawable.coming_soon_placeholder)
            .error(R.drawable.coming_soon_placeholder)
            .into(ivPoster);

    // Add viewpager_item.xml to ViewPager
    ((ViewPager) container).addView(itemView);

    return itemView;
}

@Override
public void destroyItem(ViewGroup container, int position, Object object) {
    // Remove viewpager_item.xml from ViewPager
    ((ViewPager) container).removeView((LinearLayout) object);

}
}

查看寻呼机adaptor2

public class ViewPagerAdapter2 extends PagerAdapter {
    Context context;
    LayoutInflater inflater;
    ArrayList<HashMap<String, String>> data;


HashMap<String, String> resultp = new HashMap<String, String>();

public ViewPagerAdapter2(Context context,
                        ArrayList<HashMap<String, String>> arraylist) {
    this.context = context;
    this.data = arraylist;
}

@Override
public int getCount() {
    return data.size();
}

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

@Override
public Object instantiateItem(ViewGroup container, int position) {
    resultp = data.get(position);

    // Declare Variables
    TextView tvFilm;
    ImageView ivPoster;

    inflater = (LayoutInflater) context
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View itemView = inflater.inflate(R.layout.viewpager_item2, container, false);

    // Locate the TextViews in viewpager_item.xml
    tvFilm = (TextView) itemView.findViewById(R.id.filmnamePager);
    ivPoster = (ImageView) itemView.findViewById(R.id.filmposterPager);
    tvFilm.setText(resultp.get(MainActivity.FILMNAME2));

    Uri posterUri = Uri.parse(resultp.get(MainActivity.FILMPOSTER2));

    Picasso.with(ViewPagerAdapter2.this.context)
            .load(posterUri)
            .placeholder(R.drawable.coming_soon_placeholder)
            .error(R.drawable.coming_soon_placeholder)
            .into(ivPoster);

    // Add viewpager_item.xml to ViewPager
    ((ViewPager) container).addView(itemView);

    return itemView;
}

@Override
public void destroyItem(ViewGroup container, int position, Object object) {
    // Remove viewpager_item.xml from ViewPager
    ((ViewPager) container).removeView((LinearLayout) object);

}
}

activity_main中的浏览器

<android.support.v4.view.ViewPager
                android:id="@+id/pager"
                android:layout_width="wrap_content"
                android:layout_height="200dp" />

        <android.support.v4.view.ViewPager
            android:id="@+id/pager2"
            android:layout_width="wrap_content"
            android:layout_height="200dp" />

viewpager layout1

<ImageView
    android:id="@+id/filmposterPager"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentRight="true"/>

<TextView
    android:id="@+id/filmnamePager"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

viewpager layout2

<ImageView
    android:id="@+id/filmposterPager"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentRight="true"/>

<TextView
    android:id="@+id/filmnamePager"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />