0

Here's the problem. I have 2 activities:

  • in the 1st activity I have a shopping list with checkbox. I have also created the adapter for 1st activity;
  • in the 2nd activity I must receive the products which were marked by a checkbox.

But something goes wrong and I always receive my last product from the 1st activity:

MainActivity.java

import java.util.ArrayList;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;

public class MainActivity extends Activity implements OnClickListener {

  ArrayList<Product> products = new ArrayList<Product>();
  BoxAdapter boxAdapter;
  Button chek;
  String filePath;

  /** Called when the activity is first created. */
  public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);

      chek = (Button)findViewById(R.id.chek); 
      chek.setOnClickListener(this);
      // Create an adapter
      fillData();
      boxAdapter = new BoxAdapter(this, products);

      // setup list
      ListView lvMain = (ListView) findViewById(R.id.lvMain);
      lvMain.setAdapter(boxAdapter);
  }

  // Generate data for adapter
  void fillData() {
      products.add(new Product("Kolbasa ", 35.50f,
          R.drawable.kolbasa, false));
      products.add(new Product("Product 1", 20f,
          R.drawable.ic_launcher, false));
      products.add(new Product("Product2 ", 50f,
          R.drawable.ic_launcher, false));
      products.add(new Product("Product3 ", 30f,
          R.drawable.ic_launcher, false));
      products.add(new Product("Product4 ",65f,
          R.drawable.ic_launcher, false));
      products.add(new Product("Product 5",78f,
          R.drawable.ic_launcher, false));
  }

  // Output info about shopping bag
  public void showResult(View v) {
      String res1 = "Items in bag:";
      String res2 = "Total cost";
      String result = "";
      float prc=0;
      for (Product p : boxAdapter.getBox()) {
          if (p.box)
              prc += p.price;
          res1 += "\n" + p.name + p.price;

          result = res1 + "\n" + res2 + prc;
      }

      Toast.makeText(this, result, Toast.LENGTH_LONG).show();
  }

  @Override
  public void onClick(View v) {
      switch(v.getId()) {
        case R.id.chek:

            Intent anIntent;
            anIntent = new Intent(this,Chek.class);
            for (Product p : products) {
                if(p.box);
                anIntent.putParcelableArrayListExtra("products", products);
            }
            startActivity(anIntent);
            break;
        }
    }
}

BoxAdapter.java

    import java.util.ArrayList;
    import android.content.Context;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.BaseAdapter;
    import android.widget.CheckBox;
    import android.widget.CompoundButton;
    import android.widget.CompoundButton.OnCheckedChangeListener;
    import android.widget.ImageView;
    import android.widget.TextView;

    public class BoxAdapter extends BaseAdapter {
        Context ctx;
        LayoutInflater lInflater;
        ArrayList<Product> objects;

        BoxAdapter(Context context, ArrayList<Product> products) {
            ctx = context;
            objects = products;
            lInflater = (LayoutInflater) ctx
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }

        // number of elements
        @Override
        public int getCount() {
            return objects.size();
        }

        // element by position
        @Override
        public Object getItem(int position) {
            return objects.get(position);
        }

        // id by position
        @Override
        public long getItemId(int position) {
            return position;
        }

        // item of list
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            // используем созданные, но не используемые view
            View view = convertView;
            if (view == null) {
                view = lInflater.inflate(R.layout.item, parent, false);
            }

            Product p = getProduct(position);

            // fill view in item of list with info: name, price and image
            ((TextView) view.findViewById(R.id.tvDescr)).setText(p.name);
            ((TextView) view.findViewById(R.id.tvPrice)).setText(p.price + "");
            ((ImageView) view.findViewById(R.id.ivImage)).setImageResource(p.image);

            CheckBox cbBuy = (CheckBox) view.findViewById(R.id.cbBox);
            // add hadler to checkbox
            cbBuy.setOnCheckedChangeListener(myCheckChangList);
            // save position
            cbBuy.setTag(position);
            // fill from item: if in bag or not
            cbBuy.setChecked(p.box);
            return view;
       }

       // good by position
       Product getProduct(int position) {
           return ((Product) getItem(position));
       }

       // goods in shopping bag
       ArrayList<Product> getBox() {
           ArrayList<Product> box = new ArrayList<Product>();
           for (Product p : objects) {
               // если в корзине
               if (p.box)
                   box.add(p);
           }
        return box;
      }

      // hadler for checkboxes
     OnCheckedChangeListener myCheckChangList = new OnCheckedChangeListener() {
         public void onCheckedChanged(CompoundButton buttonView,
     boolean isChecked) {
             // change data about the good (if in bag or not)
             getProduct((Integer) buttonView.getTag()).box = isChecked;
         }
    };
}

Chek.java(second activity)

import java.util.ArrayList;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class Chek extends Activity {
    TextView tv1;
    String prod = "";
    @Override
    protected void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.chek);
        tv1 = (TextView) findViewById(R.id.tv1);

        ArrayList<Product> products = getIntent().getParcelableArrayListExtra("products");
        for(int i=0;i<products.size();i++)
        {
    //  products.get(i).getName();
    //  products.get(i).getPrice();
        prod = String.format("\n" + products.get(i).getName() + " " +                products.get(i).getPrice() );
    }
        tv1.setText(prod);
     }}

Product.java

