将保存在数据库 sqlite 中的列表视图中的一行发送到另一个列表视图,并使其与第一个列表视图中的行相同

Posted

技术标签:

【中文标题】将保存在数据库 sqlite 中的列表视图中的一行发送到另一个列表视图,并使其与第一个列表视图中的行相同【英文标题】:send a row from a listview saved in database sqlite to another listview and make it do the same as the row in the first listview 【发布时间】:2020-04-28 03:52:33 【问题描述】:

我有两个活动,每个活动都有一个列表视图,第一个连接到数据库并从 strings.xml 获取其数据我想将一行发送到另一个活动中的另一个列表视图并使其执行就像我之前在第一个列表视图中那样,但所有数据都直接保存在数据库中(没有 strnigs.xml)这是我的代码,请帮助我

public class DB_Sqlite extends SQLiteOpenHelper 
    public static final String BDname = "data.db";
    public static final int DBVERSION = 1; /*<<<<< ADDED BUT NOT NEEDED */
    public static final String TABLE_FAVOURITES = "mytable";

    public static final String FAVOURITES_COL_ID = BaseColumns._ID; /*<<<< use the android stock ID name*/
    public static final String FAVOURITES_COL_NAME = "name";
    public static final String FAVOURITES_COL_FAVOURITEFLAG = "favourite_flag"; /*<<<<< NEW COLUMN */

    public DB_Sqlite(@Nullable Context context) 
        super(context, BDname, null, DBVERSION /*<<<<< used constant above */);
    

    @Override
    public void onCreate(SQLiteDatabase db) 
        db.execSQL("create table " + TABLE_FAVOURITES + " (" +
                FAVOURITES_COL_ID + " INTEGER PRIMARY KEY," + /*<<<<< AUTOINCREMENT NOT NEEDED AND IS INEFFICIENT */
                FAVOURITES_COL_NAME + " TEXT, " +
                FAVOURITES_COL_FAVOURITEFLAG + " INTEGER DEFAULT 0" + /*<<<<< COLUMN ADDED */
                ")");
        /* CHANGES HERE BELOW loop adding all Resource names NOT VALUES */
        ContentValues cv = new ContentValues();
        for (String s: StringResourcesHandling.getAllStringResourceNames()) 
            cv.clear();
            cv.put(FAVOURITES_COL_NAME,s);
            db.insert(TABLE_FAVOURITES,null,cv);


        
    

    @Override
    public void onUpgrade(SQLiteDatabase db, int i, int i1) 
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_FAVOURITES);
        onCreate(db);
    
    public boolean insertData(String name)
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put(FAVOURITES_COL_NAME, name);
        long result = db.insert(TABLE_FAVOURITES,null, contentValues);
        if (result == -1)
            return false;
        else
            return true;
    


    public Cursor getFavouriteRows(boolean favourites)  
        SQLiteDatabase db = this.getWritableDatabase();
        String whereclause = FAVOURITES_COL_FAVOURITEFLAG + "=?";
        String compare = "<1";
        if (favourites) 
            compare =">0";
        

        return db.query(
                TABLE_FAVOURITES,null,
                FAVOURITES_COL_FAVOURITEFLAG + compare,
                null,null,null,null
        );
    


    private int setFavourite(long id, boolean favourite_flag) 
        SQLiteDatabase db = this.getWritableDatabase();
        String whereclause = FAVOURITES_COL_ID + "=?";
        String[] whereargs = new String[]String.valueOf(id);
        ContentValues cv = new ContentValues();
        cv.put(FAVOURITES_COL_FAVOURITEFLAG,favourite_flag);
        return db.update(TABLE_FAVOURITES,cv,whereclause,whereargs);
    


    public int setAsFavourite(long id) 
        return setFavourite(id,true);
    


    public int setAsNotFavourite(long id) 
        return setFavourite(id, false);
    

    /* Getting everything and make MatrixCursor VALUES from Resource names from Cursor with Resource names  */
    public Cursor getAllDataInCurrentLocale(Context context) 
        SQLiteDatabase db = this.getWritableDatabase();
        Cursor csr = db.query(TABLE_FAVOURITES,null,null,null,null,null,null);
        if (csr.getCount() < 1) return csr;
        MatrixCursor mxcsr = new MatrixCursor(csr.getColumnNames(),csr.getCount());
        while (csr.moveToNext()) 
            mxcsr.addRow(convertCursorRow(context,csr,new String[]FAVOURITES_COL_NAME));
        
        csr.close();
        return mxcsr;
    
    public Cursor getDataInCurrentLocaleById(Context context, long id) 
        SQLiteDatabase db = this.getWritableDatabase();
        String wherepart = FAVOURITES_COL_ID + "=?";
        String[] args = new String[]String.valueOf(id);
        Cursor csr = db.query(TABLE_FAVOURITES,null,wherepart,args,null,null,null);
        if (csr.getCount() < 1) return csr;
        MatrixCursor mxcsr = new MatrixCursor(csr.getColumnNames(),csr.getCount());
        while (csr.moveToNext()) 
            mxcsr.addRow(convertCursorRow(context,csr,new String[]FAVOURITES_COL_NAME));
        
        csr.close();
        return mxcsr;
    

    /* This getting columns from Cursor into String array (no BLOB handleing)*/
    private String[] convertCursorRow(Context context, Cursor csr, String[] columnsToConvert) 
        String[] rv = new String[csr.getColumnCount()];
        for (String s: csr.getColumnNames()) 
            boolean converted = false;
            for (String ctc: columnsToConvert) 
                if (csr.getType(csr.getColumnIndex(s)) == Cursor.FIELD_TYPE_BLOB) 
                    //........ would have to handle BLOB here if needed (another question if needed)
                
                if (ctc.equals(s)) 
                    rv[csr.getColumnIndex(s)] = StringResourcesHandling.getStringByName(context,csr.getString(csr.getColumnIndex(s)));
                    converted = true;
                
             if (!converted) 
                rv[csr.getColumnIndex(s)] = csr.getString(csr.getColumnIndex(s));
            
        
        return rv;
    

    
