简体   繁体   中英

app crashes when clicking on add item button in todo list

I created an option of to-do list in my navigation drawer, it opens up but when I click on add item button, my app crashes. I have extended fragments.

please help!

code for todo.java:

(this is called from my main java file )

public class todo extends Fragment {

View myView;

private ArrayList<String> items;
private ArrayAdapter<String> itemsadapter;
private ListView lvItems;

private void readItems() {
    File filesDir = this.getContext().getFilesDir();
    File todoFile = new File(filesDir, "todo.txt");
    try {
        items = new ArrayList<String>(FileUtils.readLines(todoFile));

    } catch (IOException e) {
        items = new ArrayList<String>();
    }
}

private void writeItems() {
    File filesDir = this.getContext().getFilesDir();
    File todoFile = new File(filesDir, "todo.txt");
    try {
        FileUtils.writeLines(todoFile, items);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    myView = inflater.inflate(R.layout.todo_layout, container, false);

    lvItems=(ListView) myView.findViewById(R.id.lvItems);
    items= new ArrayList<String>();
    readItems();
    itemsadapter= new ArrayAdapter<String>(this.getContext(),android.R.layout.simple_list_item_1,items);
    lvItems.setAdapter(itemsadapter);
    setupListViewListener();

    return myView;
}

public void onADDItem(View v)
{
    EditText etNewItem=(EditText)myView.findViewById(R.id.etNewItem);
    String itemText = etNewItem.getText().toString();
    Boolean a =itemText.isEmpty();
    if(a==true){
        Toast.makeText(getActivity().getBaseContext(),"Please Enter the item in the textbox",Toast.LENGTH_SHORT).show();

    }
    else {
        String datetimestamp= DateFormat.getDateTimeInstance().format(new Date());
        itemsadapter.add(itemText + "\n" + datetimestamp);
        etNewItem.setText("");
        writeItems();
    }

}

private void setupListViewListener()
{
    lvItems.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener()
                                       {
                                           @Override
                                           public boolean onItemLongClick(AdapterView<?> adapter,
                                                                          View item, final int pos, long id) {
                                               AlertDialog.Builder alertbox= new AlertDialog.Builder(item.getContext());
                                               alertbox.setTitle("Delete entry")
                                                       .setMessage("Are you sure you want to delete this entry?")
                                                       .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                                                           public void onClick(DialogInterface dialog, int which) {
                                                               items.remove(pos);
                                                               itemsadapter.notifyDataSetChanged();
                                                               writeItems();
                                                               // continue with delete
                                                           }
                                                       })
                                                       .setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
                                                           public void onClick(DialogInterface dialog, int which) {
                                                               // do nothing
                                                           }
                                                       })
                                                       .setIcon(android.R.drawable.ic_dialog_alert)
                                                       .show();
                                               return true;
                                           }
                                       }
    );
}}

And XML layout for todo is here:

<?xml version="1.0" encoding="utf-8"?>
 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/image">
<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginBottom="30dp"
    android:textSize="20dp"
    android:textAppearance="?android:attr/textAppearanceMedium"
    android:text="YOUR LIST:"
    android:textColor="#324567"
    android:id="@+id/textView"
    android:layout_alignParentTop="true"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:layout_alignRight="@+id/btnADDItem"
    android:layout_alignEnd="@+id/btnADDItem" />
<ListView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/lvItems"
    android:layout_alignParentTop="true"
    android:layout_marginTop="20dp"
    android:layout_above="@+id/btnADDItem"
    android:layout_below="@+id/textView"
    android:textColor="#000000"
    />

<EditText
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/etNewItem"
    android:layout_alignTop="@+id/btnADDItem"
    android:hint="enter a new item"
    android:textColorHint="#000000"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:layout_toLeftOf="@+id/btnADDItem"
    android:layout_toStartOf="@+id/btnADDItem"
    android:layout_alignParentBottom="true"
    android:textColor="#000000"
    />
<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="ADD ITEM"
    android:id="@+id/btnADDItem"
    android:layout_alignParentBottom="true"
    android:layout_alignParentRight="true"
    android:layout_alignParentEnd="true"
    android:onClick="onADDItem"
    />
 </RelativeLayout>

my app crashes when I click on "ADD ITEM" button. I have tried all options.
if I do not extend fragment then connectivity fails as I have used navigation drawer.

Error in logcat:

09-17 13:58:10.835: E/SurfaceFlinger(293): strok layer name=none
09-17 13:58:10.843: E/SIMInfo(7137): info.mWapPush init error, not support 
 in FW.
