1

I am just a beginner in programming. I am having issue with my code. Whenever I try to click on the 2nd item in a list, the app suddenly crashes.

This is my code:

public class MainActivity extends AppCompatActivity {

    ListView lvCategories;
    String[] categories = {
        "School", "Work", "Family Outings", "Friends Outings", "Groceries" , "Appointments", "Indoor Activities",
            "Outdoor Activities", "Games","Overseas Travelling"
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        lvCategories = (ListView)findViewById(R.id.listViewCategories);

        final ArrayAdapter<String> adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, categories);
        lvCategories.setAdapter(adapter);

        lvCategories.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String category = (String) parent.getItemAtPosition(position);

                if (category == "School") {
                    Intent school = new Intent(view.getContext(), school_activity.class);
                    school.putExtra("school_category", "");
                    startActivity(school);
                }
                if (category == "Work") {
                    Intent work = new Intent(view.getContext(), work_activity.class);
                    work.putExtra("work_category", "");
                    startActivity(work);
                }
            }
        });
    }
}

May I know what is the issue?

Here is the error I found from LogCat.

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.EditText.setText(java.lang.CharSequence)' on a null object reference

And here's my work_activity

public class work_activity extends AppCompatActivity {

    Button btnSave;
    EditText etContent;
    TextView tvLastUpdated;

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

        btnSave = (Button)findViewById(R.id.buttonSave);
        etContent = (EditText)findViewById(R.id.editTextContent);
        tvLastUpdated = (TextView)findViewById(R.id.textViewLastUpdated);

        Intent intentReceived = getIntent();
        final String strContent = intentReceived.getStringExtra("work_category");
        etContent.setText(strContent);
        Calendar now = Calendar.getInstance();
        final String datetime = now.get(Calendar.DAY_OF_MONTH) + "/" +
                (now.get(Calendar.MONTH) + 1) + "/" +
                now.get(Calendar.YEAR) + " " +
                now.get(Calendar.HOUR_OF_DAY) + ":" +
                now.get(Calendar.MINUTE);
        tvLastUpdated.setText(datetime);

        btnSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String strContentSaved = etContent.getText().toString();
                SharedPreferences preferences = getSharedPreferences("category_work_saved", MODE_PRIVATE);
                SharedPreferences.Editor prefEdit = preferences.edit();
                prefEdit.putString("contentSaved", strContentSaved);
                prefEdit.putString("date", datetime);
                prefEdit.commit();
                Toast.makeText(work_activity.this, "Content Saved Successfully", Toast.LENGTH_SHORT).show();
                finish();
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        SharedPreferences preferences = getSharedPreferences("category_work_saved", MODE_PRIVATE);
        String contentSaved = preferences.getString("contentSaved", "");
        etContent.setText(contentSaved);
        String dateTime = preferences.getString("date","");
        tvLastUpdated.setText(dateTime);
    }
}
halfer
  • 19,824
  • 17
  • 99
  • 186
Mobile Developer
  • 191
  • 1
  • 3
  • 10
  • post your error report to get answes – siddhesh Nov 13 '16 at 06:42
  • Sorry, but i not sure how to do that. Is it use the Logcat error code? If so, i honestly also dont know how to put that – Mobile Developer Nov 13 '16 at 06:51
  • Search how to show logcat erros in Android Studio and post the log output below your question. @MobileDeveloper – Prokash Sarkar Nov 13 '16 at 07:00
  • are you using android studio ? Please refer http://stackoverflow.com/questions/16817566/restore-logcat-window-within-android-studio – Minh Bui Nov 13 '16 at 07:01
  • Oh, i believe its this error: Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.EditText.setText(java.lang.CharSequence)' on a null object reference – Mobile Developer Nov 13 '16 at 07:01
  • yes Minh Bui, I am using Android Studio. Ok i will look into it. And i posted the error on top of my current comment. – Mobile Developer Nov 13 '16 at 07:02
  • oh, i will show you the work_activity class – Mobile Developer Nov 13 '16 at 07:04
  • Is id `editTextContent` in layout `activity_work_activity.xml`? – K Neeraj Lal Nov 13 '16 at 07:09
  • OMG! YOU HELP ME FOUND THE ERROR! Yes! I forgot to put editTextContent!! THANK YOU VERY VERY MUCH!!! It is such a great honor to have your help. Thank you all guys for the help!! Thank you very very much – Mobile Developer Nov 13 '16 at 07:12
  • By the way... `(category == "School")`... [How to compare strings in Java](http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java#513839) – OneCricketeer Nov 13 '16 at 07:18
  • I saw a guy who managed to do something like that and give it a try. But yeah, i also use switch case method and also if else statement base on position to get to the next activity with Intent. It all works the same. Even comparing String in Android Studio seems possible. – Mobile Developer Nov 13 '16 at 07:20
  • @MobileDeveloper Please accept the answer if it helped you. – K Neeraj Lal Nov 13 '16 at 07:33

3 Answers3

0

It looks like you may be trying to set your text

etContent.setText(strContent);

without a strContent value...is that the case? You're sending "work_category", but it may be a null value ""

kwishnu
  • 1,730
  • 19
  • 17
  • Yup, i found the error thanks to K Neeraj Lal. I forgot to change the id name in EditText to match the value. Thank you very the help anyway. :) – Mobile Developer Nov 13 '16 at 07:17
0

You've some critical problems in your code. Let me point out these issues here.

In your MainActivity you're comparing the String values wrongly. You need to use equals() method instead of == operator comparison to compare String.

And yes, try sending something to the work_activity or school_activity.

lvCategories.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        String category = (String) parent.getItemAtPosition(position);

        if (category.equals("School")) {
            Intent school = new Intent(view.getContext(), school_activity.class);
            school.putExtra("school_category", "send something here");
            startActivity(school);
        }
        if (category.equals("Work")) {
            Intent work = new Intent(view.getContext(), work_activity.class);
            work.putExtra("work_category", "send something here");
            startActivity(work);
        }
    }
});

Now in your work_activity, you need to check for null value for received intent.

String strContent = null;
Intent intentReceived = getIntent();

// Check if the intent received is null
if (intentReceived != null) 
    strContent = intentReceived.getStringExtra("work_category");

// Now check if the string content is null 
if(strContent != null) 
    etContent.setText(strContent);

Another thing to check if the id of the EditText in your activity_work_activity layout is editTextContent. The id needs to match to find the EditText which might cause the crash here.

Reaz Murshed
  • 23,691
  • 13
  • 78
  • 98
  • Glad to know. Please upvote and accept the answer if you find this helpful. And please take care of the critical issues I've pointed. :) – Reaz Murshed Nov 13 '16 at 07:26
  • Oh, btw, even though i use == operator comparision, surprisingly it work. I forgot equals() method is actually the correct method to do that. Even Switch Case method and If Else Statement based on position in ListView also work out. – Mobile Developer Nov 13 '16 at 07:28
  • Oh, how to upvote. Haha sorry, i just join this website when i cant solve and find the error. – Mobile Developer Nov 13 '16 at 07:30
0

The error says,

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.EditText.setText(java.lang.CharSequence)' on a null object reference

So that means findViewById(R.id.editTextContent); is returning null.

I think you forgot to add the id editTextContent to the EditText or you don't have the Editetext in layout activity_work_activity.xml.

Also as cricket007 suggested in the comments, use equals to compare Strings as follows,

if (category.equals("School")){
    ...
}
K Neeraj Lal
  • 6,768
  • 3
  • 24
  • 33