Adding listener to ListView - android

I've created a ListView from an SQLite database but am stuck on how to add a listener to each ListView item so that when an item is clicked I can display another page with more information on that item. The database is just a sample. Any help would be appreciated.
public class Database extends ListActivity {
private final String SAMPLE_DB_NAME = "myFriendsDb";
//private final String SAMPLE_TABLE_NAME = "friends";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ArrayList<String> results = new ArrayList<String>();
SQLiteDatabase db = null;
try {
db = this.openOrCreateDatabase(SAMPLE_DB_NAME, MODE_PRIVATE, null);
db.execSQL("CREATE TABLE IF NOT EXISTS people" +
" (LastName VARCHAR, FirstName VARCHAR," +
" Country VARCHAR, Age INT(3));");
db.execSQL("INSERT INTO people" +
" Values ('Jones','Bob','UK',30);");
db.execSQL("INSERT INTO people" +
" Values ('Smith','John','UK',40);");
db.execSQL("INSERT INTO people" +
" Values ('Thompson','James','UK',50);");
Cursor c = db.rawQuery("SELECT FirstName, LastName FROM people", null);
if (c != null ) {
if (c.moveToFirst()) {
do {
String firstName = c.getString(c.getColumnIndex("FirstName"));
String lastName = c.getString(c.getColumnIndex("LastName"));
results.add("" + firstName + " " + lastName);
}while (c.moveToNext());
}
}
this.setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,results));
} catch (SQLiteException se ) {
Log.e(getClass().getSimpleName(), "Could not create or Open the database");
} finally {
if (db != null)
db.execSQL("DELETE FROM people");
db.close();
}
}
}

there are many ways to solve your problem. One possible solution is this: you simply need to implement protected method onListItemClick(ListView l, View v, int position, long id) in your ListActivity.
public class Database extends ListActivity {
//YOUR CODE ABOVE HERE...
public static final String SHOWITEMINTENT_EXTRA_FETCHROWID = "fetchRow";
public static final int ACTIVITY_SHOWITEM = 0; /*Intent request user index*/
#Override
protected void onListItemClick(ListView l, View v, int position, long id){
/*
position variable holds the position of item you clicked...
do your stuff here. If you want to send to another page, say another activity
that shows your stuff, you can always use an intent
example:
*/
Intent tmpIntent = new Intent(this, YourActivityForShowingItem.class);
tmpIntent.putExtra(SHOWITEMINTENT_EXTRA_FETCHROWID, position);
startActivityForResult(tmpIntent, ACTIVITY_SHOWITEM);
}
}
Alternately, you can access the ListView of your listActivity using getListView(), and call the setters for listeners or context menu as you would have done with a regular ListView object. For instance, this function that sets a listener using this approach:
private void setMyListListener(){
getListView().setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> a, View v, int position, long id){
/*same fake code as above for calling another activity using an intent:*/
Intent tmpIntent = new Intent(this, YourActivityForShowingItem.class);
tmpIntent.putExtra(SHOWITEMINTENT_EXTRA_FETCHROWID, position);
startActivityForResult(tmpIntent, ACTIVITY_SHOWITEM);
}
});
}
This function can be called by your onCreate(...) function afterwards if you want your click listener to be configured the same way for the whole duration of your activity.

Related

SQLite Database item comes back after restarting Activity even though it was deleted

