-1

So today I'm making a project using listview but I want to pass all the selected values with parcelable in android java. But I'm kinda confuse since I am using array to store the data. Here's my MainActivity.java looks like:

package com.example.lee;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Parcelable;
import android.view.View;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;

import java.util.ArrayList;

import static android.provider.Contacts.SettingsColumns.KEY;

public class MainActivity extends AppCompatActivity{

    ListView list;
    String[] title;
    int[] image;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        image = new int[]{R.drawable.poster_a_star, R.drawable.poster_aquaman, R.drawable.poster_avengerinfinity, R.drawable.poster_birdbox,
                            R.drawable.poster_bohemian};

        title = new String[]{"A Star is Born", "Aquaman", "Avengers Infinity War", "Bird Box", "Bohemian Rhapsody"};


        ListViewAdapters adapters = new ListViewAdapters(MainActivity.this, image, title, release_info, languages, genres);
        list = (ListView)findViewById(R.id.listview_movie);
        // Binds the Adapter to the ListView
        list.setAdapter(adapters);
//         Capture ListView item click
            list.setOnItemClickListener(new OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view,
                                        int position, long id) {
                    ArrayList<Movie> movies = new ArrayList<>();
                    Movie movie = new Movie();
                    Intent i = new Intent(MainActivity.this, ObjectReceived.class);

                i.putExtra("title",title);
                // Pass listview item click position
                i.putExtra("position", position);
                //Pass image item click image
                i.putExtra("image", image);
                // Open SingleItemView.java Activity
                startActivity(i);
            }

        });
    }
}

This one in my Movie.java class:

package com.example.lee;
import android.os.Parcel;
import android.os.Parcelable;

public class Movie implements Parcelable {

    private String title;
    private int image;

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public int getImage() {
        return image;
    }

    public void setImage(int image) {
        this.image = image;
    }

    protected Movie(Parcel in){
        title = in.toString();
        image = in.readInt();
    }
    public Movie(){

    }
    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(title);
        dest.writeInt(image);
    }

    public static final Creator<Movie> CREATOR = new Creator<Movie>() {
        @Override
        public Movie createFromParcel(Parcel source) {
            return new Movie(source);
        }
        @Override
        public Movie[] newArray(int size) {
            return new Movie[size];
        }
    };
}

And here's my ObjectReceived.java class:

package com.example.made_lee;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.widget.TextView;

import java.util.ArrayList;

import static android.provider.Contacts.SettingsColumns.KEY;

public class ObjectReceived extends AppCompatActivity {
    public static final String EXTRA_MOVIE = "extra_person";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_object_received);
        TextView tvObject = findViewById(R.id.object_received);
        ArrayList<Movie> movies = getIntent().getParcelableArrayListExtra(EXTRA_MOVIE);
    }
}

Here's the error messages:

 E/AndroidRuntime: FATAL EXCEPTION: main
     Process: com.example.made_lee, PID: 25122
     java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.made_lee/com.example.made_lee.ObjectReceived}:
 java.lang.NullPointerException: Attempt to invoke virtual method
 'java.lang.String[]
 com.example.made_lee.Movie.getTitle()' on a null
 object reference
         at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2817)
         at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892)
         at android.app.ActivityThread.-wrap11(Unknown Source:0)
         at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593)
         at android.os.Handler.dispatchMessage(Handler.java:105)
         at android.os.Looper.loop(Looper.java:164)
         at android.app.ActivityThread.main(ActivityThread.java:6541)
         at java.lang.reflect.Method.invoke(Native Method)
         at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
         at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
      Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String[]
 com.example.made_lee.Movie.getTitle()' on a null
 object reference
         at com.example.made_lee.ObjectReceived.onCreate(ObjectReceived.java:16)
         at android.app.Activity.performCreate(Activity.java:6975)
         at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1213)
         at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2770)
         at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892) 
         at android.app.ActivityThread.-wrap11(Unknown Source:0) 
         at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593) 
         at android.os.Handler.dispatchMessage(Handler.java:105) 
         at android.os.Looper.loop(Looper.java:164) 
         at android.app.ActivityThread.main(ActivityThread.java:6541) 
         at java.lang.reflect.Method.invoke(Native Method) 
         at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240) 
         at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)

The List View is successfully show up, but whenever I clicked one of the item the app will directly stop running. I think it's because I don't pass the value correctly from MainActivity.java to ObjectReceived.java but in here I confuse about how to pass the value with array items. Please help me :D Thank You

Jakir Hossain
  • 3,830
  • 1
  • 15
  • 29
XVallerie
  • 141
  • 2
  • 11

