更改列表视图

时间:2012-10-09 15:43:24

标签: java android

我想在此示例中使用自定义List adapter,以便我可以获得getView()的好处 然后获取列表视图中按钮的 id

这样我就可以使用delete按钮从数据库中检索(name_id) student 作为列表。

我希望实施delete,以便当用户点击delete时,它会占用学生的id 并将其从数据库中删除。

如何在此将我的适配器更改为自定义列表适配器?

我的代码如下:

public class ManageSection extends ListActivity {

//ProgresogressDialog pDialog;

    private ProgressDialog pDialog;

    // Creating JSON Parser object

// Creating JSON Parser object
JSONParser jParser = new JSONParser(); //class
boolean x =true; 

ArrayList<HashMap<String, String>> studentList;

//url to get all products list
private static String url_all_student = "http://10.0.2.2/SmsPhp/view_student_info.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_student = "student";
private static final String TAG_StudentID = "StudentID";
private static final String TAG_StudentNo = "StudentNo";
private static final String TAG_FullName = "FullName";
// course JSONArray
JSONArray student = null;
private TextView mDateDisplay;
private int mYear;
private int mMonth;
private int mDay;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.manage_section);
        mDateDisplay = (TextView) findViewById(R.id.day);

        // add a click listener to the button

        // get the current date

        final Calendar c = Calendar.getInstance();
       mYear = c.get(Calendar.YEAR);
      mMonth = c.get(Calendar.MONTH);
        mDay = c.get(Calendar.DAY_OF_MONTH);
        mDateDisplay.setText(mDay+"-"+mMonth+"-"+mYear);


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



     // on seleting single course
        // launching Edit course Screen
         // on seleting single course
           // launching Edit course Screen




        new LoadAllstudent().execute();


    }


    /**
     * Background Async Task to Load all student by making HTTP Request
     * */
    class LoadAllstudent extends AsyncTask<String, String, String>
    {

        /**
         * Before starting background thread Show Progress Dialog
         * */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(ManageSection.this);
            pDialog.setMessage("Loading student. Please wait...");
            pDialog.setIndeterminate(false);
                  }




        /**
         * getting All student from u r l
         * */
        @Override
        protected String doInBackground(String... args) {
            // Building Parameters
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            // getting JSON string from URL
            JSONObject json = jParser.makeHttpRequest(url_all_student, "GET", params);

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

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

                if (success == 1)
                {
                    // student found
                    // Getting Array of course
                    student = json.getJSONArray(TAG_student);

                    // looping through All courses
                    for (int i = 0; i < student.length(); i++)//course JSONArray
                    {
                        JSONObject c = student.getJSONObject(i); // read first

                        // Storing each json item in variable
                        String StudentID = c.getString(TAG_StudentID);
                        String StudentNo = c.getString(TAG_StudentNo);
                        String FullName = c.getString(TAG_FullName);

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

                        // adding each child node to HashMap key => value
                        map.put(TAG_StudentID, StudentID);
                        map.put(TAG_StudentNo, StudentNo);
                        map.put(TAG_FullName, FullName);

                        // adding HashList to ArrayList
                        studentList.add(map);
                    }
                } else {
                    x=false;

                }

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

            return null;
        }   

        /**
         * After completing background task Dismiss the progress dialog
         * **/
        protected void onPostExecute(String file_url) { 
              // dismiss the dialog after getting all products 
              pDialog.dismiss(); 
              if (x==false)
                Toast.makeText(getBaseContext(),"no student" ,Toast.LENGTH_LONG).show();

              ListAdapter adapter = new SimpleAdapter( 
                      ManageSection.this,  studentList, 
                        R.layout.list_student, new String[] { TAG_StudentID, 
                              TAG_StudentNo,TAG_FullName}, 
                        new int[] { R.id.StudentID, R.id.StudentNo,R.id.FullName}); 
               setListAdapter(adapter); 

             // Updating parsed JSON data into ListView 

        } 


    }
}

请注意,如果在不更改适配器的情况下轻松实现,我可以为每个按钮设置id。 因为我听说我必须使用自定义列表适配器...

2 个答案:

答案 0 :(得分:2)

在此处使用setListAdapter为ListActivity使用自定义适配器:http://developer.android.com/reference/android/app/ListActivity.html#setListAdapter(android.widget.ListAdapter

然后,您就可以使用ID等标记您的观看次数。

在没有自定义适配器(更简单但不是首选)的情况下执行此操作的另一种方法是使用列表中的位置手动映射所有条目。 (因为你可以提供一个元素数组,你可以使用该位置来获取对象)。话虽这么说,如果你只是想挂钩按钮,你可以让onClick记录元素的位置,然后当他们按下按钮你可以通过访问数组正确反应。

编辑:

在你的onCreate do:

getListView()。setOnItemClickListener(new OnItemClickListener(){

public void onItemClick(AdapterView<?> parent, View view, final int pos, long id){
    selected_student=studentList.get(pos); //member of your activity.
});

然后在你的按钮onClickListener中你只需删除(selected_student);

答案 1 :(得分:1)

您的列表需要点击监听器!

这是一个例子;

list.setOnItemClickListener(new OnItemClickListener() {

            public void onItemClick(AdapterView<?> arg0, View arg1, final int arg2, long arg3) {
                //get your information through array.get(arg0), find and delete in database, delete from your arraylist here, then call adapter.notifyDataSetChanged()


                });

这就是你所需要的一切!