简体   繁体   English

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

[英]Click Item in List - Pass Data to Another Activity and display other columns using sqlite database

I search a lot here but i didn't find something working on my app. 我在这里搜索了很多内容,但没有找到适用于我的应用程序的内容。

I have 3 Activity (Activity 1, Activity 2 and Activity 3). 我有3个活动(活动1,活动2和活动3)。

Activity 1 is a list view populated from my database 活动1是从我的数据库填充的列表视图

Activity 2 is a list view populated from another table on my database(regarding the item selected in my activity 1). 活动2是一个列表视图,该列表视图是从数据库中的另一个表填充的(关于活动1中选择的项目)。

Activity 3 is a text view where we can find a description of the selected item in the activity 2. 活动3是一个文本视图,我们可以在活动2中找到所选项目的描述。

My problem is that i can get the ID of the selected item but i need to show value of other columns. 我的问题是,我可以获取所选项目的ID,但是我需要显示其他列的值。

Activity 2 code : 活动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));
    }   
}

Acitivity 3 code : Acitivity 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 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));
    }

} Thank you for your help and don't hesitate if you need more information. }感谢您的帮助,如果您需要更多信息,请不要犹豫。

I don't fully understand your question, but I think you want to pass more than just the ID to the activity 3, 我不完全理解您的问题,但是我想您不仅要将ID传递给活动3,

well you could pass the whole object you are working with as a serializable item, 好吧,您可以将要使用的整个对象作为可序列化的项目传递,

just implement Serializable ( class xxx implement Serializable ) , and you are good to go, 只需实现Serializableclass xxx implement Serializable ),就可以了,

intent.putExtra("key", object);

in the activity3 在活动3中

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

hope this helps, otherwise if I it's not what you need, please provide us with more infos, 希望对您有所帮助,否则,如果我不是您所需要的,请向我们提供更多信息,

For your first activity, you need to get the data from the database that includes what you want to display in the ListView and any additional data you need to pass to Activity 2, so that Activity 2 has what it needs to get the information from the database. 对于第一个活动,您需要从数据库中获取数据,其中包括要在ListView中显示的内容以及需要传递给活动2的任何其他数据,以便活动2具有从活动数据库2获取信息所需的内容。数据库。

Activity 2 does the same thing as Activty 1. Get what it needs for display and info to pass to Activity 3. 活动2与活动1的作用相同。获取显示和信息传递给活动3所需的内容。

In that onItemClick(), you need to get the item that was clicked from your ArrayList using the position of that item. 在该onItemClick()中,您需要使用该项目的位置来获取从ArrayList中单击的项目。 The ID of the item clicked is not useful for that. 单击的项目的ID对此没有用。 It is not the same thing as the id of the item in the database. 它与数据库中项目的ID不同。

Your question shows a basic lack of understanding of how you would use an ArrayList and a ListView. 您的问题表明基本缺乏对如何使用ArrayList和ListView的理解。 There are many examples of that on the internet. 互联网上有很多这样的例子。 Just Google "android listview example". 只是Google的“ android listview示例”。

If the other columns are in listView you can get those values: 如果其他列在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);

    }
};

here is another way to retreive data from the data base, adapt it to your needs 这是从数据库检索数据并使其适应您的需求的另一种方法

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

so this returns to you an ArrayList of all your data, from here it's fairly easy to manage, hope this helps 因此,这将为您返回所有数据的ArrayList ,从这里开始很容易管理,希望对您有所帮助

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何通过单击按钮将Listview中的数据传递到购物车列表(新活动)。 我插入列表视图的数据正在使用SQLite - How to pass the data in Listview to Cart list (new activity) by click on button . My data inserted to listview is using SQLite 将数据从列表视图(从Rest Api生成)传递到另一个活动,并将其保存到SQLite数据库中 - pass Data from a List View (generated from Rest Api) to another activity and save that into SQLite Database 如何将数据从sqlite数据库传递到另一个活动? - How do I pass data from sqlite database to another activity? 将单击的列表项数据库列传递给另一个活动 - Passing clicked list item database columns to another activity 如何使用Robotium在其他活动中单击项目列表? - How to click on item list in other activity using robotium? 如何在Android中使用列表项单击导航到另一个活动 - How to navigate in to another activity using list item click in Android 点击列表项将移至另一个活动类 - Click list item will move into another activity class Android如何将与ListView项目相关的数据从sqlite数据库传递到下一个活动 - Android how to pass data related to a listview item from sqlite database into next activity 如何将点击的项目数据传递给另一个活动 - how to pass clicked item data to another activity Android工具在列表项上单击以通过自定义列表适配器将数据传递到新的活动 - Android implement on list item click to pass data to new Activity via custom list adapter
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM