单击列表中的项目 - 将数据传递给另一个活动并使用sqlite数据库显示其他列

时间:2013-12-12 22:06:41

标签: android sqlite android-intent

我在这里搜索很多,但我没有找到适用于我的应用程序的东西。

我有3个活动(活动1,活动2和活动3)。

活动1是从我的数据库填充的列表视图

活动2是从我的数据库中的另一个表填充的列表视图(关于在我的活动1中选择的项目)。

活动3是一个文本视图,我们可以在其中找到活动2中所选项目的描述。

我的问题是我可以获取所选项目的ID,但我需要显示其他列的值。

活动2代码:

public final static String ID_EXTRA="com.example.testdb5._ID";

String passedVar=null;
private TextView passedView=null;
private BooklistHelper dbBookHelper = null;
private Cursor ourCursor = null;
private BookAdapter adapter=null;




public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.act2);

    passedVar=getIntent().getStringExtra(Tutorial16.ID_EXTRA);

    ListView myListView = (ListView)findViewById(R.id.myListView);

    dbBookHelper=new BooklistHelper(this);

    ourCursor=dbBookHelper.getBooksByAuthor(passedVar);

    startManagingCursor(ourCursor);

    adapter=new BookAdapter(ourCursor);

    myListView.setAdapter(adapter);

    myListView.setOnItemClickListener(onListClick);

}

private AdapterView.OnItemClickListener onListClick=new AdapterView.OnItemClickListener() {
    public void onItemClick(AdapterView<?> parent, 
            View view, int position,
            long id)
    {
        Intent i=new Intent(Activity2.this, Activity3.class);

        i.putExtra(ID_EXTRA, String.valueOf(id));
        startActivity(i);

    }
};


class BookAdapter extends CursorAdapter {
    BookAdapter(Cursor c) {
        super(Activity2.this, c);

    }

    public void bindView(View row, Context ctxt, 
            Cursor c) {
        BookHolder holder=(BookHolder)row.getTag();
        holder.populateFrom(c, dbBookHelper);

    }

    public View newView(Context ctxt, Cursor c, 
            ViewGroup parent) {
        LayoutInflater inflater=getLayoutInflater();
        View row=inflater.inflate(R.layout.row2,  parent, false);
        BookHolder holder=new BookHolder(row);
        row.setTag(holder);
        return(row);
    }


}

static class BookHolder {
    private TextView name=null;

    BookHolder(View row) {
        name=(TextView)row.findViewById(R.id.bookText);
    }

    void populateFrom(Cursor c, BooklistHelper r) {
        name.setText(r.getName(c));
    }   
}

活动3代码:

public class Activity3 extends Activity{

String passedVar=null;
private TextView passedView=null;

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.act3);

    passedVar=getIntent().getStringExtra(Activity2.ID_EXTRA);

    passedView=(TextView)findViewById(R.id.passed);

    passedView.setText("You Clicked item Id="+passedVar);


}

BooklistHelper

public class BooklistHelper extends SQLiteOpenHelper{

//The Android's default system path of your application database.
private static String DB_PATH = "/data/data/com.example.testdb5/databases/";
private static String DB_NAME = "booklist.db";
private static final String TABLE_NAME = "Authors";
private static final String COLUMN_ID = "_id";
public static final String COLUMN_TITLE = "author_name";

private static final String SECOND_TABLE_NAME = "Books";
private static final String SECOND_COLUMN_ID = "_id";
public static final String SECOND_COLUMN_TITLE = "book_name";




private SQLiteDatabase myDataBase; 

private final Context myContext;

/**
 * Constructor
 * Takes and keeps a reference of the passed context in order to access to the application assets and resources.
 * @param context
 */
public BooklistHelper(Context context) {

    super(context, DB_NAME, null, 1);
    this.myContext = context;
}   


public void createDataBase() throws IOException{

    boolean dbExist = checkDataBase();

    if(dbExist){
        //do nothing - database already exist
    }else{

        //By calling this method and empty database will be created into the default system path
           //of your application so we are gonna be able to overwrite that database with our database.
        this.getReadableDatabase();

        try {

            copyDataBase();

        } catch (IOException e) {

            throw new Error("Error copying database");

        }
    }

}

/**
 * Check if the database already exist to avoid re-copying the file each time you open the application.
 * @return true if it exists, false if it doesn't
 */
private boolean checkDataBase(){

    SQLiteDatabase checkDB = null;

    try{
        String myPath = DB_PATH + DB_NAME;
        checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);

    }catch(SQLiteException e){

        //database does't exist yet.

    }

    if(checkDB != null){

        checkDB.close();

    }

    return checkDB != null ? true : false;
}

