将数据(从数据库)传递到下一个活动

时间:2014-01-15 09:33:41

标签: android android-intent android-listview android-activity

在我的第一个活动中,我有一个ListView从数据库(SQLite)获取数据。 我可以在ListView上显示描述(例如购买圣诞礼物,购买火鸡......)。

public class OpenHelper extends SQLiteOpenHelper {

 public static final String NAME = "oef.db";
 public static final int VERSION = 1; 

public OpenHelper(Context context) {
    super(context, NAME, null, VERSION);
}

@Override
public void onCreate(SQLiteDatabase db) {
    onUpgrade(db, 1, VERSION);  
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    String sqlCreateTodo = "CREATE TABLE TODOS (_id INTEGER PRIMARY KEY AUTOINCREMENT, description TEXT, reason TEXT, image TEXT)";
    db.execSQL(sqlCreateTodo);

    String sqlInsertTodo = "INSERT INTO TODOS (description, reason, image) VALUES(?,?,?)";
    db.execSQL(sqlInsertTodo, new Object[] { "Buy Christmas presents.", "Family", "ic_launcher" });
    db.execSQL(sqlInsertTodo, new Object[] { "Buy turkey.", "Family", "ic_launcher" });
    db.execSQL(sqlInsertTodo, new Object[] { "Buy beer.", "Me", "ic_launcher" });
    db.execSQL(sqlInsertTodo, new Object[] { "Buy more beer.", "Me", "ic_launcher" });
    db.execSQL(sqlInsertTodo, new Object[] { "Buy tree.", "Family", "ic_launcher" });
}
}

第一个问题:我还希望在MainActivity上显示图片原因。 (图片 - 描述 - 原因)

public class MainActivity extends ListActivity implements LoaderCallbacks<Cursor>{

private static final int TEST_LOADER = 0;
private SimpleCursorAdapter adapter;

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

    String[] from = new String[] { "description" };
    int[] to = new int[] { android.R.id.text1 };
    adapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_1, null, from, to, 0);
    setListAdapter(adapter);

    getLoaderManager().initLoader(TEST_LOADER, null, this); 

    //listtest.setOnItemClickListener(new AdapterView.OnItemClickListener() {       
    //ListView listtest = (ListView) findViewById(R.id.list);   
    ListView lv = getListView();
    lv.setOnItemClickListener(new OnItemClickListener() {

        public void onItemClick(AdapterView<?> adapter, View view, int position, long id){
            Intent intent = new Intent(MainActivity.this, Detail.class);
            intent.putExtra("id", id);
            startActivity(intent);

           // startActivityForResult(intent, 0);
        }
    });
}

@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
    if (id == TEST_LOADER){
    SQLiteCursorLoader cursorLoader = new SQLiteCursorLoader(this, new OpenHelper(this), "SELECT _id, description FROM TODOS", null);   
        return cursorLoader;
    }
    return null;
}

@Override
public void onLoadFinished(Loader<Cursor> arg0, Cursor arg1) {
    adapter.swapCursor(arg1);
}

@Override
public void onLoaderReset(Loader<Cursor> arg0) {
    adapter.swapCursor(null);
}
}

第二个问题:当点击ListView中的项目时,我想将该项目的数据传递给第二个活动。在控件中显示图像,描述和原因。 (例如,当点击第一行时 - &gt; myDescription text =购买圣诞礼物,myReason tex = family,myImage =设置背景图片)

    <ImageView
        android:id="@+id/myImage"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:contentDescription="@string/hello_world"
        android:layout_marginTop="5dp"
        android:layout_centerHorizontal="true"
        android:src="@drawable/ic_launcher" />

    <TextView
        android:id="@+id/myDescription"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="@string/hello_world" />

    <TextView
        android:id="@+id/myReason"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/myDescription"
        android:layout_below="@+id/myDescription"
        android:layout_marginTop="57dp"
        android:text="@string/hello_world" />

第二项活动:

public class Detail extends Activity {

public static String[] DESCRIPTION = null;

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

    Bundle b = new Bundle();
    b = getIntent().getExtras();
    long id = b.getLong("id");

    TextView t = new TextView(this); 
    t =(TextView)findViewById(R.id.myDescription);
    t.setText(String.valueOf(id));

/*      TextView t = new TextView(this); 
    t =(TextView)findViewById(R.id.myDescription);
    t.setText("Show description");    */  

    TextView t1 = new TextView(this); 
    t1 =(TextView)findViewById(R.id.myReason);
    t1.setText("Show reason");      

    //Show the correct image
    ImageView image = new ImageView(this);
    image = (ImageView)findViewById(R.id.myImage);
    // .... image.setBackground
    //image.setBackgroundResource(R.drawable.ic_launcher);     
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.detail, menu);
    return true;
}
}

对于第二个问题,我可能需要查询数据库?谢谢你们!

3 个答案:

答案 0 :(得分:1)

您可以创建一个Hashmap,将其用作列表视图的适配器。

ArrayList<HashMap<String, String>> yourlist = new ArrayList<HashMap<String, String>>();
HashMap<String,String> hm = new HashMap<String,String>();
hm.put("description",description);
yourlistview.add(hm);

如果您想要显示图片,只需确保您的xml中有一个imageview,这样就可以执行以下操作:

String[] from = { "image","some text","some other text" }; 
//Id(s of the views in your listviewlayout
int[] to = { R.id.image,R.id.sometext,R.id.someothertext};
SimpleAdapter adapter = new SimpleAdapter(getBaseContext(), yourlist, R.layout.listview_layout, from, to);

在itemclick事件中,您可以访问以下项目:

public void onItemClick(AdapterView<?> parent, View view, int position, long id) {              
       HashMap<String, String> map = (HashMap<String, String>) yourlistview.getItemAtPosition(position);
       yourlistview.getItemAtPosition(position);
       Intent intent = new Intent(MainActivity.this, Detail.class);
       intent.putExtra("description", map.get("description"));
...
}

答案 1 :(得分:0)

您可以创建一个包含数据的对象,然后将整个对象传递给第二个活动。您可以查看here以在活动之间传递对象。

答案 2 :(得分:0)

由于您正在使用CursorAdapter,因此列表视图包含光标,该光标包含您从数据库查询并存储在适配器中的项目。因此,listitemclicklistener中的lv.getItemAtPosition(position)将返回指向所选&#39;位置的项目的光标。从游标中,您可以使用cursor.getString()获取所需的值。