如何在android中更改我的列表视图以扩展BaseAdapter?

时间:2014-04-12 19:47:18

标签: android json android-listview baseadapter

我有一个活动,使用列表视图和从mysql数据库获取后显示值应用程序工作正常,但现在我想改变列表活动扩展BaseAdapter因为我需要添加第2行文本视图。

任何人都可以帮助我做出这个改变吗?

这是我的代码

User.java

package com.devleb.loginDemo;

import java.util.Date;

public class User {

    String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Date getDate() {
        return date;
    }

    public void setDate(Date date) {
        this.date = date;
    }

    Date date;
}

CustomAdapter.java

package com.devleb.loginDemo;

import java.util.ArrayList;
import java.util.Date;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

public class CustomAdapter extends BaseAdapter {

    private static ArrayList<User> usersList;

    // private static ArrayList name, date;
    LayoutInflater layoutInflater;
    String[] userName;
    Date[] createdDate;
    Context context;

    public CustomAdapter(ArrayList<User> result, Context c) {
        usersList = result;
        context = c;

    }

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

    @Override
    public Object getItem(int arg0) {
        // TODO Auto-generated method stub
        return usersList.get(arg0);
    }

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

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

        layoutInflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View row = null;

        row = layoutInflater.inflate(R.layout.list_item, parent, false);
        TextView txtCreateDate = (TextView) row
                .findViewById(R.id.txtCreateDate);

        txtCreateDate.setText(usersList.get(position).getDate().toString());

        TextView txtName = (TextView) row.findViewById(R.id.name);

        txtName.setText(usersList.get(position).getName());
        return row;
    }

}

现在如何将此自定义适配器添加到我的UserListActivity ???

UserListActivity.java

package com.devleb.loginDemo;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.app.ListActivity;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

public class UserListActivity extends ListActivity {

    JSONParser jsonParser = new JSONParser();

    ArrayList<HashMap<String, String>> usersList;

    private static String url_display_user = "http://10.0.3.2/android_connect/display_user.php";

    // JSON Node names
    private static final String TAG_SUCCESS = "success";
    private static final String TAG_MESSAGE = "message";

    private static final String TAG_ID = "id";

    private static final String TAG_USERS = "userlist";

    private static final String TAG_USER = "user";
    private static final String TAG_DATE = "create_date";


    // private static final String TAG_NAME = "name";

    // employees JSONArray
    JSONArray users = null;

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

        usersList = new ArrayList<HashMap<String, String>>();

        new getUserList().execute();

        // getListView
        ListView lv = getListView();

        lv.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View view, int arg2,
                    long arg3) {

                // String id = ((TextView)
                // view.findViewById(R.id.uid)).getText()
                // .toString();

                // Intent in = new Intent(getBaseContext(), StatusList.class);
                // in.putExtra(TAG_ID, uid);

                // startActivity(in);
            }
        });
    }

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

        /**
         * Before starting background thread Show Progress Dialog
         * */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();

            UserListActivity.this.setProgressBarIndeterminateVisibility(true);
        }

        @Override
        protected String doInBackground(String... params) {
            // TODO Auto-generated method stub

            // Building Parameters
            List<NameValuePair> parametres = new ArrayList<NameValuePair>();
            // getting JSON string from URL
            JSONObject json = jsonParser.makeHttpRequest(url_display_user,
                    "GET", parametres);

            // Check your log cat for JSON reponse
            Log.d("All Users: ", json.toString());

            try {
                // Checking for SUCCESS TAG
                int success = json.getInt(TAG_SUCCESS);

                if (success == 1) {
                    // products found
                    // Getting Array of Products
                    users = json.getJSONArray(TAG_USERS);

                    // looping through All Users
                    for (int i = 0; i < users.length(); i++) {
                        JSONObject c = users.getJSONObject(i);

                        // Storing each json item in variable
                        String id = c.getString(TAG_ID);
                        String user = c.getString(TAG_USER);

                        // creating new HashMap
                        HashMap<String, String> map = new HashMap<String, String>();

                        // adding each child node to HashMap key => value
                        map.put(TAG_ID, id);
                        map.put(TAG_USER, user);

                        // adding HashList to ArrayList
                        usersList.add(map);

                    }
                    return json.getString(TAG_MESSAGE);
                } else {

                    return json.getString(TAG_MESSAGE);

                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

            return null;
        }

        /**
         * After completing background task Dismiss the progress dialog
         * **/
        protected void onPostExecute(String result) {
            // dismiss the dialog after getting all products
            if (result != null) {

                UserListActivity.this
                        .setProgressBarIndeterminateVisibility(false);

                /**
                 * Updating parsed JSON data into ListView
                 * */
                ListAdapter adapter = new SimpleAdapter(UserListActivity.this,
                        usersList, R.layout.list_item, new String[] { TAG_ID,
                                TAG_USER }, new int[] { R.id.uid, R.id.name });
                // updating listview
                setListAdapter(adapter);

                Toast.makeText(getBaseContext(), result, Toast.LENGTH_LONG)
                        .show();

            }
        }

    }

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

}

我知道必须在OnPostExecute()中完成更改

1 个答案:

答案 0 :(得分:0)

您的ListView不会extend BaseAdapter,但您自己的自定义适配器将意味着您将编写自己的适配器,为ListView提供数据和功能。观点。 您自己的适配器将为列表项创建唯一的布局,并且必须实现/覆盖一些基本方法,如getCount()getView()getItem()等。 在interwebs上可以找到大量的示例和教程,this看起来非常简单。