On deleting the item from the Listview the item gets deleted at that time, but on coming back to the activity the item reappears.
This is my Main2Activity code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
position = intent.getIntExtra("position", 0);
adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, listItem);
listView.setAdapter(adapter);
viewData1();
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, final int pos, long id) {
final int itemToDelete = pos;
new AlertDialog.Builder(Main2Activity.this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle("Are you sure?")
.setMessage("Do you want to delete this location?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
listItem.remove(itemToDelete);
databaseHelper1.deleteLocation(itemToDelete, position);
adapter.notifyDataSetChanged();
}
}
)
.setNegativeButton("No", null)
.show();
return true;
}
});
}
private void viewData1() {
Cursor cursor = databaseHelper1.viewData1(position);
if (cursor.getCount() == 0) {
Toast.makeText(this, "No data to show", Toast.LENGTH_SHORT).show();
} else {
while (cursor.moveToNext()) {
Log.i("message", "Data got");
listItem.add(cursor.getString(1));
}
adapter.notifyDataSetChanged();
}
}
DatabaseHelper:
public void deleteLocation(int itemToDelete,int position)
{
SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
String itemDelete = Integer.toString(itemToDelete);
Log.i("itemdel",itemDelete);
if(position ==0)
{
String Id = (ID1);
Log.i("Id",Id);
String query = " Delete from "+DB_TABLE1 + " where "+ Id + " = " + itemDelete;
sqLiteDatabase.execSQL(query);
sqLiteDatabase.delete(DB_TABLE1,ID1 + " = "+ itemDelete, null);
sqLiteDatabase.compileStatement(query);
Log.i("del"," executed")
}
}
public Cursor viewData1(int position)
{
SQLiteDatabase sqLiteDatabase = this.getReadableDatabase();
Cursor cursor = null;
if (position ==0)
{
String query = "Select * from " + DB_TABLE1;
cursor = sqLiteDatabase.rawQuery(query, null);
}
return cursor;
}
What happens is:
Before Deleting:
After Deleting garden:
On restarting activity:
How do I commit the delete to the database? Thanks.
Your issue is that you are assuming that position (3rd parameter passed to the onItemLongClick method) directly relates to the id of the row.
You cannot rely on a correlation between position and id.
The first position in the list will be at position 0. The lowest ID allocated (unless forced) will be 1. However adding 1 is not a solution as even though it may initially work. As soon as you delete anything other than the last item in the list then an id is omitted from the list of id's and you may not delete a row or you may delete a different row.
The most sensible/easiest fix is to utilise a CursorAdapter i.e. SimpleCursorAdapter in which case the 4th parameter to onItemClick and onItemLongClick (long l) will be the actual id. However, to utilise a CursorAdapter you MUST have the id column named as _id (hence why there is the constant BaseColumns._ID).
You could always rename the column when extracting it using AS e.g. SELECT rowid AS _id, * FROM the_table; (which will select all existing columns AND the id column).
Here's a link to a more comprehensive answer with options for other adapter Deleting item from ListView and Database with OnItemClickListener

Deleting database items in a ListView (created from an ArrayAdapter)

