send a row from one listview to another listview

旧城冷巷雨未停 提交于 2020-01-24 18:47:25

问题


i have two listviews in the same activity one of them have elements the other one is empty and i want to send any element to the second lisview by long click and i want the elements to do the same as it is in the first listview(open an activity) here is my code and please tell what to do:

MainActivity.java


import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Toast;

import java.util.ArrayList;


public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";
    DB_Sqlite db = new DB_Sqlite(this);
    ListView listView1;
    ListView listView;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
         listView = (ListView) findViewById(R.id.list_view);
         listView1 = (ListView) findViewById(R.id.list_view1);

        final ArrayList arrayList = new ArrayList<String>();
        arrayList.add("Complex Complex");
        arrayList.add("Trix Complex");
        arrayList.add("Kingdoms");
        final ArrayList arrayList1 = new ArrayList<String>();
        final ListAdapter adapter = new ArrayAdapter<>(MainActivity.this,android.R.layout.simple_list_item_1,arrayList);
        listView.setAdapter(adapter);




        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
                if (position == 0){
                    Intent intent = new Intent(MainActivity.this,cc.class);
                    startActivity(intent);
                }
                if (position == 1){
                    Intent intent = new Intent(MainActivity.this,tc.class);
                    startActivity(intent);
                }
                if (position == 2){
                    Intent intent = new Intent(MainActivity.this,k.class);
                    startActivity(intent);
                }


            }
        });
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
    @Override
    public boolean onItemLongClick(AdapterView<?> adapterView, View view, int position, long l) {
        if (position == 0) {

            Boolean result = db.insertData((String) arrayList.get(position));
            if (result == true){
                Toast.makeText(MainActivity.this,"Added To Favorite",Toast.LENGTH_SHORT).show();
            }else{
                Toast.makeText(MainActivity.this, "Already Exist", Toast.LENGTH_SHORT).show();
            }

        }
        if (position == 1){
            Toast.makeText(MainActivity.this, "TC Added to Favorites", Toast.LENGTH_SHORT).show();
        }
        if (position == 2){
            Toast.makeText(MainActivity.this, "K Added to Favorites", Toast.LENGTH_SHORT).show();
        }
        return true;
    }

});


}
public void showData(){
    ArrayList arrayList1 = db.getAllrecord();
    final ListAdapter adapter1 = new ArrayAdapter<>(MainActivity.this,android.R.layout.simple_list_item_1,arrayList1);
    listView1.setAdapter(adapter1);
}
    }

this is what i have done so far please help, thank you very much.
DB_Sqlite.java


import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import androidx.annotation.Nullable;

import java.util.ArrayList;

public class DB_Sqlite extends SQLiteOpenHelper {
    public static final String BDname = "data.db";
    public DB_Sqlite(@Nullable Context context) {
        super(context, BDname, null, 1);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("create table mytable (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)");

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int i, int i1) {
        db.execSQL("DROP TABLE IF EXISTS mytable");
        onCreate(db);

    }
    public boolean insertData(String name){
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put("name", name);
        long result = db.insert("mytable",null, contentValues);
        if (result == -1)
            return false;
        else
            return true;
    }
    public ArrayList getAllrecord(){
        ArrayList arrayList = new ArrayList();
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor res = db.rawQuery("select * from mytable",null);
        res.moveToFirst();
        while (res.isAfterLast()==false){
            String t1 = res.getString(0);
            arrayList.add(t1+" - ");
            res.moveToNext();
        }
        return arrayList;
    }
}
activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    android:background="#f2f2f2"
    android:orientation="vertical">


    <TextView
        android:id="@+id/tv1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="25sp"
        android:textColor="@color/colorAccent"
        android:text="Favorite List:">

    </TextView>

    <ListView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/list_view1"
        android:layout_below="@+id/tv1"
        android:divider="@color/colorPrimary"
        android:dividerHeight="1dp"
        android:layout_weight="1">
    </ListView>




    <TextView
        android:id="@+id/tv"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="25sp"
        android:textColor="@color/colorAccent"
        android:layout_weight="0"
        android:text="Game List:"
        android:layout_below="@+id/list_view1">

    </TextView>

    <ListView
        android:id="@+id/list_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/tv"
        android:layout_weight="2"
        android:divider="@color/colorPrimary"
        android:dividerHeight="1dp"
        android:layout_alignParentBottom="true"
        >

    </ListView>



