Android ListView只包含1个值,Null异常

时间:2015-05-05 15:07:10

标签: java android listview android-listview

当我完成活动时,我正在为Listview上显示的数组添加一个值。

在第一次意图后我刷新游戏(回到main_activity)并开始游戏agian。

当我完成那个游戏时,我在数组中添加了另一个值,但它只显示输入的当前(lawst)值的新值。

我想在数组中显示最后十个值。现在我看到的另一个问题是,当我打开游戏并且arraylist是空的时我得到了一个错误:

java.lang.NullPointerException: Attempt to invoke virtual method '   java.lang.String java.lang.String.toString()' on a null object reference

人员类(在比赛之后,它将数据发送到前十名):

public class Person extends Activity{
EditText name;//define
Button ok;
TextView enter;
Integer Score;
Integer score;//c'tor
String Name;
String pname;//c'tor
@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_person);

    Intent intent = getIntent();//getting extra from intent
    Score = intent.getIntExtra("Score", 0);//defualt value if thers no score
    name =(EditText)findViewById(R.id.namep);
    Name = name.getText().toString();//getting the name that was input to the EditText box
    Log.d("name", Name);
    ok =(Button)findViewById(R.id.send);
    enter =(TextView)findViewById(R.id.entername);
    Toast toast = Toast.makeText(getApplicationContext(), "Lets see if you are can be on TopTen", Toast.LENGTH_SHORT);//Toast Message
    toast.show();
    ok.setOnClickListener(SendActionListener);//set OnClicklistener
}

public Person(){
    this(null,0);
}

public Person(String Tname,int Tscore){
    this.score = Tscore;//score getting Score from last activity
    this.pname = Tname;//pname getting the Name from the editBox
}
public String toString(){
    return "Name :"+this.pname.toString() +" Score : " +this.score.toString();
}
private OnClickListener SendActionListener = new OnClickListener() {

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        Integer s;
        String n;
        s = Score;//getting score
        n = name.getText().toString();
        Log.d("Name", n);
        //details=name+" "+score;//making one string that include the name and the score for the array
        Log.d("ScoreIs", String.valueOf(s));
        Log.d("Name is",n);
        Intent person = new Intent(Person.this,TopTen.class);
        person.putExtra("Score", s);//send extra with the intent
        person.putExtra("Name", n);
        startActivity(person);//start activity
        Log.d("inside", "activity Person");
    };

};

public Integer getScore() {
    return score;
}

public String getName(){
    return pname;
}

/*class ScoreComparator implements Comparator<Person>{
    @Override
    public int compare(Person person1, Person person2) {
        // TODO Auto-generated method stub
        return person1.getScore().compareTo(person2.getScore());
    }
}*/
}//end of Person

TopTen类(带有te数组,列表视图和排序):

public class TopTen extends ListActivity{
ArrayList<Person>TopTens = new ArrayList<Person>(10);
String Name;
Integer Score;
ListView list;
Person newScore;
Person temp;
int i=0;
int j=0;
@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_topten);
    Intent intent = getIntent();//getting Extra from last Intent
    Name = intent.getStringExtra("Name");//getting name
    Score = intent.getIntExtra("Score", 0);//getting score
    newScore = new Person(Name,Score);//creating new person

    ActionBar actionBar = getActionBar();//ActionBar Define
    actionBar.setDisplayHomeAsUpEnabled(true);
    list = (ListView)findViewById(android.R.id.list);//find list by id
    list.setOnItemClickListener(new OnItemClickListener() {//if clicked on item in the list view
        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                long arg3) {
            // TODO Auto-generated method stub
            Intent i = new Intent(TopTen.this, MainActivity.class);//creat intent
            startActivity(i);//start activity go back to main
        }
    });
    int size = TopTens.size();//last value in arry
    if(size<10)
        TopTens.add(newScore);
    if(!TopTens.isEmpty()){//while not empty there is a value
        if(TopTens.get(size).getScore()<newScore.getScore()){//check last value score is lower then newscore score
            Toast toast = Toast.makeText(getApplicationContext(), "You hit the Top Ten",Toast.LENGTH_SHORT);//if yes you in top ten
            toast.show();
            TopTens.add(newScore);
            for(i=0;i<TopTens.size();i++){//running all over the array
                for(j=0;j<TopTens.size();j++){
                    if(TopTens.get(i).getScore()>TopTens.get(j).getScore()){//if the plce iam in which is i
                        //change i and j lets say i is one and j is two change them
                        temp = TopTens.get(i);
                        TopTens.set(i, TopTens.get(j));
                        TopTens.set(j, temp);
                    }
                }
            }
        }
    }//else//else if TopTens is empty there is no values add the new value

    populateListView();//list func
}

