jeudi 6 août 2015

How to pass ID (Primary Key) in ListView in OnItemClickListener to get data from SQLite Database in Android app?

I need to pass ID, which is a primary key in SQLite Database in android app, to get the data from the Database related to the list item in ListView. When the data is received, it is then passed to another activity using intent. Everything else is working properly but I am not able to get the ID of the row in the Database according to list item clicked.

Following is the DatabaseHandler.java:

package com.Its_Kush.comety_new;

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

public class DatabaseHandler extends SQLiteOpenHelper {

public DatabaseHandler(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
    // TODO Auto-generated constructor stub
}

// MainActivity
public static final String dbID = "ID";
public static final String dbNAME = "Name";
public static final String dbEMI = "Emi";
public static final String dbMONTHLY_EXP = "Monthly_Exp";
public static final String dbMEMBERS = "Members";
//
public static final String DATABASE_NAME = "Comety_Database.db";
public static final String TABLE_NAME = "Comety_Database_Table";
public static final int DATABASE_VERSION = 1;
SQLiteDatabase db;

//

@Override
public void onCreate(SQLiteDatabase db) {
    // TODO Auto-generated method stub
    db.execSQL("CREATE TABLE " + TABLE_NAME + "(" + dbID
            + " INTEGER PRIMARY KEY AUTOINCREMENT, " + dbNAME + " TEXT, "
            + dbEMI + " REAL, " + dbMONTHLY_EXP + " REAL, " + dbMEMBERS
            + " INTEGER " + ")");
}

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

public boolean insertData(String name, double emi, double monthly_exp,
        int members) {
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues content = new ContentValues();
    content.put(dbNAME, name);
    content.put(dbEMI, emi);
    content.put(dbMONTHLY_EXP, monthly_exp);
    content.put(dbMEMBERS, members);
    long result = db.insert(TABLE_NAME, null, content);
    if (result == -1)
        return false;
    else
        return true;
}

public Cursor viewOne(String id){
    SQLiteDatabase db = this.getWritableDatabase();
    Cursor dataShow = db.rawQuery("SELECT * FROM " + TABLE_NAME + " WHERE ID = " + id, null);
    return dataShow;
}

public Cursor viewAll(){
    SQLiteDatabase db = this.getWritableDatabase();
    Cursor dataShow = db.rawQuery("SELECT * FROM " + TABLE_NAME, null);
    return dataShow;
}

public boolean updateData(String id, String name, double emi, double monthly_exp, int members){
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues content = new ContentValues();
    content.put(dbID, id);
    content.put(dbNAME, name);
    content.put(dbEMI, emi);
    content.put(dbMONTHLY_EXP, monthly_exp);
    content.put(dbMEMBERS, members);
    db.update(TABLE_NAME, content, "id = ?", new String[] { id });
    return true;
}

public int deleteData(String id){
    SQLiteDatabase db = this.getWritableDatabase();
    return db.delete(TABLE_NAME, "ID = ?", new String[] { id });
}

public void deleteAll(){
    SQLiteDatabase db = this.getWritableDatabase();
    db.execSQL("DELETE FROM " +  TABLE_NAME);
}

public void resetId(){
    SQLiteDatabase db = this.getWritableDatabase();
    db.execSQL("delete from sqlite_sequence where name = '" + TABLE_NAME + "'");
}

}

Following is the class containing ListView:

    package com.Its_Kush.comety_new;