</LinearLayout>

this is what i have done so far please help me thank you in advance.


回答1:


The following should do what you want (assuming that by Send to means move to) :-

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";
    DB_Sqlite db = new DB_Sqlite(this);
    ListView listView1;
    ListView listView;
    ArrayAdapter<String> adapter, adapter1; /* changed to use ArrayAdapter */
    ArrayList<String> arrayList,arrayList1; /* moved (not necessary) */



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        listView = (ListView) findViewById(R.id.list_view);
        listView1 = (ListView) findViewById(R.id.list_view1);

        arrayList = new ArrayList<String>();
        arrayList.add("Complex Complex");
        arrayList.add("Trix Complex");
        arrayList.add("Kingdoms");
        arrayList1 = new ArrayList<String>();
        adapter = new ArrayAdapter<>(MainActivity.this,android.R.layout.simple_list_item_1,arrayList);
        listView.setAdapter(adapter);

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
                if (position == 0){
                    Intent intent = new Intent(MainActivity.this,cc.class);
                    startActivity(intent);
                }
                if (position == 1){
                    Intent intent = new Intent(MainActivity.this,tc.class);
                    startActivity(intent);
                }
                if (position == 2){
                    Intent intent = new Intent(MainActivity.this,k.class);
                    startActivity(intent);
                }


            }
        });
        listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> adapterView, View view, int position, long l) {
                if (position == 0) {

                    Boolean result = db.insertData((String) arrayList.get(position));
                    if (result == true){
                        Toast.makeText(MainActivity.this,"Added To Favorite",Toast.LENGTH_SHORT).show();
                    }else{
                        Toast.makeText(MainActivity.this, "Already Exist", Toast.LENGTH_SHORT).show();
                    }

                }
                if (position == 1){
                    Toast.makeText(MainActivity.this, "TC Added to Favorites", Toast.LENGTH_SHORT).show();
                }
                if (position == 2){
                    Toast.makeText(MainActivity.this, "K Added to Favorites", Toast.LENGTH_SHORT).show();
                }
                /*<<<<< the core code that was added >>>>>*/
                arrayList1.add(arrayList.get(position));
                arrayList.remove(position);
                adapter1.notifyDataSetChanged();
                adapter.notifyDataSetChanged();
                return true;
            }

        });

        /* added */
        adapter1 = new ArrayAdapter<>(this,android.R.layout.simple_list_item_1,arrayList1);
        listView1.setAdapter(adapter1);

    }
    public void showData(){
        ArrayList arrayList1 = db.getAllrecord();
        final ListAdapter adapter1 = new ArrayAdapter<>(MainActivity.this,android.R.layout.simple_list_item_1,arrayList1);
        listView1.setAdapter(adapter1);
    }
}

Result

  • The first ListView has a blue background, the other Listview has a green background to allow one to be distinguished from the other.

When first started :-

After Long Clicking Trix Complex :-

Additional

re comment :-

@AhmedZaqout roughly what you need to do is a) add a column as an inidcator of which list e.g. favourite_flag INTEGER DEFAULT 0 b) populate DB with initial values (Kingdons etc) instead of defining the values in an ArrayList. When the activity starts extract the values into the 2 lists according to the indicator column. If item in first is Long clicked update the row to set the indicator then refresh the lists.

Then consider the following :-

