【问题标题】:android endless scroll using custom adapter (text, images) from json url, not adding second page items to list viewandroid无限滚动使用来自json url的自定义适配器(文本,图像),不将第二页项目添加到列表视图
【发布时间】:2013-12-30 13:12:31
【问题描述】:

谁能告诉我如何使用一些自定义适配器(加载文本和图像)为列表视图实现无限滚动。下面是我试过的代码,它加载了第一页而不是第二页,检查了滚动触发事件它工作正常,

注意:(在此示例中,我尝试再次加载相同的 json 数据以进行测试)

提前非常感谢!!

MainActivity.java

public class MainActivity extends Activity implements EndlessListener {
TextView ver;
TextView name;
TextView api;

EndlessAdapter oEndlessAdapter;
EndlessListView oEndlessListView;

//URL to get JSON Array
private static String url = "http://api.learn2crack.com/android/jsonos/";

//JSON Node Names 
private static final String TAG_OS = "android";
public static final String TAG_VER = "ver";
public static final String TAG_NAME = "name";
public static final String TAG_API = "api";

JSONArray android = null;
int iPageNo = 1;

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

    oEndlessListView = (EndlessListView) findViewById(R.id.list);

    //EndlessAdapter adp = new EndlessAdapter(this, getDataFrmJson(iPageNo));
    //oEndlessListView.setLoadingView(R.layout.loading_layout);
    //oEndlessListView.setAdapter(adp);
    new JSONParse().execute();
}


private class JSONParse extends AsyncTask<String, String, ArrayList<HashMap<String, String>>> {
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
         ver = (TextView)findViewById(R.id.vers);
         name = (TextView)findViewById(R.id.name);
         api = (TextView)findViewById(R.id.api);
    }

    @Override
    protected ArrayList<HashMap<String, String>> doInBackground(String... args) {
        Log.i("KUMAR", "Calling doInBackground()");
        ArrayList<HashMap<String, String>> list = getDataFrmJson(iPageNo);
        return list;
    }
     @Override
     protected void onPostExecute(ArrayList<HashMap<String, String>> list) {
         try {
             int currentPosition = oEndlessListView.getFirstVisiblePosition(); 
             if( iPageNo == 1 ) {
                 oEndlessAdapter = new EndlessAdapter(MainActivity.this, list);
                 oEndlessListView.setLoadingView(R.layout.loading_layout);
                 oEndlessListView.setAdapter(oEndlessAdapter);
                 oEndlessListView.setListener(MainActivity.this);
                 iPageNo++;
             }else {
                oEndlessAdapter = new EndlessAdapter(MainActivity.this, list);
                oEndlessListView.setAdapter(oEndlessAdapter);
             }
            oEndlessListView.setSelectionFromTop(currentPosition + 1, 0);
        } catch (Exception e) {
            e.printStackTrace();
        }
     }
}

public ArrayList<HashMap<String, String>> getDataFrmJson(int page) {
    ArrayList<HashMap<String, String>> osList = new ArrayList<HashMap<String, String>>();
    try {

        JSONParser jParser = new JSONParser();
        JSONObject json = jParser.getJSONFromUrl(url);

        android = json.getJSONArray(TAG_OS);
        for (int i = 0; i < android.length(); i++) {
            JSONObject c = android.getJSONObject(i);

            // Storing JSON item in a Variable
            String ver = c.getString(TAG_VER);
            String name = c.getString(TAG_NAME);
            String api = c.getString(TAG_API);

            // Adding value HashMap key => value
            HashMap<String, String> map = new HashMap<String, String>();

            map.put(TAG_VER, ver);
            map.put(TAG_NAME, name);
            map.put(TAG_API, api);

            osList.add(map);
        }
    }catch(JSONException je) {
        je.printStackTrace();
    }
    return osList;
}

@Override
public void loadData() {
    new JSONParse().execute();
}

}}

EndlessListView.java

{public class EndlessListView extends ListView implements OnScrollListener {

private View footer;
private boolean isLoading;
private EndlessListener listener;
private EndlessAdapter adapter;

public EndlessListView(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);    
    this.setOnScrollListener(this);
}

public EndlessListView(Context context, AttributeSet attrs) {
    super(context, attrs);
    this.setOnScrollListener(this);
}

public EndlessListView(Context context) {
    super(context);     
    this.setOnScrollListener(this);
}

public void setListener(EndlessListener listener) {
    this.listener = listener;
}

@Override
public void onScroll(AbsListView view, int firstVisibleItem,
        int visibleItemCount, int totalItemCount) {

    if (getAdapter() == null)
        return ;

    if (getAdapter().getCount() == 0)
        return ;

    int l = visibleItemCount + firstVisibleItem;

    //Log.i("KUMAR", "list size: " + l);
    //Log.i("KUMAR", "isLoading status: " + Boolean.toString(isLoading));


    if (l >= totalItemCount && !isLoading) {
        Log.i("KUMAR", "totalItemCount: " + totalItemCount);
        // It is time to add new data. We call the listener
        this.addFooterView(footer);
        isLoading = true;
        Log.i("KUMAR", "Calling loadData()");
        listener.loadData();
    }
}

@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {}

public void setLoadingView(int resId) {
    Log.i("KUMAR", "Calling setLoadingView()");
    LayoutInflater inflater = (LayoutInflater) super.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    footer = (View) inflater.inflate(resId, null);
    this.addFooterView(footer);

}


public void setAdapter(EndlessAdapter adapter) {        
    Log.i("KUMAR", "Calling setAdapter()");
    super.setAdapter(adapter);
    this.adapter = adapter;
    this.removeFooterView(footer);
}


public void addNewData(EndlessAdapter eAdp) {
    this.removeFooterView(footer);
    setAdapter(eAdp);
    this.adapter.notifyDataSetChanged();
    isLoading = false;
}


public EndlessListener setListener() {
    return listener;
}


public static interface EndlessListener {
    public void loadData() ;
}

}

