ArrayAdapter导致java.lang.NullPointerException

时间:2015-05-04 01:16:15

标签: java android

我正在尝试在保存项目后向我的ArrayAdapter添加项目,但它会抛出NullPointerException。任何人都可以告诉我这是什么造成的?看起来信息会保存到数据库中,然后重新加载应用程序。

这是我的java文件,有问题的行是

adapter.addAll(character);

继承完整档案

package com.fasttracksites.dnd5e;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Adapter;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.getbase.floatingactionbutton.FloatingActionButton;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {
    private CustomCursorAdapter customAdapter;
    private List<Character> characters;
    private static final int ENTER_DATA_REQUEST_CODE = 1;
    private ListView listView;
    private Context ctx;
    private ArrayAdapter<Character> adapter;
    private static final String TAG = MainActivity.class.getSimpleName();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        setTitle("Choose a Character");
        ctx = getApplicationContext();

        listView = (ListView) findViewById(R.id.characters);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Log.d(TAG, "clicked on item: " + position);
            }
        });

        // Construct the data source
        ArrayList<Character> arrayOfCharacters = new ArrayList<Character>();
        // Create the adapter to convert the array to views
        CharacterListAdapter adapter = new CharacterListAdapter(this, arrayOfCharacters);
        // Attach the adapter to a ListView
        listView.setAdapter(adapter);

        characters = Character.listAll(Character.class);
        adapter.addAll(characters);

        final FloatingActionButton actionA = (FloatingActionButton) findViewById(R.id.addCharacter);
        actionA.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                actionA.setTitle("Add Character clicked");
                startActivityForResult(new Intent(MainActivity.this, AddCharacterActivity.class), ENTER_DATA_REQUEST_CODE);
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == ENTER_DATA_REQUEST_CODE && resultCode == RESULT_OK) {
            Character character = new Character(data.getExtras().getString("tag_character_name"), data.getExtras().getString("tag_character_class"), data.getExtras().getInt("tag_character_level"));
            character.save();
            adapter.addAll(character); // This is causing the null pointer exception
        }
    }
}

class CharacterListAdapter extends ArrayAdapter<Character> {
    // View lookup cache
    private static class ViewHolder {
        TextView name;
        TextView classAndLevel;
    }
    public CharacterListAdapter(Context context, ArrayList<Character> characters) {
        super(context, R.layout.list_characters, characters);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // Get the data item for this position
        Character character = getItem(position);
        // Check if an existing view is being reused, otherwise inflate the view
        ViewHolder viewHolder; // view lookup cache stored in tag
        if (convertView == null) {
            viewHolder = new ViewHolder();
            LayoutInflater inflater = LayoutInflater.from(getContext());
            convertView = inflater.inflate(R.layout.list_characters, parent, false);
            viewHolder.name = (TextView) convertView.findViewById(R.id.tvCharacterName);
            viewHolder.classAndLevel = (TextView) convertView.findViewById(R.id.tvCharacterClassAndLevel);
            convertView.setTag(viewHolder);
        } else {
            viewHolder = (ViewHolder) convertView.getTag();
        }
        // Populate the data into the template view using the data object
        viewHolder.name.setText(character.name);
        viewHolder.classAndLevel.setText(character.chosenClass + " - Level " + character.level);
        // Return the completed view to render on screen
        return convertView;
    }
}

这是控制台中的错误:

05-03 21:09:35.628    2106-2106/com.fasttracksites.dnd5e E/AndroidRuntime﹕ FATAL EXCEPTION: main
    java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1, result=-1, data=Intent { cmp=com.fasttracksites.dnd5e/.AddCharacterActivity (has extras) }} to activity {com.fasttracksites.dnd5e/com.fasttracksites.dnd5e.MainActivity}: java.lang.NullPointerException
            at android.app.ActivityThread.deliverResults(ActivityThread.java:3367)
            at android.app.ActivityThread.handleSendResult(ActivityThread.java:3410)
            at android.app.ActivityThread.access$1100(ActivityThread.java:141)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1304)
            at android.os.Handler.dispatchMessage(Handler.java:99)
            at android.os.Looper.loop(Looper.java:137)
            at android.app.ActivityThread.main(ActivityThread.java:5103)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:525)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
            at dalvik.system.NativeStart.main(Native Method)
     Caused by: java.lang.NullPointerException
            at com.fasttracksites.dnd5e.MainActivity.onActivityResult(MainActivity.java:78)
            at android.app.Activity.dispatchActivityResult(Activity.java:5322)
            at android.app.ActivityThread.deliverResults(ActivityThread.java:3363)
            at android.app.ActivityThread.handleSendResult(ActivityThread.java:3410)
            at android.app.ActivityThread.access$1100(ActivityThread.java:141)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1304)
            at android.os.Handler.dispatchMessage(Handler.java:99)
            at android.os.Looper.loop(Looper.java:137)
            at android.app.ActivityThread.main(ActivityThread.java:5103)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:525)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
            at dalvik.system.NativeStart.main(Native Method)

发送意图的代码是:

package com.fasttracksites.dnd5e;


        import android.content.Intent;
        import android.os.Bundle;
        import android.support.v7.app.AppCompatActivity;
        import android.view.View;
        import android.widget.EditText;

public class AddCharacterActivity extends AppCompatActivity {

    EditText editTextCharacterName;
    EditText editTextCharacterClass;
    EditText editTextCharacterLevel;

    /**
     * Called when the activity is first created.
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_character);
        setTitle("Enter Your Character Info");

        editTextCharacterName = (EditText) findViewById(R.id.et_character_name);
        editTextCharacterClass = (EditText) findViewById(R.id.et_character_class);
        editTextCharacterLevel = (EditText) findViewById(R.id.et_character_level);
    }

    public void onClickAdd (View btnAdd) {

        String characterName = editTextCharacterName.getText().toString();
        String characterClass = editTextCharacterClass.getText().toString();
        Integer characterLevel = Integer.parseInt(editTextCharacterLevel.getText().toString());

        if ( characterName.length() != 0 && characterClass.length() != 0 ) {

            Intent newIntent = getIntent();
            newIntent.putExtra("tag_character_name", characterName);
            newIntent.putExtra("tag_character_class", characterClass);
            newIntent.putExtra("tag_character_level", characterLevel);

            this.setResult(RESULT_OK, newIntent);

            finish();
        }
    }
}

1 个答案:

答案 0 :(得分:1)

更改:

     CharacterListAdapter adapter = 
           new CharacterListAdapter(this, arrayOfCharacters);

      adapter = new CharacterListAdapter(this, arrayOfCharacters);

问题正在发生,因为调用adapter方法时null方法onActivityResultadapter.addAll