DB_SQlite.java

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 */
                ")");
        /*<<<<< Add initial data */
        /* Note indicator will set to non_favourite i.e. 0 */
        ContentValues cv = new ContentValues();
        cv.put(FAVOURITES_COL_NAME,"Complex Complex");
        db.insert(TABLE_FAVOURITES,null,cv);
        cv.clear();
        cv.put(FAVOURITES_COL_NAME,"Trix Complex");
        db.insert(TABLE_FAVOURITES,null,cv);
        cv.clear();
        cv.put(FAVOURITES_COL_NAME,"Kingdoms");
        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;
    }

    /*<<<<< ADDEDD */
    public Cursor getFavouriteRows(boolean favourites /* true to return favourites (listView 2), false to return non-favourites (ListView 1) */) {
        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
        );
    }

    /*<<<<< ADDEDD */
    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);
    }

    /*<<<<< ADDEDD */
    public int setAsFavourite(long id) {
        return setFavourite(id,true);
    }

    /*<<<<< ADDEDD */
    public int setAsNotFavourite(long id) {
        return setFavourite(id, false);
    }

    /* Will be unused */
    public ArrayList getAllrecord(){
        ArrayList arrayList = new ArrayList();
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor res = db.rawQuery("select * from mytable",null);
        res.moveToFirst();
        while (res.isAfterLast()==false){
            String t1 = res.getString(0);
            arrayList.add(t1+" - ");
            res.moveToNext();
        }
        return arrayList;
    }
}

