Android 使用BaseAdapter复制项目自定义listview

Android 使用BaseAdapter复制项目自定义listview,android,mysql,listview,android-listview,baseadapter,Android,Mysql,Listview,Android Listview,Baseadapter,我尝试使用自定义listview扩展BaseAdapter将数据从数据库mysql显示到listview。数据库中的数据,如: tbl_用户手册: id | username | title | category ------+-----------+-----------------+------------- 1 | A | Java | 1 2 | B | VB.NE

我尝试使用自定义listview扩展BaseAdapter将数据从数据库mysql显示到listview。数据库中的数据,如:

tbl_用户手册:

    id   | username  |  title          | category
   ------+-----------+-----------------+-------------
    1    | A         |  Java           | 1
    2    | B         |  VB.NET         | 1
    3    | C         |  Swing Java     | 1
    4    | D         |  Java Hibernate | 1
    5    | E         |  C#             | 1
    6    | F         |  Ruby           | 1
    7    | G         |  MySQL          | 1
    8    | H         |  Sqlite         | 1
    9    | I         |  PHP            | 1
    10   | J         |  MsSQL          | 1
我的问题是为什么listview显示的重复项从id 1到6,数据id 7、8、9、10没有显示在listview中

Listview中显示的数据如下:

    | username  |  title          | 
    +-----------+-----------------+
    | A         |  Java           |
    | B         |  VB.NET         |
    | C         |  Swing Java     |
    | D         |  Java Hibernate |
    | E         |  C#             |
    | F         |  Ruby           |
    | A         |  Java           | < ----  duplicate starting from here
    | B         |  VB.NET         |
    | C         |  Swing Java     |
    | D         |  Java Hibernate |
|用户名|标题|
+-----------+-----------------+
|A | Java|
|B | VB.NET|
|C | Swing Java|
|D| Java Hibernate|
|E|C#|
|红宝石|
|A | Java |<----从这里开始重复
|B | VB.NET|
|C | Swing Java|
|D| Java Hibernate|
基本适配器:

public class HomeListViewAdapter extends BaseAdapter {

Context context;
ArrayList<HashMap<String, String>> userList;
HashMap<String, String> map = new HashMap<String, String>();

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

@Override
public int getCount() {
    // TODO Auto-generated method stub
    return userList.size();
}

@Override
public Object getItem(int position) {
    // TODO Auto-generated method stub
    return null;
}

@Override
public long getItemId(int position) {
    // TODO Auto-generated method stub
    return 0;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    // TODO Auto-generated method stub

    TextView tvUsername, tvTitle;

    if (convertView == null) {
        LayoutInflater layoutInflator = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        convertView = layoutInflator.inflate(R.layout.custom_listview_home, parent, false);

        map = membersList.get(position);

        tvUsername = (TextView) convertView.findViewById(R.id.tvUsername);
        tvTitle = (TextView) convertView.findViewById(R.id.tvTitle);

        tvUsername.setText(map.get(FragmentHome.USERNAME));
        tvTitle.setText(map.get(FragmentHome.TITLE));

    }
    return convertView;
公共类HomeListViewAdapter扩展了BaseAdapter{
语境;
ArrayList用户列表;
HashMap=newHashMap();
公共HomeListViewAdapter(上下文,
ArrayList(ArrayList){
this.context=上下文;
userList=arraylist;
}
@凌驾
public int getCount(){
//TODO自动生成的方法存根
返回userList.size();
}
@凌驾
公共对象getItem(int位置){
//TODO自动生成的方法存根
返回null;
}
@凌驾
公共长getItemId(int位置){
//TODO自动生成的方法存根
返回0;
}
@凌驾
公共视图getView(int位置、视图转换视图、视图组父视图){
//TODO自动生成的方法存根
TextView tvUsername,tvTitle;
if(convertView==null){
LayoutInflater layoutInflator=(LayoutInflater)上下文
.getSystemService(上下文布局\充气机\服务);
convertView=LayoutFlator.inflate(R.layout.custom\u listview\u home,parent,false);
map=membersList.get(位置);
tvUsername=(TextView)convertView.findViewById(R.id.tvUsername);
tvTitle=(TextView)convertView.findViewById(R.id.tvTitle);
setText(map.get(FragmentHome.USERNAME));
setText(map.get(FragmentHome.TITLE));
}
返回视图;
碎片

public class FragmentHome extends SherlockFragment {

public static String USERNAME = "username";
public static String TITLE = "title";

private ProgressDialog pDialog; 
JSONPostGet jPostget = new JSONPostGet();
JSONArray users = null;
ArrayList<HashMap<String, String>> userList;

private static String url_getbook = "http://....../get_userbook.php";

ListView list;
HomeListViewAdapter homeadapter;

private static final String KEY_SUCCESS = "success";
private static final String KEY_USERS = "users";
private static final String KEY_USERNAME = "username";
private static final String KEY_TITLE = "title";

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_home, container, false);
    userList = new ArrayList<HashMap<String,String>>();
    new LoadUserBook().execute();
    return rootView;
}

class LoadUserBook extends AsyncTask<String, String, String> {

    @Override
    protected void onPreExecute() {
        // TODO Auto-generated method stub
        super.onPreExecute();
        pDialog = new ProgressDialog(getActivity());
        pDialog.setMessage("Please wait....");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(true);
        pDialog.show();
    }

    @Override
    protected String doInBackground(String... args) {
        // TODO Auto-generated method stub
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("category", "1"));
        JSONObject json = jPostget.makeHttpRequest(url_getbook, "GET", params);
        Log.d("All News Feed: ", json.toString());
        try {
            int success = json.getInt(KEY_SUCCESS);
            if (success == 1) {
                users = json.getJSONArray(KEY_USERS);
                for (int i = 0; i < users.length(); i++) {
                    JSONObject c = users.getJSONObject(i);

                    String suname = c.getString(KEY_USERNAME);
                    String stitle = c.getString(KEY_TITLE);

                    HashMap<String, String> map = new HashMap<String, String>();
                    map.put(KEY_USERNAME, suname);
                    map.put(KEY_TITLE, stitle);

                    userList.add(map);
                }
            } else {
                // ...
            }
        } catch (JSONException e) {
            // TODO: handle exception
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(String result) {
        // TODO Auto-generated method stub
        pDialog.dismiss();
        try {
            getActivity().runOnUiThread(new Runnable() {

                @Override
                public void run() {
                    // TODO Auto-generated method stub      
                    list = (ListView) getView().findViewById(R.id.listview1);
                    homeadapter = new HomeListViewAdapter(getActivity(), userList);
                    list.setAdapter(homeadapter);
                    homeadapter.notifyDataSetChanged();
                }
            });
        } catch (Exception e) {
            // TODO: handle exception
        }
    }
}
公共类FragmentHome扩展了SherlockFragment{
公共静态字符串USERNAME=“USERNAME”;
公共静态字符串TITLE=“TITLE”;
私人对话;
JSONPostGet jPostget=新的JSONPostGet();
JSONArray用户=null;
ArrayList用户列表;
私有静态字符串url_getbook=”http://....../get_userbook.php";
列表视图列表;
HomeListViewAdapter homeadapter;
私有静态最终字符串密钥\u SUCCESS=“SUCCESS”;
私有静态最终字符串KEY_USERS=“USERS”;
私有静态最终字符串密钥\u USERNAME=“USERNAME”;
私有静态最终字符串键\u TITLE=“TITLE”;
@凌驾
创建视图上的公共视图(布局、充气机、视图组容器、,
Bundle savedInstanceState){
视图根视图=充气机。充气(R.layout.fragment\u home,container,false);
userList=newarraylist();
新建LoadUserBook().execute();
返回rootView;
}
类LoadUserBook扩展了AsyncTask{
@凌驾
受保护的void onPreExecute(){
//TODO自动生成的方法存根
super.onPreExecute();
pDialog=newprogressdialog(getActivity());
pDialog.setMessage(“请稍候…”);
pDialog.setUndeterminate(假);
pDialog.setCancelable(真);
pDialog.show();
}
@凌驾
受保护的字符串doInBackground(字符串…args){
//TODO自动生成的方法存根
List params=new ArrayList();
参数添加(新的BasicNameValuePair(“类别”,“1”));
JSONObject json=jPostget.makeHttpRequest(url_getbook,“GET”,参数);
Log.d(“所有新闻提要:,json.toString());
试一试{
int success=json.getInt(KEY_success);
如果(成功==1){
users=json.getJSONArray(键用户);
对于(int i=0;i
}


请帮助。感谢advance

您的
getView
实现不正确。请尝试此操作-

  @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // TODO Auto-generated method stub

        TextView tvUsername, tvTitle;

        if (convertView == null) {
            LayoutInflater layoutInflator = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

            convertView = layoutInflator.inflate(R.layout.custom_listview_home, parent, false);   
        }


            map = membersList.get(position);

            tvUsername = (TextView) convertView.findViewById(R.id.tvUsername);
            tvTitle = (TextView) convertView.findViewById(R.id.tvTitle);

            tvUsername.setText(map.get(FragmentHome.USERNAME));
            tvTitle.setText(map.get(FragmentHome.TITLE));

        return convertView;
}

您的
getView
实现不正确。请尝试此操作-

  @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // TODO Auto-generated method stub

        TextView tvUsername, tvTitle;

        if (convertView == null) {
            LayoutInflater layoutInflator = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

            convertView = layoutInflator.inflate(R.layout.custom_listview_home, parent, false);   
        }


            map = membersList.get(position);

            tvUsername = (TextView) convertView.findViewById(R.id.tvUsername);
            tvTitle = (TextView) convertView.findViewById(R.id.tvTitle);

            tvUsername.setText(map.get(FragmentHome.USERNAME));
            tvTitle.setText(map.get(FragmentHome.TITLE));

        return convertView;
}
我认为getItem()应该在onCreateView中返回userlist.get(position)和 map=membersList.get(位置);
应该是
ap=userlist.get(位置)

另一件事是当convert view不为null时缺少else子句。

我认为getItem()应该返回userlist.get(position)和onCreateView中的
map=membersList.get(位置);
应该是
ap=userlist.get(位置)

另一件事是当convert view不为null时,else子句丢失。

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    // TODO Auto-generated method stub

    TextView tvUsername, tvTitle;

    if (convertView == null) {
        LayoutInflater layoutInflator = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        convertView = layoutInflator.inflate(R.layout.custom_listview_home, parent, false);




    }else{
       LayoutInflater layoutInflator = convertView;

    }

     map = membersList.get(position);

        tvUsername = (TextView) convertView.findViewById(R.id.tvUsername);
        tvTitle = (TextView) convertView.findViewById(R.id.tvTitle);

        tvUsername.setText(map.get(FragmentHome.USERNAME));
        tvTitle.setText(map.get(FragmentHome.TITLE));

    return convertView;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub

TextView tvUsername, tvTitle;

if (convertView == null) {
    LayoutInflater layoutInflator = (LayoutInflater) context
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    convertView = layoutInflator.inflate(R.layout.custom_listview_home, parent, false);



    tvUsername = (TextView) convertView.findViewById(R.id.tvUsername);
    tvTitle = (TextView) convertView.findViewById(R.id.tvTitle);



}
map = membersList.get(position);
tvUsername.setText(map.get(FragmentHome.USERNAME));
    tvTitle.setText(map.get(FragmentHome.TITLE));
return convertView;
}
            // get the layout inflater

            LayoutInflater mLayoutInflater = (LayoutInflater) getApplicationContext()
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

            // create a ViewHolder reference
            ViewHolder holder = null;

            // check to see if the reused view is null or not, if is not
            // null then reuse it

            if (view == null) {
                holder = new ViewHolder();
                // check to see if the reused view is null or not, if is not
                // null then reuse it
                if (view == null) {
                    holder = new ViewHolder();

                    view = mLayoutInflater.inflate(
                            R.layout.listview_values, null);
                    holder.txt_date = (TextView) view
                            .findViewById(R.id.t_date);
                    holder.txt_intime = (TextView) view
                            .findViewById(R.id.txt_intime);
                    holder.txt_outtime = (TextView) view
                            .findViewById(R.id.txt_outtime);

                    // the setTag is used to store the data within this view
                    view.setTag(holder);
                } else {
                    // the getTag returns the viewHolder object set as a tag
                    // to the view
                    holder = (ViewHolder) view.getTag();
                    view = mLayoutInflater.inflate(
                            R.layout.listview_values, parent, false);
                }

            }
            // get the string item from the position "position" from array
            // list to put it on the TextView
            String date = attendence_webdata.get(position).get("A_date")
                    .toString();
            String intime = attendence_webdata.get(position)
                    .get("Ain_time").toString();
            String outtime = attendence_webdata.get(position)
                    .get("out_time").toString();
            if (date != null) {
                if (holder.txt_date != null) {
                    // set the item name on the TextView
                    holder.txt_date.setText(date);
                }
            }
            if (intime != null) {
                if (holder.txt_intime != null) {
                    // set the item name on the TextView
                    holder.txt_intime.setText(intime);
                }
            }
            if (outtime != null) {
                if (holder.txt_outtime != null) {
                    // set the item name on the TextView
                    holder.txt_outtime.setText(outtime);
                }
            }

            // this method must return the view corresponding to the data at
            // the specified position.
            return view;

        }
    }

}

/**
 * Static class used to avoid the calling of "findViewById" every time the
 * getView() method is called, because this can impact to your application
 * performance when your list is too big. The class is static so it cache
 * all the things inside once it's created.
 */
private static class ViewHolder {
    private TextView txt_outtime;
    private TextView txt_intime;
    private TextView txt_date;

}

@Override
public void onBackPressed() {
    // TODO Auto-generated method stub
    super.onBackPressed();
    attendence_webdata.clear();// where attendence_webdata is arraylistname
    list.setAdapter(null);     //where list is your listview name
}
public View getView(int position, View convertView, ViewGroup parent) {
    LayoutInflater inflater = (LayoutInflater) context
        .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View gridView;
    if (convertView == null) {
        gridView = new View(context);
    } else {
        gridView = (View) convertView;
    }
    gridView = inflater.inflate(R.layout.worker_listmain, null);
    // your source code here!!! Run 100%
    return gridView;
}