如何使用onitemlisterner将数据从列表视图重定向到另一个活动

时间:2014-08-17 16:36:08

标签: android

请熟悉android编程。 可以有人帮助我使用代码将数据从sqlite数据库中的列表视图重定向到单击列出的项目上的另一个活动 "我的意思是,当程序运行并且用户点击列出的名字时,应该打开一个新活动,为每个人提供正确的描述(名字,姓氏,年龄) 这是我到目前为止所写的内容,

 `package com.example.mhs;

  import java.util.ArrayList;

  import android.app.ListActivity;
  import android.database.Cursor;
  import android.database.sqlite.SQLiteDatabase;
  import android.database.sqlite.SQLiteException;
  import android.os.Bundle;
  import android.util.Log;
  import android.widget.ArrayAdapter;

  public class P4act extends ListActivity {

  private final String SAMPLE_DB_NAME = "college";
  private final String SAMPLE_TABLE_NAME = "students";

   /** Called when the activity is first created. */
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);


    ArrayList<String> results = new ArrayList<String>();
    SQLiteDatabase sampleDB = null;

    try {
        sampleDB =  this.openOrCreateDatabase(SAMPLE_DB_NAME, MODE_PRIVATE, null);

        sampleDB.execSQL("CREATE TABLE IF NOT EXISTS " +
                SAMPLE_TABLE_NAME +
                " (LastName VARCHAR, FirstName VARCHAR," +
                " Country VARCHAR, Age INT(3));");

        sampleDB.execSQL("INSERT INTO " +
                SAMPLE_TABLE_NAME +
                " Values ('Ebola','Moorthy','Cameroon',22);");
        sampleDB.execSQL("INSERT INTO " +
                SAMPLE_TABLE_NAME +
                " Values ('Eseke','rocks','India',26);");
        sampleDB.execSQL("INSERT INTO " +
                SAMPLE_TABLE_NAME +
                " Values ('Achaki','stones','Nigeria',20);");

        Cursor c = sampleDB.rawQuery("SELECT FirstName, Age FROM " +
                SAMPLE_TABLE_NAME
                , null);

        if (c != null ) {
            if  (c.moveToFirst()) {
                do {
                    String firstName = c.getString(c.getColumnIndex("FirstName"));
                    int age = c.getInt(c.getColumnIndex("Age"));
                    results.add("" + firstName + ",Age: " + age);
                }while (c.moveToNext());
            }
        }

        this.setListAdapter(new ArrayAdapter<String>(this,     android.R.layout.simple_list_item_1,results));



    } 


    catch (SQLiteException se ) {
        Log.e(getClass().getSimpleName(), "Could not create or Open the database");
    } finally {
        if (sampleDB != null)
            sampleDB.execSQL("DELETE FROM " + SAMPLE_TABLE_NAME);
            sampleDB.close();
    }
}

}`

1 个答案:

答案 0 :(得分:0)

@Override
protected void onListItemClick (ListView l, View v, int position, long id) {
    String mySelectedItemValue = results.get(position);
    Intent a = new Intent(this, MyNewActivity.class);
    a.putExtra("myValueKey", mySelectedItemValue);
    startActivity(a);
}

另外:将'results'arraylist移动​​到声明DB名称的位置等等......当你重新调用db时清除它。

获取新活动的价值

String myValue = getIntent().getExtras().getString("myValueKey");