简体   繁体   中英

ListView: Null pointer exception

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.

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, eg

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.)

onCreate之前调用notifyArray()

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();
}

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