import java.util.ArrayList;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class ShowActivity extends AppCompatActivity {

DatabaseHandler dbComety = new DatabaseHandler(this);
ArrayList<String> listItems = new ArrayList<String>();
ArrayAdapter<String> adapter;
ListView list1;
Button submit, delete;
EditText id;
String name, str;
double monthly_exp, emi;
short members;

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

    list1 = (ListView) findViewById(R.id.list1);

    show_all();

    list1.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View v,
                int position, long id) {
            // TODO Auto-generated method stub
            str = (String) ((TextView) v).getText();
            Cursor dataOneView = dbComety.viewOne(str.substring(0, 2));
            if (dataOneView.moveToFirst()) {
                name = dataOneView.getString(1);
                emi = dataOneView.getDouble(2);
                monthly_exp = dataOneView.getDouble(3);
                members = dataOneView.getShort(4);
            }
            // showMessage("Value", "Name: " + name + "\nemi:" + emi
            // + "\nm_exp" + monthly_exp + "\nmembers: " + members);
            // id.setText("");

            Intent submit = new Intent(ShowActivity.this,
                    MainActivity.class);
            submit.putExtra("name", name);
            submit.putExtra("emi", emi);
            submit.putExtra("members", members);
            submit.putExtra("monthly_exp", monthly_exp);

            //
            startActivity(submit);
        }
    });

    list1.setOnItemLongClickListener(new OnItemLongClickListener() {

        @Override
        public boolean onItemLongClick(AdapterView<?> arg0, View v,
                int arg2, long arg3) {
            // TODO Auto-generated method stub
            str = (String) ((TextView) v).getText();
            showMessage("Delete", "Are you sure?");
            return true;
        }
    });

}

DialogInterface.OnClickListener cancelClickListner = new DialogInterface.OnClickListener() {

    @Override
    public void onClick(DialogInterface arg0, int arg1) {
        // TODO Auto-generated method stub
        finish();
    }
};

public void show_all() {
    Cursor dataView = dbComety.viewAll();
    if (dataView.getCount() == 0) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("Error");
        builder.setCancelable(false);
        builder.setMessage("No data found.").setPositiveButton("Back", cancelClickListner).show();
        dbComety.resetId();

    } else {

        String buffer = null;
        if (dataView.moveToFirst()) {
            do {
                buffer = dataView.getString(0) + "\t\t"
                        + dataView.getString(1);
                listItems.add(buffer);
            } while (dataView.moveToNext());
        }
    }
    adapter = new ArrayAdapter<String>(this, R.layout.textview_listitems,
            listItems);

    list1.setAdapter(adapter);
}

DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which) {
        switch (which) {
        case DialogInterface.BUTTON_POSITIVE:
            // Yes button clicked

            int deletedRows = dbComety.deleteData(str.substring(0, 2));
            if (deletedRows > 0) {
                Toast.makeText(ShowActivity.this, R.string.deleted,
                        Toast.LENGTH_SHORT).show();
                adapter.clear();
                show_all();
                adapter.notifyDataSetChanged();
            } else

                Toast.makeText(ShowActivity.this, R.string.not_deleted,
                        Toast.LENGTH_SHORT).show();
            break;

        case DialogInterface.BUTTON_NEGATIVE:
            // No button clicked
            break;
        }
    }
};

public void showMessage(String title, String message) {
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setTitle(title);
    builder.setMessage(message)
            .setPositiveButton("Yes", dialogClickListener)
            .setNegativeButton("No", dialogClickListener);
    builder.show();
}

DialogInterface.OnClickListener deleteAllClickListener = new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which) {
        switch (which) {
        case DialogInterface.BUTTON_POSITIVE:
            // Yes button clicked

            dbComety.deleteAll();
            adapter.clear();
            show_all();
            adapter.notifyDataSetChanged();
            break;

        case DialogInterface.BUTTON_NEGATIVE:
            // No button clicked
            break;
        }
    }
};

@Override
public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this
                                                // adds items to the action
                                                // bar if it is present.
    getMenuInflater().inflate(R.menu.show, menu);
    return true;
}



@Override
    public boolean onOptionsItemSelected(MenuItem item) { 
AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.delete_all) {
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle("Delete all");
            builder.setMessage("Are you sure?")
                    .setPositiveButton("Yes", deleteAllClickListener)
                    .setNegativeButton("No", deleteAllClickListener);
            builder.show();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}

I am currently using a String to store the list item TextView data and then getting the id using the substring method. How can I directly get the ID of the row in Database?

Aucun commentaire:

Enregistrer un commentaire