I have created a database which is displayed in a ListView using an ArrayAdapter. I want a selected ListView item to be deleted when a ContextMenu pops up with a delete option as depicted below:
I have a class for handling all the database functions like delete. When I use a normal onCLicklistener with a button, the delete function is performed correctly, i.e it deletes the correct database entry and reaches the if (cursor.moveToFirst()) line. When I make use of the delete menu item, it does not reach the if (cursor.moveToFirst()) line in the attached delete handler function and therefore does not delete the entry (attached after the ListView code snippet below is the delete handler).
Any help/guidance/examples will be greatly appreciated.
My ListView is populated as follows:
public class Listview extends AppCompatActivity
{
private ListView users;
FloatingActionButton fab;
MyDBHandler dbHandler;
ArrayAdapter<String> arrayAdapter;
String lists;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
StrictMode.ThreadPolicy policy = new
StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
setContentView(R.layout.activity_listview);
// Create back button in action bar
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
users = (ListView) findViewById(R.id.clientlst);
// Floating Action bar for adding new data entries
fab = (FloatingActionButton) findViewById(R.id.fab1);
MyDBHandler dbHandler = new MyDBHandler(getApplicationContext());
lists = dbHandler.loadHandler();
//Create a list of the saved database String array items and split into
Strings
ArrayList<String> list = new ArrayList<>
(Arrays.asList(lists.split("\n")));
// Create the List view adapter
arrayAdapter = new ArrayAdapter<String>(Listview.this,
android.R.layout.simple_list_item_1, android.R.id.text1, list)
{
#Override // Edit the Text colour of the Listview items
public View getView(int position, View convertView, ViewGroup parent)
{
String Items = arrayAdapter.getItem(position);
String[] separated = Items.split(":");
String Name123 = separated[1]; // This will contain "Name"
TextView textView = (TextView) super.getView(position,
convertView, parent);
textView.setTextColor(Color.BLUE);
textView.setText(Name123);
return textView;
}
};
users.setAdapter(arrayAdapter);
registerForContextMenu(users);
// Create an action to be performed by each click of an item in the
users.setOnItemClickListener
(
new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View
view, int position, long id) {
String Items = arrayAdapter.getItem(position);
String[] separated = Items.split(":");
String ip = separated[5]; // This will contain "PORT address"
String port = separated[3]; // This will contain "IP number"
Toast.makeText(Listview.this, port + ip,
Toast.LENGTH_LONG).show();
} // onItemClick
} // OnItemClickListener View
); // OnItemClickListener
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view)
{
Toast.makeText(Listview.this, "Fab
Clicked", Toast.LENGTH_LONG).show();
}
}
);
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenu.ContextMenuInfo menuInfo)
{
super.onCreateContextMenu(menu, v, menuInfo);
menu.setHeaderTitle("Choose an option");
MenuInflater inflator = getMenuInflater();
inflator.inflate(R.menu.example_menu, menu);
}
#Override
public boolean onContextItemSelected(MenuItem item)
{
AdapterView.AdapterContextMenuInfo info =
(AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
switch (item.getItemId())
{
case R.id.option_1:
arrayAdapter.getItem(info.position);
MyDBHandler dbHandler = new MyDBHandler(getApplicationContext());
String Items= arrayAdapter.getItem(info.position);
String[] separated = Items.split(":");
String ip = separated[3]; // This will
contain "IP addr"
String names = separated[1]; // This will
contain "Name"
Log.d("LATE",names + ip);
dbHandler.deleteHandler(names,ip);
arrayAdapter.notifyDataSetChanged(); // Refresh the
listview
Toast.makeText(this, "Deleted", Toast.LENGTH_SHORT).show();
Intent listviews1 = new Intent(Listview.this, Listview.class);
startActivity(listviews1);
return true;
case R.id.option_2:
Intent listviews2 = new Intent(Listview.this, Listview.class);
startActivity(listviews2);
Toast.makeText(this, "Updated", Toast.LENGTH_SHORT).show();
return true;
default:
return super.onContextItemSelected(item);
}
}
}
The delete handler function of the database is as follows:
public void deleteHandler(String username, String IP)
{
//boolean result = false;
String query = "Select*FROM " + TABLE_USER + " WHERE " + COLUMN_NAME + "
= '" + String.valueOf(username) + "'" + " and " + COLUMN_ID + " = '" +
String.valueOf(IP) + "'";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(query, null);
Log.d ("MEH", String.valueOf(cursor));
User user = new User();
if (cursor.moveToFirst())
{
user.setUserName(cursor.getString(2));
user.setID(cursor.getString(3));
db.delete(TABLE_USER, COLUMN_NAME + "=? and " + COLUMN_ID + "=?",
new String[]
{
String.valueOf(user.getUserName()),
String.valueOf(user.getID())
});
cursor.close();
//result = true;
}
db.close();
//return result;
}
You aren't calling any method to delete the item from the database from your users.setOnItemClickListener
As you added in your comment, all you are doing is trying to delete the item from your ActionBar's onItemClicked method.
Do the same inside your OnItemClickListener
Update2: Change in requirement
users.setLongClickable(true);
users.setOnItemLongClickListener(new OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView<?> parent, View v, int position, long id) {
//Do your tasks here
AlertDialog.Builder alert = new AlertDialog.Builder(
YourActivity.this);
alert.setTitle("Alert!!");
alert.setMessage("Choose an option");
alert.setPositiveButton("Edit", new OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//do your work here
dialog.dismiss();
}
});
alert.setNegativeButton("Delete", new OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//perform your delete callback here
dialog.dismiss();
}
});
alert.show();
return true;
}
});
Update1: Explanation to Amiya's answer,
The reason why
cursor.moveToFirst() isn't a good option is because this statement
is unnecessary. The compiler knows exact spot to hit when it will
enter inside your DB. One usually perform cursor.moveToFirst()
when you need to iterate through all or some data elements from your
database.
"Make sure, COLUMN_ID is PRIMARY Key." Reason behind this is to avoid duplicity in case you ever add a functionality of adding items on the run time.
REMOVE this if (cursor.moveToFirst()) .
Make sure, COLUMN_ID is PRIMARY Key.
Check deleteHandler() method is invoking or not.
You should try with
public void deleteHandler(String username, String IP)
{
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_USER,
COLUMN_NAME + " = ? AND " + COLUMN_ID + " = ?",
new String[] {username, IP});
db.close();
}

how to give onClick event to listview where the data is dynamically generated