public class MainActivity extends AppCompatActivity 

    DB_Sqlite dbSqlite;
    ListView listView;
    ListView listView1;
    ArrayAdapter adapter, adapter1;
    ArrayList arrayList, arrayList1;
    String[] number;
    Button button;
    StringResourcesHandling srh;
    MatrixCursor getAllDataInCurrentLocale,getAllDataInCurrentLocale1;
    SimpleCursorAdapter favourites_adapter,non_favourites_adapter;




    @Override
    protected void onCreate(Bundle savedInstanceState) 
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        listView = (ListView) findViewById(R.id.list_view);
        arrayList = new ArrayList<String>();
        arrayList1 = new ArrayList<String>();
        listView.setAdapter(adapter);
        button = (Button) findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() 
            @Override
            public void onClick(View view) 
                Intent intent = new Intent(MainActivity.this, cc.class);
                startActivity(intent);
            
        );





        /* Show the resources for demo */
        for (String s : StringResourcesHandling.getAllStringResourceNames()) 
            Log.d("RESOURCEDATA", "String Resource Name = " + s +
                    "\n\tValue = " + StringResourcesHandling.getStringByName(this, s)

            );

        

        dbSqlite = new DB_Sqlite(this);
        Cursor csr = dbSqlite.getAllDataInCurrentLocale(this);
        DatabaseUtils.dumpCursor(csr);
        csr.close();

    

    @Override
    protected void onDestroy() 
        super.onDestroy();
        getAllDataInCurrentLocale.close();

    





    @Override
    protected void onResume() 
        super.onResume();
        manageNonFavouritesListView();


    





    private void manageNonFavouritesListView() 
        getAllDataInCurrentLocale = (MatrixCursor) dbSqlite.getAllDataInCurrentLocale(this);
        if (non_favourites_adapter == null) 
            non_favourites_adapter = new SimpleCursorAdapter(
                    this,
                    R.layout.textview,
                    getAllDataInCurrentLocale,
                    new String[]FAVOURITES_COL_NAME,
                    new int[]R.id.textview10,
                    0
            );
            listView.setAdapter(non_favourites_adapter);
            setListViewHandler(listView,false);
         else 
            non_favourites_adapter.swapCursor(getAllDataInCurrentLocale);
        
    





    private void setListViewHandler(ListView listView, boolean favourite_flag) 
        if (!favourite_flag) 
            listView.setOnItemClickListener(new AdapterView.OnItemClickListener() 
                @Override
                public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) 
                    if (i == 0) 
                        Intent intent = new Intent(MainActivity.this, tc.class);
                        startActivity(intent);
                    
                
            );
            listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() 
                @Override
                public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long l) 
                    Intent intent = new Intent(MainActivity.this,cc.class);
                    intent.putExtra("EXTRAKEY_ID",l);
                    String name = getAllDataInCurrentLocale.getString(getAllDataInCurrentLocale.getColumnIndex(FAVOURITES_COL_NAME));
                    Toast.makeText(MainActivity.this, name+" Added To Favorite", Toast.LENGTH_SHORT).show();
                    return true;
                
            );

        