public boolean onOptionsItemSelected(MenuItem item){//actionbar activity
    Intent myIntent = new Intent(getApplicationContext(), MainActivity.class);
    startActivityForResult(myIntent, 0);
    return true;
}


private void populateListView(){
    System.out.println(TopTens);
    Log.d("inside", "populateListView");
    ArrayAdapter<Person> adapter = new ArrayAdapter<Person>(this, R.layout.activity_topten,R.id.text1,TopTens);
    //set and arrayadapter to thow array in the list
    Log.d("Inside", "LIST:");
    list.setAdapter(adapter);//set/use the adapter
    Log.d("Inside", "Adapter:");
}
}

当我刚启动应用程序时打开Listview时,我得到null的Logcat:

05-05 17:42:23.981: I/Timeline(13730): Timeline: Activity_launch_request id:com.example.flagsgame time:70151464
05-05 17:42:24.044: D/AndroidRuntime(13730): Shutting down VM
05-05 17:42:24.044: E/AndroidRuntime(13730): FATAL EXCEPTION: main
05-05 17:42:24.044: E/AndroidRuntime(13730): Process: com.example.flagsgame, PID: 13730
05-05 17:42:24.044: E/AndroidRuntime(13730): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.flagsgame/com.example.flagsgame.TopTen}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.String.toString()' on a null object reference
05-05 17:42:24.044: E/AndroidRuntime(13730):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2329)
05-05 17:42:24.044: E/AndroidRuntime(13730):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2389)
05-05 17:42:24.044: E/AndroidRuntime(13730):    at android.app.ActivityThread.access$900(ActivityThread.java:147)
05-05 17:42:24.044: E/AndroidRuntime(13730):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1296)
05-05 17:42:24.044: E/AndroidRuntime(13730):    at android.os.Handler.dispatchMessage(Handler.java:102)
05-05 17:42:24.044: E/AndroidRuntime(13730):    at android.os.Looper.loop(Looper.java:135)
05-05 17:42:24.044: E/AndroidRuntime(13730):    at android.app.ActivityThread.main(ActivityThread.java:5254)
05-05 17:42:24.044: E/AndroidRuntime(13730):    at java.lang.reflect.Method.invoke(Native Method)
05-05 17:42:24.044: E/AndroidRuntime(13730):    at java.lang.reflect.Method.invoke(Method.java:372)
05-05 17:42:24.044: E/AndroidRuntime(13730):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:898)
05-05 17:42:24.044: E/AndroidRuntime(13730):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:693)
05-05 17:42:24.044: E/AndroidRuntime(13730): Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.String.toString()' on a null object reference
05-05 17:42:24.044: E/AndroidRuntime(13730):    at com.example.flagsgame.Person.toString(Person.java:64)
05-05 17:42:24.044: E/AndroidRuntime(13730):    at java.lang.StringBuilder.append(StringBuilder.java:202)
05-05 17:42:24.044: E/AndroidRuntime(13730):    at java.util.AbstractCollection.toString(AbstractCollection.java:374)
05-05 17:42:24.044: E/AndroidRuntime(13730):    at java.lang.StringBuilder.append(StringBuilder.java:202)
05-05 17:42:24.044: E/AndroidRuntime(13730):    at com.android.internal.os.LoggingPrintStream.println(LoggingPrintStream.java:290)
05-05 17:42:24.044: E/AndroidRuntime(13730):    at com.example.flagsgame.TopTen.populateListView(TopTen.java:82)
05-05 17:42:24.044: E/AndroidRuntime(13730):    at com.example.flagsgame.TopTen.onCreate(TopTen.java:71)
05-05 17:42:24.044: E/AndroidRuntime(13730):    at android.app.Activity.performCreate(Activity.java:5933)
05-05 17:42:24.044: E/AndroidRuntime(13730):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
05-05 17:42:24.044: E/AndroidRuntime(13730):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2282)
05-05 17:42:24.044: E/AndroidRuntime(13730):    ... 10 more

1 个答案:

答案 0 :(得分:1)

您需要检查pname和分数是否为NULL。

public String toString(){
    return "Name :"+this.pname.toString() +" Score : " +this.score.toString();
}

编辑:

尝试从

更改此设置
ArrayList<Person>TopTens = new ArrayList<Person>(10);

ArrayList<Person>TopTens = new ArrayList<Person>();

或以这种方式打印TopTen ArrayList

for (Person p : TopTens)
    if (p != null)
        System.out.println(p);

而不是

System.out.println(TopTens);