jeudi 4 février 2016

How to delete a selected row from SQLite by OnItemLongClickListener ListView

I am trying to delete a selected data from SQLite by OnItemLongClickListener on a ListView but can't seem to manage it,I can only do either delete all or just delete the last row of the data.Here is my code;

addressActivity.class

public class addressActivity extends Activity{
addressDatabase myDb;
ListView listView;
EditText savedName,savedIP;
ImageButton imgAddData;
ImageButton imgDelData;

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

    myDb = new addressDatabase(this);
    savedName = (EditText)findViewById(R.id.editName);
    savedIP = (EditText)findViewById(R.id.editIP);
    imgAddData = (ImageButton)findViewById(R.id.imgBtnAdd);
    imgDelData = (ImageButton)findViewById(R.id.imgBtnDel);

    listData();
    delData();
    addData();
    getListView();
    listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener(){
        @Override
        public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
            SQLiteDatabase db = myDb.getWritableDatabase();
            //int isDeleted = db.delete(myDb.TABLE_NAME,"ID = (SELECT MAX(ID) FROM " +myDb.TABLE_NAME+")",null);
            int isDeleted = db.delete(myDb.TABLE_NAME,"ID = (SELECT ID FROM " +myDb.TABLE_NAME+" WHERE ID = ?)",null);
            if (isDeleted > 0){
                Toast.makeText(getBaseContext(),"Address deleted !",Toast.LENGTH_SHORT).show();
            }else{
                Toast.makeText(getBaseContext(),"Address not deleted !",Toast.LENGTH_SHORT).show();
            }
            listData();
            return true;
        }
    });
}

public void addData(){
    imgAddData.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {
            Intent openFrom = new Intent(addressActivity.this, addActivity.class);
            startActivity(openFrom);
        }
    });
}

public void delData() {
    imgDelData.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {
            Toast.makeText(getBaseContext(),"Long press on an Address to delete",Toast.LENGTH_LONG).show();
            //Intent refresh = new Intent(addressActivity.this,addressActivity.class);
            //startActivity(refresh);

        }
    });
}

public ListView getListView() {
    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            //Object item = listView.getItemAtPosition(position);
            Intent openFrom = new Intent(addressActivity.this, liveActivity.class);
            startActivity(openFrom);
        }
    });
    return listView;
}

public void listData(){

    String[] res = myDb.getAllData();
    listView = (ListView)findViewById(R.id.listView);
    ArrayAdapter adapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1,res);
    //viewAll();
    listView.setAdapter(adapter);
    if(adapter.isEmpty()){
        Toast.makeText(getBaseContext(),"There is no Address !",Toast.LENGTH_LONG).show();
    }
}}

addActivity.class

public class addActivity extends Activity{
addressDatabase myDb;
EditText savedName,savedIP;
Button btnSave;
Button btnBack;

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

    savedName = (EditText)findViewById(R.id.editName);
    savedIP = (EditText)findViewById(R.id.editIP);
    btnSave = (Button)findViewById(R.id.btnSave);
    btnBack = (Button)findViewById(R.id.btnBack);

    myDb = new addressDatabase(this);

    addData();

    btnBack.setOnClickListener(new View.OnClickListener(){
        public void onClick(View view){
            Intent openFrom = new Intent(addActivity.this,addressActivity.class);
            startActivity(openFrom);
            finish();
        }
    });
}
public void addData(){
    btnSave.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            boolean isInserted = myDb.insertData(savedName.getText().toString(),
                    savedIP.getText().toString());
            if (isInserted == true) {
                Toast.makeText(getBaseContext(), "Address Saved !", Toast.LENGTH_SHORT).show();
                savedName.setText("");
                savedIP.setText("");
            } else {
                Toast.makeText(getBaseContext(), "Address not Saved", Toast.LENGTH_SHORT).show();
            }
        }
    });
}}

addressDatabase.class

public class addressDatabase extends SQLiteOpenHelper {

public static final String DATABASE_NAME = "cybereyeview.db";
public static final String TABLE_NAME = "cybereyeview_address";
public static final String COL_ID = "ID";
public static final String COL_NAME = "Name";
public static final String COL_IP = "IP";

public addressDatabase(Context context) {
    super(context, DATABASE_NAME, null, 1);
}

@Override
public void onCreate(SQLiteDatabase db) {
    db.execSQL("create table " + TABLE_NAME + " (ID INTEGER PRIMARY KEY AUTOINCREMENT,NAME TEXT,IP TEXT)");
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
    onCreate(db);
}

public boolean insertData(String name,String ip){
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues contentValues = new ContentValues();
    contentValues.put(COL_NAME, name);
    contentValues.put(COL_IP, ip);
    long result = db.insert(TABLE_NAME, null, contentValues);
    if(result == -1){
        return false;
    }else {
        return true;
    }
}

public String[] getAllData() {
    SQLiteDatabase db = this.getWritableDatabase();
    Cursor res = db.rawQuery("SELECT * FROM " + TABLE_NAME, null);
    res.moveToFirst();
    ArrayList<String> arrayList = new ArrayList<String>();
    while(!res.isAfterLast()){
        arrayList.add(res.getString(res.getColumnIndex("NAME"))+"\n"+(res.getString(res.getColumnIndex("IP"))));
        res.moveToNext();
    }

    res.close();
    return arrayList.toArray(new String[arrayList.size()]);
}}

Sorry if my codes are kinda messy since I'm a beginner in Android Studio

Thanks in advance

Aucun commentaire:

Enregistrer un commentaire