6 Answers6

1

in your onItemClick your are putting 3 values in your intent bundle:

i.putExtra("title",title);           
i.putExtra("position", position);
i.putExtra("image", image);

In yout ObjectReceived activity you need to get each value by its key.

So this does not work:

ArrayList<Movie> movies = getIntent().getParcelableArrayListExtra(EXTRA_MOVIE);
}

You need to something like this:

Movie movie = new Movie()
movie.setTitle(getIntent().getStringExtra("title")
movie.setImage(getIntent().getIntExtra("image")

The information that is placed into your intent extras has a type and you need to use this type information to retreive the correct value from your extras in your retreiving activity.

Traendy
  • 1,423
  • 15
  • 17
1

Referring this answer, Pass Parcelable ArrayList to Activity

In the sending activity:

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

ArrayList<Movie> movieArray = new ArrayList<Movie>();

i.putParcelableArrayListExtra("array", movieArray);
i.putExtra("title",title);
i.putExtra("position", position);
i.putExtra("image", image);
startActivity(i);

In the recieving activity:

ArrayList<Movie> movieArray = this.getIntent().getParcelableArrayListExtra("array");
BennyHawk
  • 172
  • 2
  • 11
1

How to pass ArrayList from one Activity to another:

 ArrayList<Movie> movies = new ArrayList<>();
    Movie movie = new Movie();
    movie.setTitle(title[position]);
    movie.setImages(image[position]);
    movies.add(movie);
    Intent i = new Intent(MainActivity.this, ObjectReceived.class);
    i.putParcelableArrayListExtra("MovieList", (ArrayList<? extends Parcelable>) movies);

How to receive ArrayList in another activity:

List<Movie> movieList = new ArrayList<>();
 Intent intent = getIntent();
    if (intent != null) {
        movieList = intent.getParcelableArrayListExtra("MovieList");
        Movie movie = movieList.get(0);
        int image = movie.getImage();
        String title = movie.getTitle();
    }
Varun
  • 214
  • 1
  • 5
  • I do try your answer, but when I clicked one of data that I store in array not it string.xml , the second activity doesn't received any data, totally blank – XVallerie Nov 21 '19 at 00:14
1

Okay, Thank you guys for helping me out! now my code works well! I tried this

 String mTitle= screenplays[position];
 intmImage= overview[position];
i.putExtra("title",mTitle);
// Pass all data title
i.putExtra("image", mImage);
// Pass all data image

And this for receiving values

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_object_received);
        TextView tvObject = findViewById(R.id.object_received);
        tvObject.setText(getIntent().getStringExtra("title"));

    }

But this one doesn't implement the POJO class could anybody here tell me how to use properly the POJO class parcelable cause I store the data in array not in string.xml and when I try to click one of data it shows nothing

XVallerie
  • 141
  • 2
  • 11
0

So you want to pass only selected item data from your listview.

You can simply do the following.

list.setOnItemClickListener(new OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view,
                                        int position, long id) {
           Intent i = new Intent(MainActivity.this, ObjectReceived.class);

           String movieTitle = title[position]; // selected item title
           int movieImage = image[position]; // selected item image

           i.putExtra("title",movieTitle);
           i.putExtra("position", position);
           i.putExtra("image", movieImage);
           startActivity(i);
   }

});

And in your ObjectReceived get data like the following.

@Override
protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_object_received);
        TextView tvObject = findViewById(R.id.object_received);

        // get your data like below.
        String title = getIntent().getStringExtra("title");
        int image = getIntent().getIntExtra("image");
        int position = getIntent().getIntExtra("position");
        Log.d("YOUR_TAG", "Title: "+title);

        // create movie object like below
        Movie movie = new Movie()
        movie.setTitle(title);
        movie.setImage(image);
        //........
}
Jakir Hossain
  • 3,830
  • 1
  • 15
  • 29
0
  • If you want to pass ArrayList using Intent then this one might help you.

  • Where you want to pass data from one to another activity using intent use below code.

     button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(context, YourActivity.class);
            Bundle args = new Bundle();
            args.putSerializable("name",list);
            intent.putExtra("namelist",args);
            context.startActivity(intent);
    
  • In Activity where you want to getIntent use code below.

     ArrayList<YourModelName> arraylistname = new ArrayList<>();
    
    Intent intent1 = getIntent();
    Bundle bundle1 = intent1.getBundleExtra("namelist");
    arraylistname = (ArrayList<YourModelName>)   
    bundle1.getSerializable("name");
    
  • And implement your model or POJO class with Serializable

Parth Lotia
  • 753
  • 1
  • 7
  • 25