4

Good day. I'm having some issues with my android project specifically listview. I tried searching for other information here in this site, and implemented some of the answers. However, it is still not working.

The error specifically is

NullPointerException at line 76 at MainActivity

Here is the code of my MainActivity

import java.util.ArrayList;

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;

public class MainActivity extends Activity {

     final ArrayList<String> studentName = new ArrayList<String>();

     ArrayAdapter<String> aa;

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



        ListView myList = (ListView) findViewById(R.id.listName);

         aa = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, studentName);

         myList.setAdapter(aa);


        //droid.R.id.list;

        //add
        Button bAdd = (Button) findViewById(R.id.addstudent);
        bAdd.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                startActivity(new Intent("android.intent.action.ADDSTUDENTS"));
            }   
        });


        //edit

        Button bEdit = (Button) findViewById(R.id.editstudent);
        bEdit.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View x) {
                startActivity(new Intent("android.intent.action.EDITSTUDENTS"));
            }
        });

        //edit

        Button bDelete = (Button) findViewById(R.id.deletestudent);
        bDelete.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View x) {
                startActivity(new Intent("android.intent.action.DELETESTUDENTS"));
                }
            });


    }

    public ArrayList<String> getArray(){
        return studentName;
    }

    public void notifyArray(){
        aa.notifyDataSetChanged();
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }

}

and line 76 by the way is

aa.notifyDataSetChanged();

Here is my code for the AddStudents class

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class AddStudents extends Activity{

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);

        setContentView(R.layout.add_student);

        Button bAddStudents = (Button) findViewById(R.id.add);
        final EditText et = (EditText) findViewById(R.id.student_name);

        bAddStudents.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {

                MainActivity as = new MainActivity();

                as.getArray().add(et.getText().toString());
                as.notifyArray();
                finish();

            }   


        });

        Button bBack = (Button) findViewById(R.id.backadd);

        bBack.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {

                finish();

            }   
    });


    }

}

and the xml part with the list view is

 <ListView
            android:id="@+id/listName" 
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1" >

        </ListView>

I hope you can help me cause I want to also learn what my mistakes are. I can add other information if you want.

  • 1
    What are the values of your `studentName` arraylist? Have you added any values in your arraylist? – GrIsHu Jan 07 '13 at 12:12
  • check this two link http://stackoverflow.com/questions/5817202/null-pointer-exception-during-android-listview-refresh and http://stackoverflow.com/questions/6894613/array-adapter-notifydatasetchanged-nullpointerexception-android – Saifuddin Sarker Jan 07 '13 at 12:14
  • @Grishu I didn't add any values in the studentName array list. Cuase in my understanding, what im planning to do is that, when ever there is a new entry in the AddStudent class (when adding studens) , it automatically goes in the studentName arraylist. Please correct me if I'm wrong. – NewbieLearner Jan 07 '13 at 12:15

3 Answers3

3

In your AddStudents class, you're calling notifyArray() right after you instantiated MainActivity. MainActivity.onCreate() will not be called just by instantiating it.

Instantiating your MainActivity there is probably not what you want anyway (because that object will be disposed directly after the onClick handler is done).

What you want instead is to access the existing instance of MainActivity. For that, add a reference to the current instance to a static member of your MainActivity class, e.g.

public class MainActivity extends Activity {
    public static MainActivity activity;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        activity = this;
    }
}

Then in your AddStudent class access it via

MainActivity.activity.notifyArray()

This is not the most beautiful way to solve your issue, but it works as long as you can be sure to only have one MainActivity instance. (If not, you could make the array itself static; or create a Singleton wrapper class for it.)

domsom
  • 3,163
  • 1
  • 22
  • 27
  • sir, thanks for this explanation. I've understood the relationship now why it is not working (especially the arrangement). I tried nmw's answer and it worked but the list is not showing(seems like another problem in my list). I then tried your answer (codes) and the problem is that in the AddStudent class, it gives an error at MainActivity.activity.notifyArray().. specifically in the notifyArray part. – NewbieLearner Jan 07 '13 at 12:47
  • The method notifyArrays() is undefined for the type Activity. i double checked by the way, it has an s in the end. – NewbieLearner Jan 07 '13 at 12:59
  • I fixed it in the answer: the `activity` member needs to be of type `MainActivity`. – domsom Jan 07 '13 at 13:25
  • sir, the error is now gone. thanks! i have another problem though, if its fine with you. im also looking at it now. even though the error is gone, and when i click add it's fine. The listview is still not showing up. – NewbieLearner Jan 07 '13 at 13:31
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/22327/discussion-between-domsom-and-newbielearner) – domsom Jan 07 '13 at 13:58
1

notifyArray() is being called before onCreate.

nmw
  • 6,664
  • 3
  • 31
  • 32
  • adding the notifyArray() right before onCreate is giving an error that Unable to start activity... Null Pointer Exception – NewbieLearner Jan 07 '13 at 12:23
  • The position of the method isn't important, I said its being *called* before `onCreate()`. So you should look at where `notifyArray()` is being called from, and fix it so it is after `onCreate()`. Or just put a `if (aa != null)` check inside `notifyArray()` if you're lazy. – nmw Jan 07 '13 at 12:25
  • i understand. im sorry, i mistook ur first comment. looking at it now. – NewbieLearner Jan 07 '13 at 12:37
  • @domsom's answer also states this but provides much more info, so I'd follow that - and accept it if it solves the question. – nmw Jan 07 '13 at 12:39
  • @nmw i tried first your answer and it elimnated the error. The only problem now is that, even though it has updated... the list view is not showing up. – NewbieLearner Jan 07 '13 at 12:45
0

Try calling getArray().add(et.getText().toString()); and notifyArray(); inside onResume() of MainActivity and NOT from AddStudentActivity( not recommended!)

So onResume() you would ideally want to add a new student to the list, so in your case, you can retrieve the student name using a common sharable object like a hashtable or somethiing similar, make it a singleton, and use it from anywhere in the applciation

The common class may go something like:

class CommonHashtable{

private static Hashtable<String, Object> commonHashtable = null;

public static getInstance(){
    if(commonHashtable == null)
        commonHashtable = new Hashtable<String, Object>();

    return commonHashtable;
}

on getInstance(), it returns a commonHashtable which can be used to store values temporarily!

so, add this on addbutton click event

Hashtable hash = CommonHashtable.getInstance();
hash.put("NEW_STUDENT_NAME", et.getText().toString());

and add this in you onResume() of MainActivity

Hashtable hash = CommonHashtable.getInstance();
Object studentName = (String) hash.get("NEW_STUDENT_NAME");

if(studentName != null){
    notifyArray();
}
stack_ved
  • 721
  • 3
  • 11
  • Architecture-wise I'd not recommend this: It introduces an implicit data-based dependency and code cluttering where not necessary. My two cents: If you're leaving the data manipulation in `StudentClass` and only move the notification to `MainActivity`, then either use a broadcast intent to trigger that or call `notifyArray()` in `MainActivity.onResume()` unconditionally. – domsom Jan 07 '13 at 13:24