在两项活动之间传输数据

时间:2015-12-10 15:27:35

标签: java android

这是问题所在。我有2项活动:

  • 在第一个活动中我有一个带复选框的购物清单。我还为第一个活动创建了适配器;
  • 在第二项活动中,我必须收到标有复选框的产品。

但出了点问题,我总是从第一项活动中收到我的最后一个产品:

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(第二项活动)

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);
        }
    };
} 

希望有人能帮助我。非常感谢!

**更新:**好吧我已经运行了我的代码。第二个activyty收到最后检查的项目,但我需要ti接收所有已检查的产品。我在Chek.java中使用循环“for”似乎是错误就在这里)你可以帮我解决这个问题吗?

这个主题不重复'因为我有一个ArrayList并且我使用ArrayList传输数据我也使用chekbox来标记我需要传输的项目。我认为这足以让人不以为这是重复的。 (对不起我的英语)ty!

3 个答案:

答案 0 :(得分:1)

问题就在您启动第二个活动之前,这里是更正后的代码:

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);

答案 1 :(得分:0)

您的代码:

results

只要您检查产品,就会调用此产品,因此第二项活动始终会收到一个产品。

您应首先保存所有已检查的产品,然后将该arraylist作为parceable arraylist发送到第二个活动:

asynctask

答案 2 :(得分:0)

我最近在尝试在活动之间传递对象列表时遇到了一个大问题,并且实现了本机方法,我必须做很多工作和代码行,比如让我的模型实现Serializable或{{ 1}}界面,我不喜欢这样做,因为它使模型变得复杂,过载,并且难以做出改变,我不会在这里讨论优势和优势。更快速,更简单的方法是将对象转换为Parcelable并传递为字符串附加内容,因为您考虑使用String,并且您可以通过以下多种方式执行此操作:

发送

Gson

接收

//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);

或简化

//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);