EndlessAdapter.java

    {public class EndlessAdapter extends BaseAdapter {

    private Activity activity;
    private ArrayList<HashMap<String, String>> data;
    private static LayoutInflater inflater=null;


    public EndlessAdapter(Activity a, ArrayList<HashMap<String, String>> d) {
        activity = a;
        data=d;
        inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        //imageLoader=new ImageLoader(activity.getApplicationContext());
    }

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

    public Object getItem(int position) {
        return position;
    }

    public long getItemId(int position) {
        return position;
    }

    public View getView(int position, View convertView, ViewGroup parent) {
        View view = convertView;

        if(convertView==null) {
            view = inflater.inflate(R.layout.list_v, null);
        }

        TextView title = (TextView)view.findViewById(R.id.vers); // title
        TextView artist = (TextView)view.findViewById(R.id.name); // artist name
        TextView duration = (TextView)view.findViewById(R.id.api); // duration
        ImageView thumb_image=(ImageView)view.findViewById(R.id.imageView1); // thumb image

        HashMap<String, String> version = new HashMap<String, String>();
        version = data.get(position);

        // Setting all values in listview
        title.setText(version.get(MainActivity.TAG_VER));
        artist.setText(version.get(MainActivity.TAG_NAME));
        duration.setText(version.get(MainActivity.TAG_API));
        UrlImageViewHelper.setUrlDrawable(thumb_image, "http://romio.com/assets/images/qa/noprofpicF480x480.png", R.drawable.loading);

        return view;
    }
}}

activity_main.xml

    {<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <com.example.androidhive.EndlessListView
        android:id="@+id/list"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_above="@+id/getdata"
        android:divider="@android:color/transparent"
        android:dividerHeight="5dp" />

   <!--  <Button
        android:id="@+id/getdata"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="23dp"
        android:text="@string/bnt_load" /> -->

</RelativeLayout>}

list_v.xml 
    {<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:padding="10dp"
    android:background="@drawable/border"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/vers"
        android:layout_width="200dp"
        android:layout_height="wrap_content"
        android:layout_marginLeft="15dp"
        android:layout_marginTop="5dp"
        android:hint="@string/ph_version_no"
        android:textColor="@color/color_black"
        android:textSize="25sp" 
        android:textStyle="bold"
        android:layout_toRightOf="@+id/imageView1"
    />

    <TextView
        android:id="@+id/name"
        android:layout_width="150dp"
        android:layout_height="wrap_content"
        android:layout_marginLeft="15dp"
        android:hint="@string/ph_version_name"
        android:textColor="@color/color_red"
        android:layout_toRightOf="@+id/imageView1"
        android:layout_below="@+id/vers"
        android:textSize="15sp"
        android:textStyle="bold" />

    <TextView
        android:id="@+id/api"
        android:layout_width="150dp"
        android:layout_height="wrap_content"
        android:layout_marginBottom="10dp"
        android:layout_marginLeft="15dp"
        android:hint="@string/ph_version_api"
        android:textColor="@color/color_black"
        android:textSize="14sp"
        android:layout_toRightOf="@+id/imageView1"
        android:layout_below="@+id/name" />

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="60dp"
        android:layout_height="71dp"
        android:layout_alignParentLeft="true"
        android:layout_alignTop="@+id/vers"
        android:contentDescription="@string/img_content_desc"
        android:src="@drawable/img_sample" />

</RelativeLayout>}

【问题讨论】:

  • 在您的postExecute 方法中,您使用新的itens(并且只有新的itens)重新创建适配器,并在iPageNo != 1 时替换以前的适配器(具有以前的itens)。在这种情况下,您应该将新的项添加到以前的适配器中,而不是替换以前的。
  • 你找到解决方案了吗?

标签: android android-listview scrollview


【解决方案1】:

因为每次下载列表数据并将新数据替换为 Arraylist 中的旧数据。您应该将新的 json 数据添加到当前的数组列表中。很快将ArrayList&lt;HashMap&lt;String, String&gt;&gt; list; 设为全局并将所有新数据添加到此全局列表中。

【讨论】:

    猜你喜欢
    • 2014-07-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多