0

I am attempting to pass an object from one activity to another. I have tried using just intent and how with bundle but I am not sure what is wrong. I have looked at similar solutions here and that is where I got most of my code for this, but it seems that my copy and paste does not work.

This is my main class

    public class MainActivity extends AppCompatActivity {
    Item item;

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

        Button buttonOne = findViewById(R.id.itemButton);
        buttonOne.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                Intent intent = new Intent(getApplicationContext(), ViewItemDetails.class);
                Bundle bundle = new Bundle();
                bundle.putSerializable("item", item);
                intent.putExtras(bundle);
                startActivity(intent);

            }
        });

    }

    void createNewItem(){
        item=new Item("Pixel 4","https://google.com",1000.00);
    }
}

This is the activity I am trying to go to:

    public class ViewItemDetails extends AppCompatActivity {

    Intent intent= getIntent();
    Bundle bundle= intent.getExtras();
    Item item = (Item) bundle.getSerializable("item");

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_view_item_details);
        setStrings();
        setButtons();
    }
    void setStrings() {
        try {
            TextView nameTextView = findViewById(R.id.itemNameid);
            nameTextView.setText(item.getItemName());

            TextView itemInitTV = findViewById(R.id.initalPriceNumID);
            itemInitTV.setText(Double.toString(item.getInitPrice()));

            TextView itemCurrTV = findViewById(R.id.currentPriceNumid);
            itemCurrTV.setText(Double.toString(item.getCurrentPrice()));
        }catch (NullPointerException e){
            //do noting
        }
    }

    void setButtons(){
        Button buyButton = findViewById(R.id.buyButtonid);
        buyButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                Uri uriUrl = Uri.parse(item.getWebaddress());
                Intent launchBrowser = new Intent(Intent.ACTION_VIEW, uriUrl);
                startActivity(launchBrowser);
            }
        });

        Button refreshButton= findViewById(R.id.refrechId);
        refreshButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                Double newPrice= new GenerateNewPrice().GenerateNewPrice(item.getWebaddress());
                Toast toast = Toast.makeText(getApplicationContext(),Double.toString(newPrice), Toast.LENGTH_SHORT);
                toast.show();
            }
        });

        Button editButton= findViewById(R.id.editid);
        editButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {

                Toast toast = Toast.makeText(getApplicationContext(),"Attempt to edit", Toast.LENGTH_SHORT);
                toast.show();
            }
        });

    }
}

This is the object I am attempting to pass between activities.

    public class Item implements Serializable {
    String itemName, webaddress;
    Double initPrice, CurrentPrice;

    public Item(String itemName, String webaddress, Double initPrice) {
        this.itemName = itemName;
        this.webaddress = webaddress;
        this.initPrice = initPrice;
    }

    public String getItemName() {
        return itemName;
    }

    public String getWebaddress() {
        return webaddress;
    }

    public Double getInitPrice() {
        return initPrice;
    }

    public Double getCurrentPrice() {
        return CurrentPrice;
    }
 }

When I run the app on my phone I click the button and then the app closes.

Thank you for your help. If needed I can add more code. I have seen similar questions here, but they have not worked for me. I got similar code from those posts but have not solved my solution. I appreciate any feedback that is give. Thank you for your time.

Ichigo Kurosaki
  • 3,765
  • 8
  • 41
  • 56
Andrea Torres
  • 15
  • 1
  • 1
  • 6
  • 1
    Possible duplicate of [How do I pass data between Activities in Android application?](https://stackoverflow.com/questions/2091465/how-do-i-pass-data-between-activities-in-android-application) – shizhen Oct 14 '19 at 03:49
  • Also, see: https://stackoverflow.com/questions/2736389/how-to-pass-an-object-from-one-activity-to-another-on-android – shizhen Oct 14 '19 at 03:49

5 Answers5

1

For now and for future help on SOF, remember, Error logs are always helpful in that kind of scenario.

Though, Here are some points..

  • You should follow the Activity lifecycle rule, Getting the data in onCreate() will be a good idea.
  • You should use Parcelable instead of Serializable. It is much more efficient.
SRB Bans
  • 3,096
  • 1
  • 10
  • 21
1

your initialisation of bundle and item is wrong in the ViewItemDetails.java activity. Try to initialise inside the onCreate method and let us know..

Peer Mohamed
  • 408
  • 4
  • 15
0

Seems like you have some bug, it should work, you can check out one of the project work example //creating the budle

 listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
            //String selectedItem = (String) adapterView.getItemAtPosition(i);
            //getting dat from text view and converting to string
           // String textview =((TextView)view.findViewById(R.id.textViewName)).getText().toString();
            //Toast.makeText(DriverInfo.this,"Driver id "+driver_id,Toast.LENGTH_SHORT).show();
            Bundle bundle=new Bundle();
            bundle.putString("DriverID",driver_id);
            bundle.putString("Route",loc_src);
            bundle.putString("Dest",loc_dest);
            bundle.putString("location_address",location_address);
            Toast.makeText(DriverInfo.this, "Driver ID="+driver_id, Toast.LENGTH_SHORT).show();
            Intent intent=new Intent(DriverInfo.this, DirverCurrentLoc.class);
            intent.putExtras(bundle);
            startActivity(intent);

        }
    });

//Getting the bundle data

 String lat, lng, realtime,src,dest;
     location_address=intent.getStringExtra("location_address");
        driver_id=intent.getStringExtra("DriverID");
        src=intent.getStringExtra("Route");
        dest=intent.getStringExtra("Dest");
0

You have to initialize this code in onCreate() method like below :

Item item;

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

Intent intent= getIntent();
Bundle bundle= intent.getExtras();
item = (Item) bundle.getSerializable("item");

setStrings();
setButtons();

}

Faisal Ahmed
  • 816
  • 9
  • 12
0

You can use GSON to convert your Object into a JSON format

Intent intent = new Intent(this, ProjectActivity.class);
intent.putExtra("item", new Gson().toJson(item));
startActivity(intent);

then in your second activity, make sure you initialize the bundle correctly in onCreate() lifecycle.

Item item;

@Override
protected void onCreate(Bundle savedInstanceState) {
    .........
    Bundle extras = getIntent().getExtras();
    if (extras != null) {
        item = new Gson().fromJson(extras.getString("item"), Item.class);
    }

Note: I read this in an article that google recommends GSON when passing objects on bundle.