/**
 * Copies your database from your local assets-folder to the just created empty database in the
 * system folder, from where it can be accessed and handled.
 * This is done by transfering bytestream.
 * */
private void copyDataBase() throws IOException{

    //Open your local db as the input stream
    InputStream myInput = myContext.getAssets().open(DB_NAME);

    // Path to the just created empty db
    String outFileName = DB_PATH + DB_NAME;

    //Open the empty db as the output stream
    OutputStream myOutput = new FileOutputStream(outFileName);

    //transfer bytes from the inputfile to the outputfile
    byte[] buffer = new byte[1024];
    int length;
    while ((length = myInput.read(buffer))>0){
        myOutput.write(buffer, 0, length);
    }

    //Close the streams
    myOutput.flush();
    myOutput.close();
    myInput.close();

}

public void openDataBase() throws SQLException{

    //Open the database
    String myPath = DB_PATH + DB_NAME;
    myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);

}

@Override
public synchronized void close() {

        if(myDataBase != null)
            myDataBase.close();

        super.close();

}



@Override
public void onCreate(SQLiteDatabase db) {
    // TODO Auto-generated method stub

}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    // TODO Auto-generated method stub

}

    // Add your public helper methods to access and get content from the database.
   // You could return cursors by doing "return myDataBase.query(....)" so it'd be easy
   // to you to create adapters for your views.
public Cursor getCursor() {

        SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();

        queryBuilder.setTables(TABLE_NAME);

        String[] asColumnsToReturn = new String [] { COLUMN_ID, COLUMN_TITLE};

        //make sure get search by string pass correctly
        Cursor mCursor = queryBuilder.query(myDataBase, asColumnsToReturn, null, 
                null, null, null, "author_name ASC");



        return mCursor;

    }

    public String getName(Cursor c) {
        return(c.getString(1));

    }

    public Cursor getBooksByAuthor(String id) {
        String[] args={id};

        return(getReadableDatabase()
                .rawQuery("SELECT _id, book_name FROM Books WHERE author_id=?",
                        args));
    }

} 感谢您的帮助,如果您需要更多信息,请不要犹豫。

4 个答案:

答案 0 :(得分:2)

我不完全理解您的问题,但我认为您希望不仅仅将ID传递给活动3,

你可以将你正在使用的整个对象作为可序列化的项目传递,

只需实施Serializableclass xxx implement Serializable),您就可以了,

intent.putExtra("key", object);
活动3中的

yourObjectInstance = (YourObject) getIntent().getSerializableExtra("key");

希望这会有所帮助,否则,如果我不是您需要的,请向我们提供更多信息,

答案 1 :(得分:0)

对于您的第一个活动,您需要从数据库中获取包含您要在ListView中显示的内容的数据以及您需要传递给活动2的任何其他数据,以便活动2具有获取来自数据库的信息。

活动2与Activty 1做同样的事情。获取显示和信息所需的内容以传递给活动3。

在onItemClick()中,您需要使用该项的位置获取从ArrayList中单击的项。单击项目的ID对此无用。它与数据库中项目的ID不同。

您的问题表明您基本上不了解如何使用ArrayList和ListView。互联网上有很多例子。只是Google&#34; android listview示例&#34;。

答案 2 :(得分:0)

如果其他列在listView中,您可以获取这些值:

private AdapterView.OnItemClickListener onListClick=new AdapterView.OnItemClickListener() {
    public void onItemClick(AdapterView<?> parent, 
            View view, int position,
            long id)
    {
        TextView view1 = (TextView)view.findViewById(R.id.yourTextView1);
        TextView view2 = (TextView)view.findViewById(R.id.yourTextView2);
        ....
        .... 

        Intent i=new Intent(Activity2.this, Activity3.class);

        i.putExtra(ID_EXTRA, String.valueOf(id));
        i.putExtra(VALUE1_EXTRA, view1.getText().toString());
        i.putExtra(VALUE2_EXTRA, view2.getText().toString());
        .....
        .....

        startActivity(i);

    }
};

答案 3 :(得分:0)

这是另一种从数据库中检索数据的方法,使其适应您的需求

public ArrayList<MyObject> getDataById(String mId) {
        String query = "select * from table where id=" + mId;

        ArrayList<MyObject> mObjects = new ArrayList<MyObject>();

        Cursor c = myDataBase.rawQuery(query, null);
        int id = c.getColumnIndex("id");
        int val1 = c.getColumnIndex("val1");
        int val2 = c.getColumnIndex("val2");

        for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
            MyObject d = new MyObject();
            d.setId(c.getString(id));
            d.setVal1(c.getString(val1));
            d.setVal2(c.getString(val2));

            mObjects .add(d);
        }
        return mObjects ;
    }

所以这会向您返回所有数据的ArrayList,从这里可以很容易地管理,希望这有帮助