Android Java,onReceive广播接收器上arraylist add()的空指针异常

时间:2016-05-18 15:10:22

标签: java android arraylist nullpointerexception

我试图将字符串添加到列表视图中,该字符串正在通过广播接收器接收。每当我尝试在我的arraylist上做某事或者在我的listview上做一个适配器时,我都会得到一个空指针异常。

public class DevScan extends AppCompatActivity {


MyReceiver rcvr;
String test;
ArrayList<String> devlist;
ArrayAdapter<String> Adapter;
ListView devLV;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_dev_scan);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    rcvr=new MyReceiver();
    this.registerReceiver(rcvr, new    IntentFilter("CUSTOM_INTENT"));





    final UDP_service srv = new UDP_service(this);
    srv.start();


    final ArrayList<String> devlist = new ArrayList<>();
    ListView devLV = (ListView) findViewById(R.id.devlistview);

    devlist.add("elloooo");

    final ArrayAdapter<String> Adapter = new ArrayAdapter<String>(
            this,
            android.R.layout.simple_list_item_1,
            devlist );

    devLV.setAdapter(Adapter);


    Button scanb1 = (Button) findViewById(R.id.scanbtn1);
    scanb1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            devlist.clear();
            Adapter.notifyDataSetChanged();


            srv.Message="eloooo!";
            srv.send();



        }
    });

}

private class MyReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent){
    test = intent.getExtras().getString("packet");
    //it works fine when I put the Extra in a string variable

      //these 3 cause NPE
     // devlist.add(intent.getExtras().getString("packet"));
     //   devlist.add("foo");
     //   Adapter.notifyDataSetChanged();


    Log.i("SOCK broadcast intent", test);

}
}


}

我不反思的是为什么字符串变量&#39; test&#39;使用MyReceiver可以正常工作,但是以相同方式定义的arraylist不会

soluton:

由于我缺乏知识,我偶然将我的物品重新称为本地物品。

1 个答案:

答案 0 :(得分:0)

There are several possible errors in your code

1) The variables MyReceiver rcvr; String test; ArrayList<String> devlist;
ArrayAdapter<String> Adapter; and ListView devLV; are decleared but not initialize.

In your onCreate the above variable was initialize but with final constrains. You should initialize your variables on 
before rcvr=new MyReceiver(); that is

final UDP_service srv = new UDP_service(this);
srv.start();


devlist = new ArrayList<>();
devLV = (ListView) findViewById(R.id.devlistview);

devlist.add("elloooo");

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

devLV.setAdapter(Adapter);

new MyReceiver().onReceive(getApplicationContext(), new Intent().putExtra("packet", "expectedString"));
//it should work
2)Try 1 let see what happens