import android.R.string;
import android.os.Parcel;
import android.os.Parcelable;

 public class Product implements Parcelable {

     String name;
     float price;
     int image;
     boolean box;


     Product(String _describe, float _price, int _image, boolean _box) {
         name = _describe;
         price = _price;
         image = _image;
         box = _box;
     }

     public String getName() {return name;}
     public float getPrice() {return price;}

     @Override
     public int describeContents() {
         // TODO Auto-generated method stub
         return 0;
     }

     @Override
     public void writeToParcel(Parcel dest, int flags) {
         dest.writeString(this.name);
         dest.writeFloat(this.price);
     }

     public Product (Parcel parcel) {
         this.name = parcel.readString();
         this.price = parcel.readFloat();
     }

     public final static Parcelable.Creator<Product> CREATOR = new Creator<Product>() {

        @Override
        public Product[] newArray(int size) {
            // TODO Auto-generated method stub
            return new Product[size];
        }

        @Override
        public Product createFromParcel(Parcel in) {
            // TODO Auto-generated method stub
            return new Product(in);
        }
    };
} 

Hope someone will help me. Big thanks!

**Upd:**okay i have run my code. second activyty receive LAST checked item but i need ti receive ALL of checked products. im using loop "for" in Chek.java seems like an error is here) can u help me with this problem?

This topic isn't duplicate 'coz i have an ArrayList and i transfer data with ArrayList also i am using chekbox to marked which items i need to transfer. I think this is enough to not thinking that this is a duplicate. (sorry for my english again) ty!

3 Answers3

1

the issue is right before you launch the second activity, here is the corrected code:

Intent anIntent;
anIntent = new Intent(this,Chek.class);
new ArrayList<Product> checkedProducts = new ArrayList<>();
for (Product p : products) {
   if(p.box){
       checkedProducts.add(p);
   }
}
anIntent.putParcelableArrayListExtra("products", checkedProducts);
startActivity(anIntent);
Budius
  • 39,391
  • 16
  • 102
  • 144
  • thank you! but i have an error in new ArrayList checkedProducts = new ArrayList<>(); syntax error how can i fix thi problem? fixed: ArrayList checkedProducts = new ArrayList(); dunno why i have an error but i have fix it thnk you anyway – SaddyThe One Dec 10 '15 at 15:46
  • I typed all this without testing. There might be some little error, but you can understand the logic behind it and fix any small errors by yourself =) – Budius Dec 10 '15 at 15:53
  • and in Chek,java i need to change ArrayList products = getIntent().getParcelableArrayListExtra("products"); to ArrayList checkedList = getIntent().getParcelableArrayListExtra("products"); Am i right? – SaddyThe One Dec 10 '15 at 15:56
  • It doesn't matter really. The name of the variable in `Check.java` can be anything u want. What matters it the key used (`"products"`) to exact match. – Budius Dec 10 '15 at 15:57
  • okay i have run my code. second activyty receive LAST checked item but i need ti receive ALL of checked products. how i can do this? – SaddyThe One Dec 10 '15 at 16:41
0

Your code :

Intent anIntent;
anIntent = new Intent(this,Chek.class);
for (Product p : products) {
    if(p.box);
anIntent.putParcelableArrayListExtra("products", products);}
startActivity(anIntent);
break;  

This is called as soon as you check a product, so always one product is received by the second activity.

You should first save all the checked products and then send that arraylist to second activity as parceable arraylist :

Arraylist<Product> checkedList = new ArrayList<Product>();

for (Product p : products) {
    if(p.box)
{

checkedlist.add(p);

}
}// end of for loop


// Now send the checkedlist as parceable list

anIntent.putParcelableArrayListExtra("products", checkedlist);}
startActivity(anIntent);
intellignt_idiot
  • 1,962
  • 2
  • 16
  • 23
  • So in Chek.java i need to change ArrayList products = getIntent().getParcelableArrayListExtra("products"); to ArrayList checkedList = getIntent().getParcelableArrayListExtra("products"); Am i right? – SaddyThe One Dec 10 '15 at 15:52
0

I recently had a big problem trying to pass lists of objects between activities, and implementing native methods I had to do a lot of work and line of code, like make my model to implement a Serializable or Parcelable interface and I don't like to do it because it make the model complex, overloaded, and difficult to do changes, i will not discuss the vantages and advantages here. The faster and easiest way to do it is converting your object as a String and pass as string extras, for do it you consider using Gson, and you can do it in many ways as follow:

To send

//Make an instance of Gson in your class, the best practice is to put 
//it inside your singleton or Application.
Gson gson = new Gson();

String jsonIput = gson.toJson(List<YourOject>);
//start your activity passing the object converted
startActivity(new Intent(this, YourSecondActivity.class))
.putExtra("myListObjecstAsJson", jsonInput);

To receive

//receiving your object as String
String jsonOutput = getIntent.getStringExtra("myListObjecstAsJson");
Gson gson = new Gson();
Type listType = new TypeToken<List<YourObject>>(){}.getType();
List<YourObject> posts = (List<YourObject>) gson.fromJson(jsonOutput, listType);

or simplified

List<YourObject> posts = (List<YourObject>) gson.fromJson(jsonOutput, 
new TypeToken<List<YourObject>>(){}.getType());
diogojme
  • 2,309
  • 1
  • 19
  • 25