gpt4 book ai didi

java - 在 2 个 Activity 之间传输数据

转载 作者:行者123 更新时间:2023-12-01 10:45:32 25 4
gpt4 key购买 nike

问题就在这里。我有 2 项 Activity :

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

但是出了问题,我总是收到第一个 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(第二个 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);
}}

产品.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);
}
};
}

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

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

这个主题不重复,因为我有一个 ArrayList,并且我使用 ArrayList 传输数据,而且我还使用 chekbox 来标记我需要传输的项目。我认为这足以不认为这是重复的。 (再次抱歉我的英语)ty!

最佳答案

问题就在您启动第二个 Activity 之前,以下是更正后的代码:

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

关于java - 在 2 个 Activity 之间传输数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34205722/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com