public class cc extends AppCompatActivity 
    String fav_name;
    long fav_id;
    DB_Sqlite dbSqlite;
    Cursor getAllDataInCurrentLocale, getDataInCurrentLocaleById;
    SimpleCursorAdapter non_favourites_adapter;
    ListView listView1;

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


        fav_id = getIntent().getLongExtra("EXTRAKEY_ID", 0);
        if (fav_id == 0) 
        

        dbSqlite = new DB_Sqlite(this);
        Cursor cursor = dbSqlite.getDataInCurrentLocaleById(this, fav_id);
        if (cursor.moveToFirst()) 
            fav_name = cursor.getString(getAllDataInCurrentLocale.getColumnIndex(FAVOURITES_COL_NAME));
            manageNonFavouritesListView();

        
        cursor.close();
    








    private void manageNonFavouritesListView() 
        getDataInCurrentLocaleById =  dbSqlite.getDataInCurrentLocaleById(this,fav_id);
        if (non_favourites_adapter == null) 
            non_favourites_adapter = new SimpleCursorAdapter(
                    this,
                    R.layout.textview,
                    getDataInCurrentLocaleById,
                    new String[]FAVOURITES_COL_NAME,
                    new int[]R.id.textview10,
                    0
            );
            listView1.setAdapter(non_favourites_adapter);
            setListViewHandler(listView1,false);
         else 
            non_favourites_adapter.swapCursor(getDataInCurrentLocaleById);
        
    

    private void setListViewHandler(ListView listView1, boolean b) 

            listView1.setOnItemClickListener(new AdapterView.OnItemClickListener() 
                @Override
                public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) 
                    if (i == 0) 
                        Intent intent = new Intent(cc.this, tc.class);
                        startActivity(intent);
                    
                
            );


        

        

提前谢谢你

【问题讨论】:

【参考方案1】:

获取onItemClick调用的l id(#4值),将其作为Extra添加到intent值,然后进入cc活动。 p>

发送的例子是

@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) 
    if (i == 0) 
        Intent intent = new Intent(MainActivity.this, cc.class);
        intent.putExtra("EXTRAKEY_ID",l); // THIS ADDED
        startActivity(intent);
    

您在 cc 活动中通过点赞获得 id

fav_id = getIntent().getLongExtra("EXTRAKEY_ID",0);
if (fav_id == 0) 
    .... code for not correct id

Cursor cursror = dbSqlite.getDataInCurrentLocaleById(this,fav_id);
if (cursor.moveToFirst()) 
    fav_name = cursor.getString(getAllDataInCurrentLocale.getColumnIndex(FAVOURITES_COL_NAME));

cursor.close();
以上是设置fav_id(长)和fav_name(字符串)和dbSQlite(DB_Sqlite的实例,如dbSqlite = new DB_Sqlite(this);

在 DB_Sqlite.java 你有方法 getDataInCurrentLocaleById 喜欢

public Cursor getDataInCurrentLocaleById(Context context, long id) 
    SQLiteDatabase db = this.getWritableDatabase();
    String wherepart = FAVOURITES_COL_ID + "=?";
    String[] args = new String[]String.valueOf(id);
    Cursor csr = db.query(TABLE_FAVOURITES,null,wherepart,args,null,null,null);
    if (csr.getCount() < 1) return csr;
    MatrixCursor mxcsr = new MatrixCursor(csr.getColumnNames(),csr.getCount());
    while (csr.moveToNext()) 
        mxcsr.addRow(convertCursorRow(context,csr,new String[]FAVOURITES_COL_NAME));
    
    csr.close();
    return mxcsr;

【讨论】:

以上是关于将保存在数据库 sqlite 中的列表视图中的一行发送到另一个列表视图,并使其与第一个列表视图中的行相同的主要内容,如果未能解决你的问题,请参考以下文章

将第一个列表和最后一个列表中的特定值保存到 SQLite

始终勾选列表视图中的选定项目

列表视图中的 csv 和复选框将选中的复选框代码保存在 ArrayAdapter 中

将数据从列表视图(从 Rest Api 生成)传递到另一个活动并将其保存到 SQLite 数据库中

如何通过iphone中的sqlite获取路径来显示文档目录中保存的图像

如何根据sqlite数据库中的名称从drawable中获取图像,然后在列表视图中显示