简体   繁体   中英

Send data through Intent

There is ListView and it has to send data to another Activity after item clicked

This is sending data:

listFavorites.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> listView, View v, int position, long id) {

        Intent intent = new Intent(ListWords.this, MainActivity.class);
        intent.putExtra(MainActivity.EXTRA_MESSAGE, Long.toString(id));
        startActivity(intent);


    }

And this is getting data:

  public Fragment getItem(int id) {
       if(id>=0&&getIntent().getExtras().get(EXTRA_MESSAGE)==null) {
           return PageFragment.newInstance(id);
       }else if(id==0&&getIntent().getExtras().get(EXTRA_MESSAGE)!=null){
           int drinkID = (Integer) getIntent().getExtras().get(EXTRA_MESSAGE);
           return PageFragment.newInstance(drinkID);}
        else{
           return PageFragment.newInstance(id);
       }

This part is working fine: if(id==0&&getIntent().getExtras().get(EXTRA_MESSAGE)!=null)

But here it won't checks for null: getIntent().getExtras().get(EXTRA_MESSAGE)==null

it appears errors as Attempt to invoke virtual method 'java.lang.Object android.os.Bundle.get(java.lang.String)' on a null object reference

Thanx in advance, I appreciate any help, advice

由于您将long值转换为String,因此long的值是预先定义的,并且显示项目列表,因此它不能为null。

Intent intent=getIntent();
if(intent.getExtras()!=null)
{    
   if(id>=0&&intent.getExtras().get(EXTRA_MESSAGE)==null) {
       return PageFragment.newInstance(id);
   }else if(id==0&&intent.getExtras().get(EXTRA_MESSAGE)!=null){
       int drinkID = (Integer) intent.getExtras().get(EXTRA_MESSAGE);
       return PageFragment.newInstance(drinkID);}
    else{
       return PageFragment.newInstance(id);
   }
}

Well, my first try would be to refactor that if block so it could be more efficient :

if(id==0&&getIntent().getExtras().get(EXTRA_MESSAGE)!=null)
{
    int drinkID = (Integer) getIntent().getExtras().get(EXTRA_MESSAGE);
    return PageFragment.newInstance(drinkID);
}
else
{
    return PageFragment.newInstance(id);
}

Why, you may ask? Because if we check the result of the first and third if statement, you are returning the exact same thing, so the first if-block is useless. Now, this way it's more efficient and you are removing the if-statement that technically was never evaluated.

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