Android viewpager 以 Android 中的数组大小显示索引中的最后一个值

Android viewpager showing last value in the index in the size of array in Android

我正在从 http 服务器获取数据,我能够显示 json 索引的最后一个值,但是,我无法在 viewpager 中显示我的 json 数组中的所有值.请验证我的代码并给我一个解决方案。 提前致谢

package com.example.vasundharaapp;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.squareup.picasso.Picasso;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

@SuppressWarnings("deprecation")
public class MainActivity extends ActionBarActivity {
     static final int NUM_ITEMS = 8;
        AdapterTask adapter;
        ViewPager viewPager;
        ProgressDialog progressDialog;
        List<Channels> channelData;
        String URl="http://172.17.22.21:925/api/homepage/gethomescroll";
        JSONObject json;
        JSONArray chanlarray;
 String artimage,articaleTitle,articaleSdec,articaldec,aricaleId,articlThumImage;

       ImageView anubandam,yuvatharang,beauty,dheera,events,ghumaghumalu,glomer,sweethome,work; 
        String[] resul;
        Timer timer;
        int page = 1;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        viewPager = (ViewPager) findViewById(R.id.pager);
        anubandam=(ImageView) findViewById(R.id.anubandam);
        yuvatharang=(ImageView) findViewById(R.id.Yuva);
        beauty=(ImageView) findViewById(R.id.beauty);
        dheera=(ImageView) findViewById(R.id.dheera);
        events=(ImageView) findViewById(R.id.events);
        ghumaghumalu=(ImageView) findViewById(R.id.ghumagumalu);
        glomer=(ImageView) findViewById(R.id.glamor);
        sweethome=(ImageView) findViewById(R.id.sweet);
        work=(ImageView) findViewById(R.id.work);
        startProgressDialog();
        getChannels();
    beauty.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                Intent i=new Intent(MainActivity.this,BeautyActivity.class);
                startActivity(i);
            }
        });

    }
    private void getChannels() {

         new Thread()
         {

             public void run() {
                 System.out.println("running");
                 String responce=SendRequest.GET(URl);
                 Log.d("responce", responce);
                 channelData=parseJSON(responce);
                 Message msg=new Message();
                 msg.arg1 = 1;
                 handler.sendMessage(msg);                       
             }      
         }.start();


    }
     private List<Channels> parseJSON(String responce) {
            // TODO Auto-generated method stub      
         List<Channels> chanel = new ArrayList<Channels>();
         try {
                chanlarray = new JSONArray(responce);
                for (int i = 0; i < chanlarray.length(); i++) {
                    JSONObject channelName=chanlarray.getJSONObject(i);
                    String image = channelName.getString("articlethumbimg");
                    String title = channelName.getString("articletitle");
                    String article=channelName.getString("articleshortdec");
                    //channelData.add(new Channels(image, title,article));

                }

            } catch (JSONException e1) {
                e1.printStackTrace();
            }           
            return chanel;
        };



     private final Handler handler = new Handler() {

            public void handleMessage(Message msg)
            {
                stopProgressDialog();
                adapter = new AdapterTask(chanlarray,MainActivity.this);
                viewPager.setAdapter(adapter);
                pageSwitcher(4);

            }

        };


    private void startProgressDialog() {
        progressDialog = new ProgressDialog(this);
        progressDialog.setMessage("Please wait..");
        progressDialog.show();
    }

    private void stopProgressDialog() {
        if (progressDialog != null && progressDialog.isShowing())
            progressDialog.dismiss();
    }

@Override
protected void onResume() {
    // TODO Auto-generated method stub

    super.onResume();
}
    @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();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
    public void pageSwitcher(int seconds) {
        timer = new Timer(); // At this line a new Thread will be created
        timer.scheduleAtFixedRate(new RemindTask(), 0, seconds * 1000); // delay
                                                                        // in
        // milliseconds
    }

        // this is an inner class...
    class RemindTask extends TimerTask {

        @Override
        public void run() {

            // As the TimerTask run on a seprate thread from UI thread we have
            // to call runOnUiThread to do work on UI thread.
            runOnUiThread(new Runnable() {
                public void run() {

                    if (page > 8) { // In my case the number of pages are 5
                        viewPager.setCurrentItem(1);
                        page=1;

                    } else {
                        viewPager.setCurrentItem(page++);
                    }
                }
            });

        }
    }
    class AdapterTask extends PagerAdapter{
        Context context;
        String redu[];
        JSONArray article;
        LayoutInflater inflater;
        private List<Channels> articlelist;
        AdapterTask(JSONArray article, Context context) {
            this.context = context;
            this.article = article;
            //this.content=content;
        }
        @Override
        public int getCount() {
            // TODO Auto-generated method stub
            return article.length();
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            // TODO Auto-generated method stub
            return view == ((RelativeLayout) object);
        }
        @Override
        public Object instantiateItem(ViewGroup container, final int position) {
            ImageView imgflag;
            TextView txt,title;

            inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            View itemView = inflater.inflate(R.layout.fashionzone, container,
                    false); 
            Typeface tf = Typeface.createFromAsset(getAssets(), "fonts/eenadu.ttf");
            imgflag = (ImageView) itemView.findViewById(R.id.flag);
            txt=(TextView) itemView.findViewById(R.id.atext);
            title=(TextView) itemView.findViewById(R.id.atitle);


            for (int j = 0; j < chanlarray.length(); j++) {

                try {
                    JSONObject channelName = chanlarray.getJSONObject(j);
                    aricaleId=channelName.getString("articleId");
                    articaleTitle=channelName.getString("articletitle");
                    articaleSdec=channelName.getString("articleshortdec");
                    artimage=channelName.getString("articleimage");
                    articlThumImage=channelName.getString("articlethumbimg");
                    articaldec=channelName.getString("articledec"); 
                    title.setTypeface(tf);
                    txt.setTypeface(tf);
                    title.setText(articaleTitle);   
                    txt.setText(articaleSdec);
                    try{
                        Picasso.with(MainActivity.this).load(articlThumImage).into(imgflag);
                        }catch(Exception e)
                        {
                            e.printStackTrace();
                        }
                } catch (JSONException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }

}

            ((ViewPager) container).addView(itemView);
            imgflag.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    Intent i=new Intent(MainActivity.this,DetailsActivity.class);
                    //Bitmap bmp = flag[position];
                    i.putExtra("image", artimage);
                    i.putExtra("txt",articaldec );
                    startActivity(i);
                }
            });

            txt.setOnClickListener(new OnClickListener() {              
                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    Intent i=new Intent(MainActivity.this,DetailsActivity.class);
                    //Bitmap bmp = flag[position];
                    i.putExtra("image", artimage);
                    i.putExtra("txt",articaldec );
                    startActivity(i);
                }
            });

            return itemView;
        }
          @Override
            public void destroyItem(View container, int position, Object object) {
                 ((ViewPager) container).removeView((View) object);
            }


    }

    public class Channels {

        private String image;
        private String title;
        private String desc;

    }

}

我强烈建议您避免将 json 解析为 instantiateItemAdapter 应该接收 Collection 个项目,通常像数据集一样引用,并从中膨胀视图。这样你就必须付出解析时间,延迟视图的绘制。要解决您的问题,您必须从 instantiateItem 中删除 for 循环。 instantiateItem 被调用 getCount 次,您必须使用参数 position 从 json 中获取要表示的项目。将 for 循环替换为

JSONObject channelName = article.getJSONObject(positon);