I am an android beginner.
I am trying to give onClick event to the data in the listview. The data is getting from the mysql database and storing in the sqlite and it was displaying on the screen. I am not getting any idea how to give onClick event for that data. Please give me suggestion.
Thanks in advance.
I am trying develop a time table app. When the user clicks on a button the classes he have to attend on that day have to be display in a listview. When he clicks on the class he have to get details of that class.
public class tuesday extends ListActivity {
private ArrayList<String> results = new ArrayList<String>();
private String DATABASE_TABLE = SQLiteDB.DATABASE_TABLE;
private SQLiteDatabase newDB;
private static final String KEY_PERIODNO = "periodno";
private static final String KEY_PERIODNAME = "periodname";
private String id;
TextView periodno,periodname;
SQLiteDB sqlite_obj;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tuesday);
sqlite_obj = new SQLiteDB(tuesday.this);
Intent previous = getIntent();
id = previous.getStringExtra("id");
Log.i("id: ", " " + id);
select_seqlite();
}
private void select_seqlite() {
sqlite_obj.open();
Cursor c = sqlite_obj.gettuesdayData();
if (c.moveToFirst())
{
do {
DisplayContact(c);
} while (c.moveToNext());
}
sqlite_obj.close();
}
private void DisplayContact(Cursor c) {
Toast.makeText(getBaseContext(),
"\n" +"periodno: " + c.getString(2)+ "\n"+"periodname: " + c.getString(3)+ "\n", Toast.LENGTH_LONG).show();
TextView tview = new TextView(this);
tview.setText(" " + c.getString(2) +
" "+ c.getString(3));
getListView().addHeaderView(tview);
setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.activity_list_item,results));
getListView().setTextFilterEnabled(true);}}
In your activity, where you defined your listview
write this below code
listview.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?>adapter,View v, int position){
ItemClicked item = adapter.getItemAtPosition(position);
Intent intent = new Intent(Activity.this,destinationActivity.class);
//based on item add info to intent
startActivity(intent);
}
});
And In your adapter's getItem you write
public ItemClicked getItem(int position){
return items.get(position);
}
I hope it might help you!

Accessing DB from list adapter

I have a listview that contains some data which I got from the web. Now I can make changes in the list item and once I make changes to the item, I am storing the updated value in the db. When i login in next time to the app, I am downloading the content from net and showing it in the listview with the changes that I have done last time. So my approach here is, I am querying the db for each item in the getview method of the list adapter to check for changes. Is it a good practice to do a db query for each item's getview method of the adapter? If not could you please suggest me some alternative. Thanks.
Never, really, never do that.
If you put your data download code in the getView method of the adapter it will make a network call for each row of the list.
Even worst, it will call it anytime that row appears on the screen, not only one time for row.
You should get all your data first, then use the adapter only to draw it.
You can at anytime call the db to check for changes and, if needed, notify the adapter to redraw the list to show the changes.
Hope this helps.
In Android development, any time you want to show a vertical list of items you will want to use a ListView which is populated using an Adapter to a data source. When we want the data for the list to be sourced directly from a SQLite database query we can use a CursorAdapter.
The CursorAdapter fits in between a Cursor (data source from SQLite query) and the ListView (visual representation) and configures two aspects:
Which layout template to inflate for an item
Which fields of the cursor to bind to views in the template
Creating the View Template
When we want to display a series of items into a list using a custom representation of the items, we need to use our own custom XML layout template for each item. We can simply create an XML layout template in res/layout/item_todo.xml representing a particular cursor row:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
<TextView
android:id="#+id/tvBody"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Study cursors"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="#+id/tvPriority"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:text="3"
android:textAppearance="?android:attr/textAppearanceMedium" />
</LinearLayout>
Defining the Adapter
public class ViewAdapter extends BaseAdapter {
LayoutInflater mInflater;
public ViewAdapter() {
mInflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
return favoriteList.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = mInflater.inflate(R.layout.listitem,null);
}
final TextView nameText = (TextView) convertView.findViewById(R.id.nameText);
nameText.setText("Name : "+favoriteList.get(position).getName());
final TextView ageText = (TextView) convertView.findViewById(R.id.ageText);
ageText.setText("Age : "+favoriteList.get(position).getAge());
final Button edit = (Button) convertView.findViewById(R.id.edit);
edit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
final Dialog dialog = new Dialog(context);
dialog.setContentView(R.layout.row);
dialog.setTitle("Add Data to Database");
final EditText name = (EditText) dialog.findViewById(R.id.name);
final EditText age = (EditText) dialog.findViewById(R.id.age);
Button Add = (Button) dialog.findViewById(R.id.Add);
Add.setText("Add");
Add.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(name.getText().toString() != null && name.getText().toString().length() >0 ){
if(age.getText().toString() != null && age.getText().toString().length() >0 ){
db.updateRow(favoriteList.get(position).getId(), name.getText().toString(), age.getText().toString());
favoriteList = db.getFavList();
listView.setAdapter(new ViewAdapter());
dialog.dismiss();
}else{
Toast.makeText(getApplicationContext(), "Please Enter the Age", Toast.LENGTH_LONG).show();
}
}else{
Toast.makeText(getApplicationContext(), "Please Enter the Name", Toast.LENGTH_LONG).show();
}
}
});
dialog.show();
}
});
final Button delete = (Button) convertView.findViewById(R.id.delete);
delete.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
db.removeFav(favoriteList.get(position).getId());
notifyDataSetChanged();
favoriteList = db.getFavList();
listView.setAdapter(new ViewAdapter());
}
});
return convertView;
}
}
Create database
DatabaseHandler.java
public class DatabaseHandler extends SQLiteOpenHelper {
//Database Version
private static final int DATABASE_VERSION = 1;
//Database Name
private static final String DATABASE_NAME = "Test";
//Table Name
private static final String TABLE_TEST = "TestTable";
//Column Name
private static final String KEY_ID = "id";
private static final String KEY_NAME = "name";
private static final String KEY_AGE = "age";
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
//Create Table
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_TEST + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT,"
+ KEY_AGE + " TEXT" + ")";
db.execSQL(CREATE_CONTACTS_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_TEST);
onCreate(db);
}
//Insert Value
public void adddata(Context context,String movieId,String songId) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, movieId);
values.put(KEY_AGE, songId);
db.insert(TABLE_TEST, null, values);
db.close();
}
//Get Row Count
public int getCount() {
String countQuery = "SELECT * FROM " + TABLE_TEST;
int count = 0;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
if(cursor != null && !cursor.isClosed()){
count = cursor.getCount();
cursor.close();
}
return count;
}
//Delete Query
public void removeFav(int id) {
String countQuery = "DELETE FROM " + TABLE_TEST + " where " + KEY_ID + "= " + id ;
SQLiteDatabase db = this.getReadableDatabase();
db.execSQL(countQuery);
}
//Get FavList
public List<FavoriteList> getFavList(){
String selectQuery = "SELECT * FROM " + TABLE_TEST;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
List<FavoriteList> FavList = new ArrayList<FavoriteList>();
if (cursor.moveToFirst()) {
do {
FavoriteList list = new FavoriteList();
list.setId(Integer.parseInt(cursor.getString(0)));
list.setName(cursor.getString(1));
list.setAge(cursor.getString(2));
FavList.add(list);
} while (cursor.moveToNext());
}
return FavList;
}
}
Enojoys.... :)
It is better to use cursor adapter to bind the list view.You can use Loader to get the list updated even if there is a change in the data base.
onLoadFinished (Loader loader, D data) of the Loader call back would be monitor for changes to the data, and report them to you through new calls. You should not monitor the data yourself.

Retrieving data from SQLite database and display it into ListView -android

I created a database(mydb) with a table(student) in the onCreate function and then entered values dynamically using a button click.Now I want to retrieve all the data from the table student on a button click and display it into listview.
public class MainActivity extends Activity
{
String name, phone;
SQLiteDatabase db;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
db=openOrCreateDatabase("mydb", MODE_PRIVATE, null);
db.execSQL("CREATE TABLE IF NOT EXISTS student(dbname VARCHAR, dbphone VARCHAR);");
}
public void btnaddtodb(View v)
{
EditText edtxtname = (EditText)findViewById(R.id.edtxtname);
EditText edtxtphone = (EditText)findViewById(R.id.edtxtphone);
name=edtxtname.getText().toString();
phone=edtxtphone.getText().toString();
db.execSQL("INSERT INTO student values('"+name+"','"+phone+"');");
edtxtname.setText("");
edtxtphone.setText("");
}
}
Try doing this...It shows all the values in table in a LinearLayout as a list
try{
mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE,null);
Cursor allrows = mydb.rawQuery("SELECT * FROM "+ TABLE, null);
System.out.println("COUNT : " + allrows.getCount());
Integer cindex = allrows.getColumnIndex("BOOK_DATE");
Integer cindex1 = allrows.getColumnIndex("TRIP_DATE");
Integer cindex2 = allrows.getColumnIndex("LOCATION");
TextView t = new TextView(MybookingsActivity.this);
t.setText("========================================");
//Linear.removeAllViews();
Linear.addView(t);
if(allrows.moveToFirst()){
do{
LinearLayout id_row = new LinearLayout(MybookingsActivity.this);
LinearLayout book_date_row = new LinearLayout(MybookingsActivity.this);
LinearLayout trip_date_row= new LinearLayout(MybookingsActivity.this);
LinearLayout location_row= new LinearLayout(MybookingsActivity.this);
LinearLayout feedback_row= new LinearLayout(MybookingsActivity.this);
final TextView id_ = new TextView(MybookingsActivity.this);
final TextView book_date = new TextView(MybookingsActivity.this);
final TextView trip_date = new TextView(MybookingsActivity.this);
final TextView location = new TextView(MybookingsActivity.this);
final TextView sep = new TextView(MybookingsActivity.this);
final Button feedback = new Button(MybookingsActivity.this);
final String ID = allrows.getString(0);
String BOOK_DATE= allrows.getString(1);
String TRIP_DATE= allrows.getString(2);
String LOCATION= allrows.getString(3);
id_.setTextColor(Color.RED);
id_.setPadding(20, 5, 0, 5);
book_date.setTextColor(Color.RED);
book_date.setPadding(20, 5, 0, 5);
trip_date.setTextColor(Color.RED);
trip_date.setPadding(20, 5, 0, 5);
location.setTextColor(Color.RED);
location.setPadding(20, 5, 0, 5);
System.out.println("BOOK_DATE " + allrows.getString(cindex) + " TRIP_DATE : "+ allrows.getString(cindex1)+ " LOCATION : "+ allrows.getString(cindex2));
System.out.println("ID : "+ ID + " || BOOK_DATE " + BOOK_DATE + "|| TRIP_DATE : "+ TRIP_DATE+ "|| LOCATION : "+LOCATION);
id_.setText("ID : " + ID);
id_row.addView(id_);
Linear.addView(id_row);
book_date.setText("BOOK_DATE : "+BOOK_DATE);
book_date_row.addView(book_date);
Linear.addView(book_date_row);
trip_date.setText("TRIP_DATE : " + TRIP_DATE);
trip_date_row.addView(trip_date);
Linear.addView(trip_date_row);
location.setText("LOCATION : " + LOCATION);
location_row.addView(location);
Linear.addView(location_row);
feedback.setText("Feedback");
feedback.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent=new Intent(MybookingsActivity.this,FeedbackActivity.class);
intent.putExtra("id", ID);
startActivity(intent);
}
});
feedback_row.addView(feedback);
Linear.addView(feedback_row);
sep.setText("---------------------------------------------------------------");
Linear.addView(sep);
}
while(allrows.moveToNext());
}
mydb.close();
}catch(Exception e){
Toast.makeText(getApplicationContext(), "Error encountered."+e.toString(), Toast.LENGTH_LONG).show();
}
Try it..Dont forget to change the dbname,tablename and fielnames..
Usually, you can always use the ArrayAdapter to show something in listview. (there is a good tutorial about it and many other ones you can find on Internet)
For something in db, besides the basic ArrayAdapter, you can also use CursorAdapter which has some extra benefits such as dynamic loading and auto refresh.
To use CursorAdapter, Let your Activity implements LoaderCallback<Cursor> and its required callbacks.
Init a CursorAdapter and set it to the ListView.
In the CreateLoader(...) method, query whatever you need.
Remember to implement the newView and bindView properly.
A simplest sample may looks like below:
public class TestActivity extends Activity implements LoaderCallbacks<Cursor>{
ListView listview;
CursorAdapter cursorAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
cursorAdapter = new CursorAdapter(this, null) {
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
LayoutInflater inflater =
(LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView;
rowView = inflater.inflate(R.layout.device_list_item, parent, false);
bindView(rowView, context, cursor);
return rowView;
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
TextView textView = view.findViewById(R.id.text);
textView.setText(cursor.getString(0));
}
};
}
#Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
return db.query(...);
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
cursorAdapter.swapCursor(data);
}
#Override
public void onLoaderReset(Loader<Cursor> loader) {
cursorAdapter.swapCursor(null);
}
}
USE this tutorial my be it help you.
1> Android-sqlite-and-listview-example
2> listview-of-data-from-sqlitedatabase

Categories

Resources