I am new to android. I would like to know that how to display the data from database in listview. It does not add a data to database.I just display whatever we store in database.please help me to achieve this...Thanks in advance...
Use these classes this may help you
for database creation
package com.example.grapes;
import java.util.ArrayList;
import java.util.List;
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 {
// All Static variables
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "dataManager";
// Contacts table name
private static final String TABLE_DATAS = "datas";
// Contacts Table Columns names
private static final String KEY_ID = "id";
private static final String KEY_ITEM = "item";
private static final String KEY_COMMENT = "comment";
private static final String KEY_DATE = "date";
private static final String KEY_TIME = "time";
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// Creating Tables
@Override
public void onCreate(SQLiteDatabase db) {
String CREATE_DATAS_TABLE = "CREATE TABLE " + TABLE_DATAS + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_ITEM + " TEXT,"
+ KEY_COMMENT + " TEXT," + KEY_DATE + " TEXT," + KEY_TIME + " TEXT" + ")";
db.execSQL(CREATE_DATAS_TABLE);
}
// Upgrading database
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_DATAS);
// Create tables again
onCreate(db);
}
/**
* All CRUD(Create, Read, Update, Delete) Operations
*/
// Adding new contact
void addData(Datas data) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_ITEM, data.getItem()); // Contact Name
values.put(KEY_COMMENT, data.getComment()); // Contact Phone
values.put(KEY_DATE, data.getDate()); // Contact Name
values.put(KEY_TIME, data.getTime()); // Contact Phone
// Inserting Row
db.insert(TABLE_DATAS, null, values);
db.close(); // Closing database connection
}
// Getting single contact
Datas getData(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_DATAS, new String[] { KEY_ID,
KEY_ITEM, KEY_COMMENT, KEY_DATE, KEY_TIME}, KEY_ID + "=?",
new String[] { String.valueOf(id) }, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
Datas data = new Datas(Integer.parseInt(cursor.getString(0)),
cursor.getString(1), cursor.getString(2),cursor.getString(3), cursor.getString(4));
// return contact
return data;
}
Datas getItemOnly(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_DATAS, new String[] { KEY_ID,
KEY_ITEM, KEY_COMMENT, KEY_DATE, KEY_TIME}, KEY_ID + "=?",
new String[] { String.valueOf(id) }, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
Datas data = new Datas(Integer.parseInt(cursor.getString(0)),
cursor.getString(1), cursor.getString(2),cursor.getString(3), cursor.getString(4));
// return contact
return data;
}
// Getting All Contacts
public List<Datas> getAllDatas() {
List<Datas> dataList = new ArrayList<Datas>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_DATAS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Datas data = new Datas();
data.setID(Integer.parseInt(cursor.getString(0)));
data.setItem(cursor.getString(1));
data.setComment(cursor.getString(2));
data.setDate(cursor.getString(3));
data.setTime(cursor.getString(4));
// Adding contact to list
dataList.add(data);
} while (cursor.moveToNext());
}
// return contact list
return dataList;
}
// Updating single contact
public void updateDatas(int position, String value) {
SQLiteDatabase db = this.getWritableDatabase();
String update = "UPDATE datas SET comment = '"+ value +"' WHERE ID = " + position;
db.execSQL(update);
}
// Deleting single contact
public void deleteValues(int position) {
SQLiteDatabase db = this.getWritableDatabase();
position = position + 1;
String id = String.valueOf(position);
db.delete(TABLE_DATAS, KEY_ID + "="+id,null);
//Updating table
//Creating temporary table
String CREATE_TABLE_COPY = "CREATE TABLE " + "COPIED_TABLE" + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_ITEM + " TEXT,"
+ KEY_COMMENT + " TEXT," + KEY_DATE + " TEXT," + KEY_TIME + " TEXT" + ")";
db.execSQL(CREATE_TABLE_COPY);
// Copying necessary columns to new temporary table
String db_insert_command;
db_insert_command = "INSERT INTO COPIED_TABLE (" + KEY_ITEM +", " + KEY_COMMENT + ", " + KEY_DATE + ", " + KEY_TIME + ") SELECT " + KEY_ITEM +", " + KEY_COMMENT + ", " + KEY_DATE + ", " + KEY_TIME + " FROM "+ TABLE_DATAS;
System.out.println(db_insert_command);
db.execSQL(db_insert_command);
//Dropping old table
db.execSQL("DROP TABLE " + TABLE_DATAS);
//Creating old table again
String CREATE_TABLE = "CREATE TABLE " + TABLE_DATAS + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_ITEM + " TEXT,"
+ KEY_COMMENT + " TEXT," + KEY_DATE + " TEXT," + KEY_TIME + " TEXT" + ")";
db.execSQL(CREATE_TABLE);
//Copying all fields from temporary table to newly created old table
db.execSQL("INSERT INTO " + TABLE_DATAS + " SELECT * FROM COPIED_TABLE");
//Dropping temporary table
db.execSQL("DROP TABLE COPIED_TABLE");
db.close();
}
// Getting contacts Count
public int getDatasCount() {
String countQuery = "SELECT * FROM " + TABLE_DATAS;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
//cursor.close();
// return count
return cursor.getCount();
}
}
for the data-management use this class
package com.example.grapes;
public class Datas {
//private variables
int _id;
String _item;
String _comment;
String _date;
String _time;
// Empty constructor
public Datas(){
}
// constructor
public Datas(int id, String item, String comment, String date, String time){
this._id = id;
this._item = item;
this._comment = comment;
this._date = date;
this._time = time;
}
// constructor
public Datas(String item, String comment, String date, String time){
this._item = item;
this._comment = comment;
this._date = date;
this._time = time;
}
// getting ID
public int getID(){
return this._id;
}
// setting id
public void setID(int id){
this._id = id;
}
// getting name
public String getItem(){
return this._item;
}
// setting name
public void setItem(String item){
this._item = item;
}
// getting phone number
public String getComment(){
return this._comment;
}
// setting phone number
public void setComment(String comment){
this._comment = comment;
}
// getting phone number
public String getDate(){
return this._date;
}
// setting phone number
public void setDate(String date){
this._date = date;
}
// getting phone number
public String getTime(){
return this._time;
}
// setting phone number
public void setTime(String time){
this._time = time;
}
}
for the list-view use this
package com.example.grapes;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
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.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
public class ListviewActivity extends ListActivity {
AlertDialog.Builder alert;
EditText input;
private static final int TEXT_ID = 0;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
input = new EditText(this);
alert = new AlertDialog.Builder(this);
final DatabaseHandler db = new DatabaseHandler(this);
System.out.println("Entered ListViewActivity");
ArrayList<HashMap<String, String>> Items = new ArrayList<HashMap<String, String>>();
System.out.println("Arraylist hashmap declared");
// Reading all values
Log.d("Reading: ", "Reading all contacts..");
List<Datas> data = db.getAllDatas();
for (Datas val : data) {
// Writing values to map
HashMap<String, String> map = new HashMap<String, String>();
map.put("comment",val.getComment());
map.put("date", val.getDate());
map.put("time", val.getTime());
map.put("item", val.getItem());
Items.add(map);
}
// Adding Items to ListView
ListAdapter adapter = new SimpleAdapter(this, Items,
R.layout.list_item,new String[] { "date", "time", "comment", "item" },
new int[] {R.id.date, R.id.time, R.id.capacity, R.id.price });
setListAdapter(adapter);
// selecting single ListView item
ListView lv = getListView();
lv.setLongClickable(true);
lv.setOnItemLongClickListener(new OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
final int pos, long id) {
// TODO Auto-generated method stub
// Log.v("long clicked","pos"+" "+pos);
alert.setTitle("Confirm Delete");
// set dialog message
alert
.setMessage("Do you want to DELETE this entry?")
.setCancelable(false)
.setPositiveButton("Do it!",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// if this button is clicked, close
// current activity
db.deleteValues(pos);
Intent i = new Intent(getApplicationContext(), ListviewActivity.class);
startActivity(i);
}
})
.setNegativeButton("I need this",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// if this button is clicked, just close
// the dialog box and do nothing
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alert.create();
// show it
alertDialog.show();
return true;
}
});
lv.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1,
final int pos, long id) {
// TODO Auto-generated method stub
input.setId(TEXT_ID);
alert.setView(input);
// Log.v("long clicked","pos"+" "+pos);
alert.setTitle("Edit the Comment?");
String dat = ((TextView) arg1.findViewById(R.id.date)).getText().toString();
String tim = ((TextView) arg1.findViewById(R.id.time)).getText().toString();
String itm = ((TextView) arg1.findViewById(R.id.price)).getText().toString();
// set dialog message
alert
.setMessage("Edit Comment of " + itm + " on " + dat + " " + tim + " ?")
.setCancelable(false)
.setPositiveButton("Do it!",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// if this button is clicked, close
// current activity
String value = input.getText().toString();
Log.d("User name: ",value);
//return;
// db.execSQL(TABLE_DATAS, KEY_COMMENT, KEY_ID + " = " + string, null);
db.updateDatas(pos+1, value);
Intent j = new Intent(getApplicationContext(), ListviewActivity.class);
startActivity(j);
}
})
.setNegativeButton("I need this",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// if this button is clicked, just close
// the dialog box and do nothing
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alert.create();
// show it
alertDialog.show();
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main_menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case R.id.home:
ListviewActivity.this.finish();
return true;
case R.id.about:
Toast.makeText(getApplicationContext(), "This is collection and is created by amdel corporation",
Toast.LENGTH_LONG).show();
return true;
case R.id.exit:
finish();
System.exit(0);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
for insertion operation use this
db.addData(new Datas(item, comment, date, time));
To read all items
for (Datas d : datas) {
String log = "Id: "+d.getID()+" ,Item: " + d.getItem() + " ,Comment: " + d.getComment() + " ,Date: " + d.getDate() + ",Comment: " + d.getTime();
// Writing Contacts to log
Log.d("Item: ", log);
}
To delete from the listview
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
final int pos, long id) {
// TODO Auto-generated method stub
// Log.v("long clicked","pos"+" "+pos);
alert.setTitle("Confirm Delete");
// set dialog message
alert
.setMessage("Do you want to DELETE this entry?")
.setCancelable(false)
.setPositiveButton("Do it!",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// if this button is clicked, close
// current activity
db.deleteValues(pos);
Intent i = new Intent(getApplicationContext(), ListviewActivity.class);
startActivity(i);
}
})
.setNegativeButton("I need this",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// if this button is clicked, just close
// the dialog box and do nothing
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alert.create();
// show it
alertDialog.show();
return true;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With