简体   繁体   中英

Android - Error when adding an OnClickListener to a button in a Dialog

Basically I'm trying to add an OnClickListener to a Button in a Dialog, however by simply adding the listener, the app becomes unstable and crashes, and when I try and catch it, the message returned is null. Thanks for taking a look at my problem.

Also, if it helps, this is being triggered when a menu button is pressed.

Creating the dialog:

try {
        final Dialog dialog = new Dialog(List.this);
        dialog.setContentView(R.layout.adddialog);
        dialog.setTitle("Add to the list");
        dialog.setCancelable(true);

        final EditText et = (EditText) findViewById(R.id.itemAddDialog);
        Button ok = (Button) findViewById(R.id.okAddDialog);
        Button cancel = (Button) findViewById(R.id.cancelAddDialog);

        ok.setOnClickListener(new OnClickListener(){
            @Override
            public void onClick(View arg0) {
                //Contents of this function don't matter, It freezes simply by being created
            }
        });

        dialog.show();
        }
catch (Exception e) {
    Toast.makeText(List.this, e.getMessage(), Toast.LENGTH_LONG).show();
}

(Slightly trimmed) XML file:

<LinearLayout
    android:id="@+id/btnpaneAddDialog"
    android:orientation="horizontal"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:gravity="center_horizontal" >

    <Button
        android:id="@+id/okAddDialog"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Add it" />

    <Button
        android:id="@+id/cancelAddDialog"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Cancel" />


</LinearLayout>

Change:

Button ok = (Button) findViewById(R.id.okAddDialog);

to

Button ok = (Button) dialog.findViewById(R.id.okAddDialog);

It seems that you are calling heavy method net.startRunning(); from the main thread (from inside OnClick() method). The proper way to do it is to run that method on a new thread, for example:

@Override
public void onClick(View arg0)
{
    String toSend = "";
    for(String s : items)
    {
        if(s != null && !s.equals("")) toSend += s + ":";
    }

    new AsyncTask<Void, Void, Void>()
    {
        @Override
        protected Void doInBackground(Void... params)
        {
            net.startRunning();
            net.sendMessage("setlist|" + uname + "#" + (toSend += et.getText().toString()));
            return null;
        }

        @Override
        protected void onPostExecute(Void result)
        {
            dialog.dismiss();
        }
    }.execute();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM