简体   繁体   中英

how to implement OnItemClickListener in simpleadapter? code delete, update etc.,

I think I have to code in MainActivity.java only. But I don't know how to implement OnItemClickListener() . when I write data in two EditTexts and click insert button, it appears in the listView through simpleadapter . when I select one of row in listView and click delete button, it should be removed from listView . I have coded "insert" but I don't know how to code delete, update, onitemclicklistener . Is anybody know how to code? thanks.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.eee.MainActivity">

    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <EditText
            android:id="@+id/eng"
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="wrap_content"
            />
        <EditText
            android:id="@+id/kor"
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="wrap_content"
            />
    </LinearLayout>
    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <Button
            android:id="@+id/ins"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="INS"
            android:onClick="onClick"
            />
        <Button
            android:id="@+id/del"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="DEL"
            android:onClick="onClick"
            />
        <Button
            android:id="@+id/upd"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="UPD"
            android:onClick="onClick"
            />
    </LinearLayout>
    <ListView
        android:id="@+id/list"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        />
</LinearLayout>

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal" android:layout_width="match_parent"
    android:layout_height="match_parent">
    <TextView
        android:id="@+id/text1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="10sp"
        android:textStyle="bold" >
    </TextView>
    <TextView
        android:id="@+id/text2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="10sp">
    </TextView>
</LinearLayout>

public class DBAdapter {
    private DatabaseHelper mHelper;
    private SQLiteDatabase mDb;

    private static final String DATABASE_NAME = "projectdb";
    private static final int DATABASE_VERSION = 1;
    private static String SQL_TABLE_CREATE;
    private static String TABLE_NAME;

    public static final String SQL_CREATE_PROJECT =
            "create table project (_id integer primary key autoincrement,"
                    + " eng text not null,"
                    + " kor text not null"
                    + ")";

    private final Context mCxt;

                    private static class DatabaseHelper extends SQLiteOpenHelper {

                        public DatabaseHelper(Context context) {
                            super(context, DATABASE_NAME, null, DATABASE_VERSION);
                        }

                        public DatabaseHelper(Context context, String name,
                                              SQLiteDatabase.CursorFactory factory, int version) {
                            super(context, name, factory, version);
                            // TODO Auto-generated constructor stub
                        }

                        @Override
                        public void onCreate(SQLiteDatabase db) {
                            // TODO Auto-generated method stub
                            db.execSQL(SQL_TABLE_CREATE);
                        }

                        @Override
                        public void onOpen(SQLiteDatabase db) {
                            // TODO Auto-generated method stub
                            super.onOpen(db);
                        }

                        @Override
                        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
                            // TODO Auto-generated method stub
                            db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
                            onCreate(db);
                        }
                    }

    public DBAdapter(Context cxt, String sql, String tableName) {
        this.mCxt = cxt;
        SQL_TABLE_CREATE = sql;
        TABLE_NAME = tableName;
    }

    public DBAdapter open() throws SQLException {
        mHelper = new DatabaseHelper(mCxt);
        mDb = mHelper.getWritableDatabase();
        return this;
    }

    public void close() {
        mHelper.close();
    }

    public long insertTable(ContentValues values) {
        return mDb.insert(TABLE_NAME, null, values);
    }

    public boolean deleteTable(String pkColumn, long pkData) {
        return mDb.delete(TABLE_NAME, pkColumn + "=" + pkData, null) > 0;
        /*db.delete("memos", "_id=" + memo.getId(), null);
        db.delete(String table, String whereClause, String[] whereArgs);*/
    }

    public Cursor selectTable(String[] columns, String selection,
                              String[] selectionArgs, String groupBy,
                              String having, String orderBy) {
        return mDb.query(TABLE_NAME, columns, selection, selectionArgs, groupBy, having, orderBy);
    }

    public boolean updateTable(ContentValues values, String pkColumn, long pkData) {
        return mDb.update(TABLE_NAME, values, pkColumn + "=" + pkData, null) > 0;
    }
}

public class Project {
    private long id;
    private String eng;
    private String kor;

    public Project(long id, String eng){
        this.id = id;
        this.eng = eng;
    }
    public Project(long id, String eng, String kor) {
        this.id = id;
        this.eng = eng;
        this.kor = kor;
    }

    public long getId() {
        return id;
    }

    public String getEng() {
        return eng;
    }

    public String getKor() {
        return kor;
    }
}

public class MainActivity extends AppCompatActivity {
    private Button bt;
    private EditText et1;
    private EditText et2;
    private ListView lv;
    DBAdapter db;
    ArrayList<HashMap<String,String>> list;
    SimpleAdapter sap;
    Project project;
    private static final String TAG = "LogTest";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        bt = (Button)findViewById(R.id.ins);
        et1 = (EditText)findViewById(R.id.eng);
        et2 = (EditText)findViewById(R.id.kor);
        //
        list = new ArrayList<HashMap<String,String>>();
        makeDS();

        sap = new SimpleAdapter(this, list, R.layout.memberlist, new String[] {"eng", "kor"}, new int[] {R.id.text1, R.id.text2});
        lv.setAdapter(sap);

        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                /*sap.getItem(position);
                et1.setText(project.getEng());
                et2.setText(project.getKor());*/
                Log.v(TAG, "list click");
            }
        });
        db.close();
    }

    public void makeDS(){
        lv = (ListView)findViewById(R.id.list);
        list.clear();
        db = new DBAdapter(this, DBAdapter.SQL_CREATE_PROJECT, "project");

        db.open();
        String columns[] = {"eng", "kor"};
        Cursor cursor = db.selectTable(columns, null, null, null, null, null);

        if(cursor.moveToFirst()) {
            do{
                HashMap<String,String> map = new HashMap<String,String>();
                map.put("eng", cursor.getString(0));
                map.put("kor", cursor.getString(1));
                list.add(map);
            }while(cursor.moveToNext());
        }
    }

    public void onClick(View v) {
        // TODO Auto-generated method stub
        // DBAdapter db;
        switch (v.getId()) {
            case R.id.ins:
                String streng = et1.getText().toString();
                String strkor = et2.getText().toString();

                db = new DBAdapter(this, DBAdapter.SQL_CREATE_PROJECT, "project");
                db.open();

                ContentValues value = new ContentValues();
                value.put("eng", streng);
                value.put("kor", strkor);
                db.insertTable(value);
                break;

            case R.id.del:
                db = new DBAdapter(this, DBAdapter.SQL_CREATE_PROJECT, "project");
                db.open();
                db.deleteTable("_id", project.getId());
                Log.v(TAG, "del button click");
                break;
        }
        makeDS();
        sap.notifyDataSetChanged();
        db.close();
    }
}

First of all declare your buttons in listView so when you click on delete, the app will delete the object you want to delete, otherwise it wo`nt know which object of the listView you want to delete Second you should implementation of OnClickListener in your MainActivity.class when inside the SimpleAdapter Constructor as following:

    sap = new SimpleAdapter(this, list, R.layout.memberlist, new String[] {"eng", "kor"}, new int[] {R.id.text1, R.id.text2}) {

                        @Override
                        public View getView(final int position, View convertView,
                                            ViewGroup parent) {
                            ViewGroup layout = (ViewGroup) super.getView(position,
                                    convertView, parent);
                            delete = (Button) layout.findViewById(R.id.delete_button);
                            edit = (Button) layout.findViewById(R.id.edit_button);

                            delete.setTag(position);
                            edit.setTag(position);
                            delete.setOnClickListener(new View.OnClickListener() {

                                @Override
                                public void onClick(View v) {
                                    list.remove(position);
                                    notifyDataSetChanged();

                                }
                            });
                            edit.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View view) {
                                    //do smth
                                }

                            });

                       return layout;
}
};

and then set your adapter

Please Change

new String[] {"eng", "kor"} to String[] tmpdata= {"eng", "kor"};
 sap = new SimpleAdapter(this, list, R.layout.memberlist, tmpdata, new int[] {R.id.text1, R.id.text2});

and now listview.onItemClickListener

 et1.setText(tmpData[0]);
            et2.setTexttmpdata[1] );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM