0

我正在制作一个 Android 应用程序,在接下来的活动中,我对数据库执行查询并获取结果。我获取结果并将 TextViews 制作到 Activity 中。当我单击 TextView 时,我希望将我单击的餐厅的名称传递给下一个 Activity。我的代码的问题在于,对于所有 TextView,它都保存了最后一家餐厅的名称。有任何想法吗?谢谢!

public class ViewRestaurants extends Activity{
String name;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.row_restaurant);

DBAdapter db = new DBAdapter(this);
db.open();

Cursor c = db.getSpRestaurants(getIntent().getStringExtra("city"), getIntent().getStringExtra("area"), getIntent().getStringExtra("cuisine"));

View layout =  findViewById(R.id.items);

if(c.moveToFirst())
{
    do{
        name = c.getString(0);
        TextView resname = new TextView(this);
        TextView res = new TextView(this);
        View line = new View(this);

        resname.setText(c.getString(0));
        resname.setTextColor(Color.RED);
        resname.setTextSize(30);
        resname.setTypeface(null,Typeface.BOLD);

        res.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT));
        res.setText(c.getString(1)+","+c.getString(2)+","+c.getString(3)+"\n"+c.getString(4));
        res.setTextSize(20);
        res.setTextColor(Color.WHITE);
        res.setClickable(true);
        res.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent i = new Intent();
                i.setClassName("com.mdl.cyrestaurants.guide", "com.mdl.cyrestaurants.guide.RestaurantDetails");
                i.putExtra("name",name);
                startActivity(i);
            }
        });

        line.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,2));
        line.setBackgroundColor(Color.RED);

        ((LinearLayout) layout).addView(resname);
        ((LinearLayout) layout).addView(res);
        ((LinearLayout) layout).addView(line);
    }while (c.moveToNext());

}

    db.close();
}

}

4

2 回答 2

0

您需要name在循环中创建最终结果并将其作为类字段删除,以便以OnClickListener您的方式使用它。

if(c.moveToFirst())
{
    do{
        final String name = c.getString(0);

        //other code ...

        res.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent i = new Intent();
                i.setClassName("com.mdl.cyrestaurants.guide", "com.mdl.cyrestaurants.guide.RestaurantDetails");
                i.putExtra("name",name);
                startActivity(i);
            }
        });

        //more code...

    }while (c.moveToNext());
}
于 2013-01-19T15:59:04.473 回答
0

尝试进行这些更改

String name = c.getString(0);
resname.setText(name);

The reason why it is setting to the last restaurant name is because string is being passed by reference rather than by value as it is an object. Creating a unique string within the scope of the do while loop should solve this.

于 2013-01-19T16:06:32.840 回答