MainActivity.java

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";
    DB_Sqlite db = new DB_Sqlite(this);
    ListView listView1, listView;
    //ArrayAdapter<String> adapter, adapter1; /*<<<<< commented out as unused */
    //ArrayList<String> arrayList,arrayList1; /*<<<<< commented out as unused */
    Cursor non_favourites_cursor, favourites_cursor; //<<<<< Added as goind to use Cursor Adapter */
    SimpleCursorAdapter non_favourites_adapter, favourites_adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        listView = (ListView) findViewById(R.id.list_view);
        listView1 = (ListView) findViewById(R.id.list_view1);
        manageBothListViews();

        //arrayList = new ArrayList<String>();
        //arrayList.add("Complex Complex");
        //arrayList.add("Trix Complex");
        //arrayList.add("Kingdoms");
        //arrayList1 = new ArrayList<String>();
        //adapter = new ArrayAdapter<>(MainActivity.this,android.R.layout.simple_list_item_1,arrayList);
        //listView.setAdapter(adapter);

        /*
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
                if (position == 0){
                    Intent intent = new Intent(MainActivity.this,cc.class);
                    startActivity(intent);
                }
                if (position == 1){
                    Intent intent = new Intent(MainActivity.this,tc.class);
                    startActivity(intent);
                }
                if (position == 2){
                    Intent intent = new Intent(MainActivity.this,k.class);
                    startActivity(intent);
                }


            }
        });
        listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> adapterView, View view, int position, long l) {
                if (position == 0) {

                    Boolean result = db.insertData((String) arrayList.get(position));
                    if (result == true){
                        Toast.makeText(MainActivity.this,"Added To Favorite",Toast.LENGTH_SHORT).show();
                    }else{
                        Toast.makeText(MainActivity.this, "Already Exist", Toast.LENGTH_SHORT).show();
                    }

                }
                if (position == 1){
                    Toast.makeText(MainActivity.this, "TC Added to Favorites", Toast.LENGTH_SHORT).show();
                }
                if (position == 2){
                    Toast.makeText(MainActivity.this, "K Added to Favorites", Toast.LENGTH_SHORT).show();
                }
                arrayList1.add(arrayList.get(position));
                arrayList.remove(position);
                adapter1.notifyDataSetChanged();
                adapter.notifyDataSetChanged();
                return true;
            }

        });

        adapter1 = new ArrayAdapter<>(this,android.R.layout.simple_list_item_1,arrayList1);
        listView1.setAdapter(adapter1);
        */

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        non_favourites_cursor.close();
        favourites_cursor.close();
    }

    @Override
    protected void onResume() {
        super.onResume();
        manageBothListViews();
    }

    public void showData(){
        ArrayList arrayList1 = db.getAllrecord();
        final ListAdapter adapter1 = new ArrayAdapter<>(MainActivity.this,android.R.layout.simple_list_item_1,arrayList1);
        listView1.setAdapter(adapter1);
    }

    private void manageBothListViews() {
        manageNonFavouritesListView();
        manageFavouritesListView();
    }

    private void manageNonFavouritesListView() {
        non_favourites_cursor = db.getFavouriteRows(false);
        if (non_favourites_adapter == null) {
            non_favourites_adapter = new SimpleCursorAdapter(
                    this,
                    android.R.layout.simple_list_item_1,
                    non_favourites_cursor,
                    new String[]{DB_Sqlite.FAVOURITES_COL_NAME},
                    new int[]{android.R.id.text1},
                    0
            );
            listView.setAdapter(non_favourites_adapter);
            setListViewHandler(listView,false);
        } else {
            non_favourites_adapter.swapCursor(non_favourites_cursor);
        }
    }
    private void manageFavouritesListView() {
        favourites_cursor = db.getFavouriteRows(true);
        if (favourites_adapter == null) {
            favourites_adapter = new SimpleCursorAdapter(
                    this,
                    android.R.layout.simple_list_item_1,
                    favourites_cursor,
                    new String[]{DB_Sqlite.FAVOURITES_COL_NAME},
                    new int[]{android.R.id.text1},
                    0
            );
            listView1.setAdapter(favourites_adapter);
            setListViewHandler(listView1,true);
        } else {
            favourites_adapter.swapCursor(favourites_cursor);
        }
    }

    private void setListViewHandler(ListView lv,  boolean favourite_flag) {
        if (!favourite_flag) {
            lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    if (non_favourites_cursor.getString(non_favourites_cursor.getColumnIndex(DB_Sqlite.FAVOURITES_COL_NAME)).equals("Complex Complex")) {
                        Intent intent = new Intent(MainActivity.this,cc.class);
                        startActivity(intent);
                    }
                    if (non_favourites_cursor.getString(non_favourites_cursor.getColumnIndex(DB_Sqlite.FAVOURITES_COL_NAME)).equals("Trix Complex")) {
                        Intent intent = new Intent(MainActivity.this,tc.class);
                        startActivity(intent);
                    }
                    if (non_favourites_cursor.getString(non_favourites_cursor.getColumnIndex(DB_Sqlite.FAVOURITES_COL_NAME)).equals("Kingdoms")){
                        Intent intent = new Intent(MainActivity.this,k.class);
                        startActivity(intent);
                    }
                }
            });
            lv.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
                @Override
                public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                    db.setAsFavourite(id);
                    manageBothListViews();
                    return true;
                }
            });
        } else {
            lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    if (favourites_cursor.getString(favourites_cursor.getColumnIndex(DB_Sqlite.FAVOURITES_COL_NAME)).equals("Complex Complex")) {
                        Intent intent = new Intent(MainActivity.this,cc.class);
                        startActivity(intent);
                    }
                    if (favourites_cursor.getString(favourites_cursor.getColumnIndex(DB_Sqlite.FAVOURITES_COL_NAME)).equals("Trix Complex")) {
                        Intent intent = new Intent(MainActivity.this,tc.class);
                        startActivity(intent);
                    }
                    if (favourites_cursor.getString(favourites_cursor.getColumnIndex(DB_Sqlite.FAVOURITES_COL_NAME)).equals("Kingdoms")){
                        Intent intent = new Intent(MainActivity.this,k.class);
                        startActivity(intent);
                    }
                }
            });
        }
    }
}
  • See the comments
  • This uses a CursorAdapter rather than ArrayAdapter.
  • This uses values (names Kingdoms etc) stored in the database when the databae is created. As such you should uninstall the App or Delete the App's data before running the changed code.


来源:https://stackoverflow.com/questions/59160185/send-a-row-from-one-listview-to-another-listview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!