简体   繁体   中英

Passing the selected object to an Another Activity

I have a news activity in which there is a list of news.I want a user to select a news from the list and direct him to the news_details page where I give the details about the selected news, however when the user selects the news, program goes quickly to news_details and comes back again to the news.

  News:

  public void Listen() {

    list.setOnItemClickListener(new AdapterView.OnItemClickListener() {  // ana sayfada herhangi bir item seçildiğinde
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {


            NewsItem selectedNews = (NewsItem) parent.getItemAtPosition(position);
            Intent i = new Intent(MainActivity.this, News_Details_Activity.class);
            i.putExtra("title", selectedNews.getTitle());
            i.putExtra("date", selectedNews.getNewsDate().toString());
            i.putExtra("image_id", selectedNews.getImageId());
            i.putExtra("text", selectedNews.getText());
            setResult(RESULT_OK, i); 
            startActivity(i);




        }

    });
}


  News_Details:

  @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_news__details);

    Intent i = new Intent(this,MainActivity.class);

    startActivityForResult(i, GET_NEWS);

}


@Override  
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == GET_NEWS) {  // Check which request we're responding to

        if (resultCode == RESULT_OK) {  // Make sure the request was successful

            title.setText(data.getStringExtra("title"));
            date.setText(data.getStringExtra("date"));
            news_img.setImageResource(data.getIntExtra("image_id", 0));
            news_text.setText(data.getStringExtra("text"));


        }

    }
}
}

First of all, remove this line:

setResult(RESULT_OK, i); 

Also, remove this line from newsdetails activity:

startActivityForResult(i, GET_NEWS);

Make changes as below:

public void Listen() {

    list.setOnItemClickListener(new AdapterView.OnItemClickListener() {  
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            NewsItem selectedNews = (NewsItem) parent.getItemAtPosition(position);
            Intent i = new Intent(MainActivity.this, News_Details_Activity.class);
            i.putExtra("title", selectedNews.getTitle());
            i.putExtra("date", selectedNews.getNewsDate().toString());
            i.putExtra("image_id", selectedNews.getImageId());
            i.putExtra("text", selectedNews.getText());
            startActivity(i);
        }

    });
}

Then, in your news details activity:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_news__details);

    Intent i = getIntent();
    String title = i.getStringExtra("title");
    String date = i.getStringExtra("date");
    int imageId = i.getIntExtra("image_id");
    String text = i.getStringExtra("text");
}

OnActivityResult method is not required so simply remove it.

FYI:

startActivity and startActivityForResult both of them start new activities , but startActivityForResult as the name suggests that you are expecting a result from the activity you are starting. And this result shall be obtained in onActivityResult method.

Say for example, you want to start Activity2 from Activity1, and you want to pass some data back to Activity1 while finishing Activity2. You simply set the Result in Activity2 using setResult() method. and while Activity1 resumes again, its onActivityResult() will be invoked, you will override onActivityResult() in Activity1 to receive the Result set by Activity2.

Hope you are now clear on this.

Remove these lines 
setResult(RESULT_OK, i); 
Intent i = new Intent(this,MainActivity.class);
startActivityForResult(i, GET_NEWS);

Use google Gson for serializing the object.

    NewsItem selectedNews = (NewsItem) parent.getItemAtPosition(position);
    String strNews = new Gson().toJson(selectedNews);

    Intent i = new Intent(MainActivity.this, News_Details_Activity.class);
                i.putExtra("news", strNews);
                startActivity(i);

On other hand News details onCreate() do this

    Bundle bundle = getIntent().getExtras();
    String newsStr = bundle.getString("news");
            Gson gson = new Gson();
            Type type = new TypeToken<NewsItem>() {
            }.getType();
            NewsItem selectedNews = gson.fromJson(newsStr, type);

to send string value

  NewsItem selectedNews = (NewsItem) parent.getItemAtPosition(position);
        Intent i=new Intent(MainActivity.this, News_Details_Activity.class);
        i.putExtra("title", selectedNews.getTitle());
        i.putExtra("date", selectedNews.getNewsDate().toString());
        i.putExtra("image_id", selectedNews.getImageId());
        i.putExtra("text", selectedNews.getText());
        startActivity(i);

to recieve in News_Details_Activity

    Intent i = getIntent();
    title = i.getStringExtra("title");
    date= i.getStringExtra("date");
    text= i.getStringExtra("text");

you can do it using Serializable by following way

public class News implements Serializable{

String title;
String desc;
String time,imageUrl;

}

Then News List activity

Intent i = new Intent(MainActivity.this, News_Details_Activity.class);
        i.putExtra("news",newsObject);

and get it onCreate of NewsDetail

    News news=(News)  getIntent().getExtras().getSerializable("news");
and user it like  title.setText(news.getTitle());

make News class that implements Serialazable

Create new Object of News class , and put into intent as putSerialazable();

in your second activity just getIntent().getSerialazable("key") and set your data to views.

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