尝试从空数组中读取 - 尝试从其他Activity获取数组返回null

时间:2017-03-02 08:25:35

标签: java android arrays

我使用光标获得了歌曲名称,并将其显示在第一个活动(MainActivity.java)的列表视图中。当我单击列表查看项目时,它会重定向到下一个活动(NextandPrevious.java)并在文本视图中显示单击项目。到目前为止一切都很好。但是我在第二个活动中设置了下一个和上一个按钮。 当我单击下一步按钮返回null。如果在第一个活动中为数组分配了某个值,则相同的代码可以正常工作。

MainActivity.java

public class MainActivity extends AppCompatActivity {

ListView listView;
        List<String>Songs=new ArrayList<>();
    int Position,size,take;
   public static final int MY_PERMISSION_READ_EXTERNAL_STORAGE=1;
    String[] FavouriteActors;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main);

    ShowSongList();




       }



public void ShowSongList(){
    if(ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE)!= PackageManager.PERMISSION_GRANTED){
        if(ActivityCompat.shouldShowRequestPermissionRationale(this,Manifest.permission.READ_EXTERNAL_STORAGE)) {
        }else{ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},MY_PERMISSION_READ_EXTERNAL_STORAGE);
        }
    }else{
        getSongs();
        FavouriteActors=Songs.toArray(new String[Songs.size()]);


        listView=(ListView)findViewById(R.id.lists);
        ArrayAdapter<String> adapter=new ArrayAdapter<>(this,android.R.layout.simple_list_item_1,FavouriteActors);
        listView.setAdapter(adapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                    Position=i;
                size=listView.getCount();

                String Name=String.valueOf(listView.getItemAtPosition(Position));
                Intent send=new Intent(getApplicationContext(),NextandPrevious.class);
                send.putExtra("position",Position);
                send.putExtra("value",Name);
                send.putExtra("length",size);
                send.putExtra("array",FavouriteActors[Position]);
                startActivity(send);


            }
        });
    }
}
public void getSongs(){
    try{
        ContentResolver c=getContentResolver();
        Uri uri=MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
        Cursor cursor=c.query(uri,null,null,null,null);
        if(cursor!=null &&cursor.moveToFirst()){
            int song=cursor.getColumnIndex(MediaStore.Audio.Media.DISPLAY_NAME);
            do{
                String SongName=cursor.getString(song);
                Songs.add(SongName);

            }while(cursor.moveToNext());
        }cursor.close();
    }catch (NumberFormatException e){
        e.printStackTrace();
    }
}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    switch(requestCode){
        case -1:
            //hello
            break;
        case MY_PERMISSION_READ_EXTERNAL_STORAGE:
            if(grantResults.length>0 && grantResults[0]==PackageManager.PERMISSION_GRANTED){
                ShowSongList();
            }else{
                Toast.makeText(getApplicationContext(),"You've denied permission",Toast.LENGTH_LONG).show();

            }
            break;
        default:
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);}

}


}

NextandPrevious.java

public class NextandPrevious extends Activity implements View.OnClickListener{
ImageButton back,next;
    int pos,len;
    String val;
    TextView show;
    String data,nowdata;
    public static int mRequestCode=100;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_nextand_previous);
    back=(ImageButton)findViewById(R.id.back);
    next=(ImageButton)findViewById(R.id.next);
    show=(TextView)findViewById(R.id.textView);
    back.setOnClickListener(this);
    next.setOnClickListener(this);
    Intent get=getIntent();
    pos=get.getExtras().getInt("position");
    val=get.getExtras().getString("value");
    len=get.getExtras().getInt("length");
    nowdata=get.getExtras().getString("array");

    show.setText(String.valueOf(nowdata));

}

@Override
public void onClick(View view) {
    switch(view.getId()){
        case R.id.back:
            if(pos==0){
               pos=len;
                pos=pos-1;
                MainActivity job=new MainActivity();
                data=job.FavouriteActors[pos];
                show.setText(String.valueOf(data));
            }
            else{
                pos=pos-1;
                MainActivity job=new MainActivity();
                data=job.FavouriteActors[pos];
                show.setText(String.valueOf(data));
            }
            break;
        case R.id.next:
            pos=pos+1;
            MainActivity job=new MainActivity();

            String name=job.FavouriteActors[pos];
            if(name!=null){
                show.setText(name);
            }


            break;
    }
}


}

我的错误日志是:

E/AndroidRuntime: FATAL EXCEPTION: main
              Process: com.example.cerebri.droids, PID: 667
              Theme: themes:{com.cyanogenmod.trebuchet=overlay:system, default=overlay:system, iconPack:system, fontPkg:system, com.android.systemui=overlay:system, com.android.systemui.navbar=overlay:system}
              java.lang.NullPointerException: Attempt to read from null array
                  at com.example.cerebri.droids.NextandPrevious.onClick(NextandPrevious.java:61)
                  at android.view.View.performClick(View.java:5204)
                  at android.view.View$PerformClick.run(View.java:21158)
                  at android.os.Handler.handleCallback(Handler.java:739)
                  at android.os.Handler.dispatchMessage(Handler.java:95)
                  at android.os.Looper.loop(Looper.java:148)
                  at android.app.ActivityThread.main(ActivityThread.java:5461)
                  at java.lang.reflect.Method.invoke(Native Method)
                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Application terminated.

请帮帮我。

2 个答案:

答案 0 :(得分:0)

错误是

MainActivity job=new MainActivity();
data=job.FavouriteActors[pos];

您不能只创建一个MainActivity对象,并期望Object拥有与您之前导航的MainActivity相同的数据。您必须像通过其他变量一样通过Intent传递给NextandPrevious-Activity。

另一个提示,了解java codestyle约定,变量命名,缩进等。您的代码真的很难阅读。 Camelcase是要走的路。 StyleGuide

答案 1 :(得分:0)

我错了。

MainActivity.java中的

put

send.putExtra("array",FavouriteActors);

而不是

send.putExtra("array",FavouriteActors[Position]);

来到NextandPrevious.java更改参数&#34; nowdata&#34;字符串到StringArray将下面的代码放在

String[] nowdata=get.getExtras().getStringArray("array");

而不是

String nowdata=get.getExtras().getString("array");

最后在NextandPrevious.java的onClick()方法中进行以下更改

@Override
public void onClick(View view) {
    switch(view.getId()){
        case R.id.back:
            if(pos==0){
               pos=len;
                pos=pos-1;
                show.setText(nowdata[pos]);
            }
            else{
                pos=pos-1;

                show.setText(nowdata[pos]);
            }
            break;
        case R.id.next:
            pos=pos+1;
            if(pos>=len){
                pos=0;
            }

           show.setText(nowdata[pos]);



            break;
    }
}

以前我只调用一个字符串并期望返回数组。显然它会抛出NPE。