单击按钮错误

时间:2012-10-11 07:44:26

标签: android

我将从数据库(MySQL)中检索学生信息(id -number- name)作为列表视图, 每个学生都有2个按钮(删除 - 提醒)和单选按钮

screen shot http://im21.gulfup.com/1pWi1.png

每件事都没问题,但是如何制作onClickListener,例如删除按钮 因为我尝试了很多例子,我听说我可以使用(自定义列表或获取视图或直接onClickListener,如我的代码(但它不工作)或简单光标适配器)我不知道该用什么,我环顾四周可以帮助我的例子,但在我的情况下,但我没有找到任何,所以我希望这是任何人有同样问题的参考。 这是我的代码,我使用直接onClick与简单适配器

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; 
Button delete;

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";
String cl;
// 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";
private static final String  TAG_Avatar="Avatar";
HashMap<String, String> selected_student;
// course JSONArray
JSONArray student = null;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.manage_section);

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

        ListView list1 = getListView();
        list1.setAdapter(getListAdapter());  
        list1.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int pos, long l) {

                 selected_student =(HashMap<String, String>) studentList.get(pos); //member of your activity.
                 delete =(Button)view.findViewById(R.id.DeleteStudent);
                 cl=selected_student.get(TAG_StudentID);
                 Toast.makeText(getBaseContext(),cl,Toast.LENGTH_LONG).show();
                 delete.setOnClickListener(new View.OnClickListener()

                    {

                        public void onClick(View v) {

                            Log.d("id: ",cl);
                            Toast.makeText(getBaseContext(),cl,Toast.LENGTH_LONG).show();
                        }
                 });
            }

        });

        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);
                     //   String Avatar = c.getString(TAG_Avatar);
                        // 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 

        } 
    }
}

那么您怎么看?为什么删除按钮不起作用?我的日志猫没有错误。有什么替代方法?

3 个答案:

答案 0 :(得分:0)

只需在ListView的onclicklistener外部定义按钮的onclick听众 -

delete =(Button)view.findViewById(R.id.DeleteStudent); // initialize this here

list1.setOnItemClickListener(new OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int pos, long l) 
    {
        selected_student =(HashMap<String, String>) studentList.get(pos); //member of your activity.
        cl=selected_student.get(TAG_StudentID);
        Toast.makeText(getBaseContext(),cl,Toast.LENGTH_LONG).show();
    }
});

delete.setOnClickListener(new View.OnClickListener()
{
    public void onClick(View v) {
        Log.d("id: ",cl);
        Toast.makeText(getBaseContext(),cl,Toast.LENGTH_LONG).show();
    }
});

从您的代码中,只有点击了ListView项后,它才会生效,只有您的按钮才有效。所以尝试使用上面的代码。

答案 1 :(得分:0)

在ListView onclicklistener之外添加onclicklistener按钮 -

list1.setAdapter(new (youradaptername)(getApplicationContext()));
list1.setOnItemClickListener(detaillistener);


private OnItemClickListener detaillistener = new OnItemClickListener()
     {
     // to your Onclick action coding here
     }
     };

就像其他按钮一样。 如需更多信息,请转到此链接here

答案 2 :(得分:0)

@sara你的代码是非常正确的,但它没有用,因为你没有正确地通过context ..!

现在使用此代码肯定会起作用:

 ListView list1 = getListView();
    list1.setAdapter(getListAdapter());  
    list1.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int pos, long l) {

             selected_student =(HashMap<String, String>) studentList.get(pos); //member of your activity.
             delete =(Button)view.findViewById(R.id.DeleteStudent);
             cl=selected_student.get(TAG_StudentID);
             Toast.makeText(getBaseContext(),cl,Toast.LENGTH_LONG).show();
             delete.setOnClickListener(new View.OnClickListener()

                {

                    public void onClick(View v) {

                        Log.d("id: ",cl);
                        Toast.makeText(ManageSection.this,cl,Toast.LENGTH_LONG).show();
                    }
             });
        }

    });

我刚刚将这一行添加到你的代码中:

  Toast.makeText(ManageSection.this,cl,Toast.LENGTH_LONG).show();

现在尝试告诉我它是否正常工作..