将一行从 Activity 中的列表视图移动到另一个 activity 中的另一个列表视图

move one row from listview in Activity to another listview in another activity

我有两个列表视图,每个列表视图都不同 activity 我想要当我长按第一个列表视图中的任何行时移动到第二个列表视图并且仍然执行相同的任务,就好像它在第一个(例如打开 activity),列表视图从 strings.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);
                    }
                }
            });


        }

        }
public class StringResourcesHandling {
    private static final String[] allowedStringResourcePrefixes = new String[]{"db_"};
    private static boolean loaded = false;
    private static Field[] fields = R.string.class.getFields();
    private static ArrayList<String> allowedStringResourceNames = new ArrayList<>();

    private static void loadStringResources() {
        if (loaded) return;

        for (Field f: fields) {
            if (isResourceNameAllowedPrefix(f.getName())) {
                allowedStringResourceNames.add(f.getName());
            }
        }
        loaded = true;
    }

    private static boolean isResourceNameAllowedPrefix(String resourceName) {
        if (allowedStringResourcePrefixes.length < 1) return true;
        for (String s: allowedStringResourcePrefixes) {
            if (resourceName.substring(0,s.length()).equals(s)) return true;
        }
        return false;
    }

    public static String getStringByName(Context context, String name) {
        String rv = "";
        boolean nameFound = false;
        if (!loaded) {
            loadStringResources();
        }
        for (String s: allowedStringResourceNames) {
            if (s.equals(name)) {
                nameFound = true;
                break;
            }
        }
        if (!nameFound) return rv;
        return context.getString(context.getResources().getIdentifier(name,"string",context.getPackageName()));
    }

    public static List<String> getAllStringResourceNames() {

        if (!loaded) {
            loadStringResources();
        }
        return allowedStringResourceNames;
    }
}

提前谢谢你

第 1 期

第一个问题,您正在尝试将 Cursor 投射到 MatrixCursor,您不能那样投射,但是您可以将 MatrixCursor 投射到 Cursor(无论如何由 getAllDataInCurrentLocale 方法)。

所以不是:-

getAllDataInCurrentLocale = (MatrixCursor) dbSqlite.getAllDataInCurrentLocale(this);

你想要:-

getAllDataInCurrentLocale = dbSqlite.getAllDataInCurrentLocale(this);

第 2 期

第二个问题是您在开始另一项活动时从未通过 Intent Extra。

也就是

一)

这里没有Intent Extra的设置(启动tc时activity):-

button = (Button) findViewById(R.id.button);
    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent intent = new Intent(MainActivity.this, tc.class);
            startActivity(intent);
        }
    });

b)

同样,这里没有 Intent Extra 设置(启动 cc activity 时):-

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

无论是否按照 显示这样做:-

@Override public void onItemClick(AdapterView adapterView, View view, int i, long l) { 如果(我== 0){ Intent intent = new Intent(MainActivity.this, cc.class); intent.putExtra("EXTRAKEY_ID",l); // 添加了 开始Activity(意图); } }

因此你需要像上面那样添加第 1 行 ADD。

第 3 期

您正在尝试访问尚未实例化的游标,因此根据 :-[=21= 在 cc activity 中出现空指针异常]

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

    }
    cursor.close();

那是你正在实例化一个名为 cursor 的 Cursor 对象,然后尝试在一个名为 getAllDataInCurrentLocale 的 Cursor 上使用 Cursor 方法,当它有没有被实例化。相反,您应该使用实例化 Cursor cursor

的方法

你应该使用 :-

    getAllDataInCurrentLocale = dbSqlite.getDataInCurrentLocaleById(this, fav_id);
    if (getAllDataInCurrentLocale.moveToFirst()) {
        fav_name = getAllDataInCurrentLocale.getString(getAllDataInCurrentLocale.getColumnIndex(FAVOURITES_COL_NAME));
        manageNonFavouritesListView();

    }
    getAllDataInCurrentLocale.close();

即声明为 getAllDataInCurrentLocale 的游标是您应该使用的游标,而不是声明另一个游标。

第 4 期

然后你会得到一个空指针异常,因为你已经 decalred 但要实例化 listView1

所以你需要这样一行(见评论):-

listView1 = this.findViewById(R.id.listview1); //<<<<< ADDED note name should match layout so may be different

通过这些更改,单击第一个(由于在 onItemClick 方法中编码 i == 0 而只有第一个)将启动 cc activity显示点击的item(only the 1 as id selects only the 1)

例如

主要Activity :-

单击 Speck 转到 cc Activity :-