09-17 13:58:10.866: E/SurfaceFlinger(293): strok layer name=none
09-17 13:58:10.867: E/SIMInfo(7137): SimStatusChangeReceiver, ss=null
09-17 13:58:10.883: E/SurfaceFlinger(293): strok layer name=none
09-17 13:58:10.945: E/lowmemorykiller(265): Error writing 
     /proc/2947/oom_score_adj; errno=22
09-17 13:58:10.961: E/SIMInfo(7137): info.mWapPush init error, not support 
   in FW.
09-17 13:58:14.695: E/ACRA(2821): ACRA caught a IllegalStateException for 
   net.cyclestreets
09-17 13:58:14.695: E/ACRA(2821): java.lang.IllegalStateException: Could not 
  find method onADDItem(View) in a parent or ancestor Context for 
   android:onClick attribute defined on view class 
   android.support.v7.widget.AppCompatButton with id 'btnADDItem'
    09-17 13:58:14.695: E/ACRA(2821):   at 


android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.resolveMethod(AppCompatViewInflater.java:325)
09-17 13:58:14.695: E/ACRA(2821):   at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:284)
09-17 13:58:14.695: E/ACRA(2821):   at android.view.View.performClick(View.java:5269)
09-17 13:58:14.695: E/ACRA(2821):   at android.view.View$PerformClick.run(View.java:21556)
09-17 13:58:14.695: E/ACRA(2821):   at android.os.Handler.handleCallback(Handler.java:815)
09-17 13:58:14.695: E/ACRA(2821):   at android.os.Handler.dispatchMessage(Handler.java:104)
09-17 13:58:14.695: E/ACRA(2821):   at android.os.Looper.loop(Looper.java:207)
09-17 13:58:14.695: E/ACRA(2821):   at android.app.ActivityThread.main(ActivityThread.java:5769)
09-17 13:58:14.695: E/ACRA(2821):   at java.lang.reflect.Method.invoke(Native Method)
09-17 13:58:14.695: E/ACRA(2821):   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789)
09-17 13:58:14.695: E/ACRA(2821):   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:679)
09-17 13:58:15.175: E/SurfaceFlinger(293): strok layer name=none
09-17 13:58:15.175: E/SurfaceFlinger(293): strok layer name=none
09-17 13:58:15.210: E/lowmemorykiller(265): Error writing /proc/2821/oom_score_adj; errno=22
09-17 13:58:15.802: E/SurfaceFlinger(293): strok layer name=none
09-17 13:58:15.818: E/SurfaceFlinger(293): strok layer name=none
09-17 13:58:15.834: E/SurfaceFlinger(293): strok layer name=none
09-17 13:58:15.850: E/SurfaceFlinger(293): strok layer name=none
09-17 13:58:15.867: E/SurfaceFlinger(293): strok layer name=none
09-17 13:58:15.883: E/SurfaceFlinger(293): strok layer name=none
09-17 13:58:15.899: E/SurfaceFlinger(293): strok layer name=none
09-17 13:58:15.915: E/SurfaceFlinger(293): strok layer name=none
09-17 13:58:15.931: E/SurfaceFlinger(293): strok layer name=none
09-17 13:58:15.947: E/SurfaceFlinger(293): strok layer name=none
09-17 13:58:15.964: E/SurfaceFlinger(293): strok layer name=none
09-17 13:58:16.161: E/MultiWindowProxy(870): getServiceInstance failed!
01-01 00:00:00.000: E/(-1): Device disconnected

This is because Android didn't associate the android:onClick="onADDItem" in the following:

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="ADD ITEM"
    android:id="@+id/btnADDItem"
    android:layout_alignParentBottom="true"
    android:layout_alignParentRight="true"
    android:layout_alignParentEnd="true"
    android:onClick="onADDItem"
    />

with the onADDItem() method in Fragment:

public void onADDItem(View v) {
  ...
}

Android will only link the onClick with onADDItem() if the method is in the Activity.

So, you need to use View.OnClickListener instead in the Fragment.

Something like this:

Button btnAdd = (Button) findViewById(R.id.btnADDItem);
btnNext.setOnClickListener(new View.OnClickListener() {
      @Override public void onClick(View v) {
        // Do something here.
      }
    });

It is a good practice to separate the UI layout and the code to handle the view click listener. Therefore, don't use android:onClick for click listener. Let the XML layout only for UI, and let the UI behaviour is handled in the code. This will save your time from maintenance nightmare in the future.

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