How to Fetch Record From SQLite in Android - android

I am not good at Android, learning things. I'm trying to fetch record from SQLite in Android. Here is my code. Please help where is my fault. Thanks.
//DatabaseAdapter.java//
package com.example.wg_an;
import java.util.ArrayList;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
public class DatabaseAdapter {
SQLiteDatabase database;
DatabaseOpenHelper dbHelper;
public DatabaseAdapter(Context context) {
dbHelper = new DatabaseOpenHelper(context);
}
public void open() {
database = dbHelper.getWritableDatabase();
}
public void close() {
database.close();
}
public long insertTest(String no, String name) {
ContentValues values = new ContentValues();
values.put("no", no);
values.put("name", name);
return database.insert("test", null, values);
}
public ArrayList<String> getAllLabels() {
Cursor mcursor = database.rawQuery("SELECT name FROM "
+ DatabaseOpenHelper.TABLE_NAME, null);
ArrayList<String> result = new ArrayList<String>();
do {
result.add(mcursor.getString(mcursor.getColumnIndex("name")));
} while (mcursor.moveToNext());
return result;
}
}
//MainActivity2.java//
package com.example.wg_an;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
public class MainActivity2 extends Activity implements OnClickListener {
EditText etno, etname;
Button btnSave;
DatabaseAdapter dbAdapter;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
dbAdapter = new DatabaseAdapter(getApplicationContext());
etno = (EditText) findViewById(R.id.txtNo);
etname = (EditText) findViewById(R.id.txtName);
btnSave = (Button) findViewById(R.id.Save);
btnSave.setOnClickListener(this);
Button back = (Button) findViewById(R.id.buttonBackPg);
back.setOnClickListener(this);
Button view_list = (Button) findViewById(R.id.view_list);
view_list.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (v.getId() == R.id.buttonBackPg) {
startActivity(new Intent(getApplicationContext(),
MainActivity.class));
}
if (v.getId() == R.id.view_list) {
ListView listview = (ListView) findViewById(R.id.list_all);
ArrayList<String> data = dbAdapter.getAllLabels();
dbAdapter.close();
listview.setAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, data));
}
if (v.getId() == R.id.Save) {
String no = etno.getText().toString();
String name = etname.getText().toString();
dbAdapter.open();
long inserted = dbAdapter.insertTest(no, name);
if (inserted >= 0) {
Toast.makeText(getApplicationContext(), "data saved",
Toast.LENGTH_LONG).show();
etno.setText("");
etname.setText("");
} else {
Toast.makeText(getApplicationContext(), "data not saved",
Toast.LENGTH_LONG).show();
}
dbAdapter.close();
}
}
}
//activity_main2.xml//
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
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=".MainActivity2" >
<EditText
android:id="#+id/txtNo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/textView1"
android:layout_centerHorizontal="true"
android:layout_marginTop="19dp"
android:ems="10"
android:hint="No"
android:inputType="text" >
<requestFocus />
</EditText>
<Button
android:id="#+id/buttonBackPg"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/Save"
android:layout_alignParentBottom="true"
android:layout_marginBottom="77dp"
android:text="Back" />
<Button
android:id="#+id/Save"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/buttonBackPg"
android:layout_centerHorizontal="true"
android:layout_marginBottom="32dp"
android:onClick="onClick"
android:text="Save" />
<EditText
android:id="#+id/txtName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="#+id/textView1"
android:layout_below="#+id/txtNo"
android:layout_marginTop="36dp"
android:ems="10"
android:hint="Name"
android:inputType="text">
</EditText>
<Button
android:id="#+id/view_list"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/txtName"
android:layout_below="#+id/Save"
android:text="View List" />
<ListView
android:id="#+id/list_all"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/msg"
android:layout_alignLeft="#+id/msg" >
</ListView>
</RelativeLayout>

Try this edit
public ArrayList<String> getAllLabels() {
Cursor mcursor = database.rawQuery("SELECT name FROM "
+ DatabaseOpenHelper.TABLE_NAME, null);
ArrayList<String> result = new ArrayList<String>();
if(mcursor!=null)
{
//move cursor to first result record
mcursor.moveToFirst();
do {
result.add(mcursor.getString(mcursor.getColumnIndex("name")));
} while (mcursor.moveToNext());
}
return result;
}

for fetch data use like that
public Cursor getdata()
{
Log.v(TAG + ".getdata", "getdatamethod called");
Cursor mCursor = null;
openAsWrite();
mCursor=db.query(tablenam,
new String[] {"column name"},null, null, null, null, null);
return mCursor;
}

Final Working Code is here --
//DatabaseAdapter.java//
package com.example.wg_an;
import java.util.ArrayList;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
public class DatabaseAdapter {
SQLiteDatabase database;
DatabaseOpenHelper dbHelper;
public DatabaseAdapter(Context context) {
dbHelper = new DatabaseOpenHelper(context);
}
public void open() {
database = dbHelper.getWritableDatabase();
}
public void close() {
database.close();
}
public long insertTest(String no, String name) {
ContentValues values = new ContentValues();
values.put("no", no);
values.put("name", name);
return database.insert("test", null, values);
}
public ArrayList<String> getAllLabels() {
Cursor mcursor = database.rawQuery("SELECT * FROM "
+ DatabaseOpenHelper.TABLE_NAME, null);
ArrayList<String> result = new ArrayList<String>();
if(mcursor!=null)
{
//move cursor to first result record
mcursor.moveToFirst();
do {
String display = mcursor.getString(mcursor.getColumnIndex("name")) + " - " + mcursor.getString(mcursor.getColumnIndex("no"));
result.add(display);
} while (mcursor.moveToNext());
}
return result;
}
}
//MainActivity2.java //
package com.example.wg_an;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity2 extends Activity implements OnClickListener {
EditText etno, etname;
Button btnSave;
DatabaseAdapter dbAdapter;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
dbAdapter = new DatabaseAdapter(getApplicationContext());
etno = (EditText) findViewById(R.id.txtNo);
etname = (EditText) findViewById(R.id.txtName);
btnSave = (Button) findViewById(R.id.Save);
btnSave.setOnClickListener(this);
Button back = (Button) findViewById(R.id.buttonBackPg);
back.setOnClickListener(this);
Button view_list = (Button) findViewById(R.id.view_list);
view_list.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (v.getId() == R.id.buttonBackPg) {
startActivity(new Intent(getApplicationContext(),
MainActivity.class));
}
if (v.getId() == R.id.view_list) {
startActivity(new Intent(getApplicationContext(),
MainActivity3.class));
}
if (v.getId() == R.id.Save) {
String no = etno.getText().toString();
String name = etname.getText().toString();
dbAdapter.open();
long inserted = dbAdapter.insertTest(no, name);
if (inserted >= 0) {
Toast.makeText(getApplicationContext(), "data saved",
Toast.LENGTH_LONG).show();
etno.setText("");
etname.setText("");
} else {
Toast.makeText(getApplicationContext(), "data not saved",
Toast.LENGTH_LONG).show();
}
dbAdapter.close();
}
}
}
//MainActivity3.java//
package com.example.wg_an;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
public class MainActivity3 extends Activity implements OnClickListener {
/** Called when the activity is first created. */
DatabaseAdapter dbAdapter;
ListView listview;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main3);
dbAdapter = new DatabaseAdapter(this);
dbAdapter.open();
try {
Button back = (Button) findViewById(R.id.back_2);
back.setOnClickListener(this);
listview = (ListView) findViewById(R.id.list_all);
Log.d("Reading: ", "Reading MA3..");
ArrayList<String> data = dbAdapter.getAllLabels();
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, data);
listview.setAdapter(adapter);
dbAdapter.close();
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "Error", Toast.LENGTH_LONG)
.show();
}
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (v.getId() == R.id.back_2) {
startActivity(new Intent(getApplicationContext(),
MainActivity2.class));
}
}
}
//DatabaseOpenHelper.java//
package com.example.wg_an;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseOpenHelper extends SQLiteOpenHelper {
public static final String DBName = "test_database.db";
public static final String TABLE_NAME = "test";
public static final String TABLE_SQL = "Create Table "+ TABLE_NAME
+"(_id INTEGER PRIMARY KEY AUTOINCREMENT, "
+"no TEXT, "
+"name TEXT);";
public DatabaseOpenHelper(Context context) {
super(context, DBName, null, 1);
// TODO Auto-generated constructor stub
}
#Override
public void onCreate(SQLiteDatabase database) {
// TODO Auto-generated method stub
database.execSQL(TABLE_SQL);
}
#Override
public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) {
// TODO Auto-generated method stub
}
}
//activity_main2.xml//
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
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=".MainActivity2" >
<Button
android:id="#+id/buttonBackPg"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/Save"
android:layout_alignParentBottom="true"
android:layout_marginBottom="77dp"
android:text="Back Screen-1" />
<Button
android:id="#+id/Save"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/buttonBackPg"
android:layout_alignLeft="#+id/txtName"
android:onClick="onClick"
android:text="Save" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="16dp"
android:layout_marginTop="21dp"
android:text="Add Records - Screen-2" />
<EditText
android:id="#+id/txtName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/Save"
android:layout_alignLeft="#+id/txtNo"
android:layout_marginBottom="58dp"
android:ems="10"
android:hint="Name"
android:inputType="text" />
<EditText
android:id="#+id/txtNo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/textView2"
android:layout_centerHorizontal="true"
android:layout_marginTop="22dp"
android:ems="10"
android:hint="No"
android:inputType="text" />
<Button
android:id="#+id/view_list"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="#+id/txtName"
android:layout_below="#+id/txtName"
android:text="View List" />
</RelativeLayout>
//activity_main3.xml//
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
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=".MainActivity3" >
<Button
android:id="#+id/back_2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="17dp"
android:text="Back Screen-2" />
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="80dp"
android:text="List of Records - Screen-3" />
<ListView
android:id="#+id/list_all"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="58dp"
android:layout_marginTop="58dp"
android:layout_below="#+id/textView3"
android:layout_centerHorizontal="true" >
</ListView>
</RelativeLayout>

Related

Delete selected item in listview and sqllite database and modify the selected item

My app gets name and address and type (sitdown,take away,phone order) of a restaurant and adds it to a sqlite and then to a listview.
I'm trying to have a delete option when one of the items of the listview get long pressed but I don't know how can I do it and I wanted to have edit option after the row item is generated so I create a context menu for long press and a remove and edit option and if the user selects the edit option a dialog pops up and there is edit texts and radiogroup so the user can modify the selected item
I'm new to android.
MainActivity:
package com.test.fastfoodfinder;
import androidx.appcompat.app.AppCompatActivity;
import android.app.AlertDialog;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.view.ContextMenu;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CursorAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RadioGroup;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private ListView listview;
private Button btn;
Cursor model = null;
RestaurantAdapter adapter = null;
EditText ffname = null;
EditText ffaddress = null;
RadioGroup types = null;
RestaurantHelper helper = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = findViewById(R.id.btn);
helper = new RestaurantHelper(this);
ffname = findViewById(R.id.edittext_name);
ffaddress = findViewById(R.id.edittext_name);
types = findViewById(R.id.radiogroup_type);
listview = findViewById(R.id.list_view);
model = helper.getAll();
startManagingCursor(model);
adapter = new RestaurantAdapter(model);
listview.setAdapter(adapter);
btn.setOnClickListener(onSave);
registerForContextMenu(listview);
}
public void onDestroy() {
super.onDestroy();
helper.close();
}
boolean doubleBackToExitPressedOnce = false;
public void onBackPressed() {
if (doubleBackToExitPressedOnce) {
super.onBackPressed();
return;
}
this.doubleBackToExitPressedOnce = true;
Toast.makeText(this, "Please click BACK again to exit", Toast.LENGTH_SHORT).show();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
doubleBackToExitPressedOnce = false;
}
}, 2000);
}
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, (ContextMenu.ContextMenuInfo) menuInfo);
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo;
menu.add(0, 1, 0, "Edit");
menu.add(0, 2, 1, "Remove");
menu.add(0, 3, 2, "Add Note");
menu.add(0, 4, 3, "All Notes");
}
public boolean onContextItemSelected(MenuItem item) {
if (item.getTitle().equals("Edit")) {
TextView title = new TextView(this);
title.setText("Edit Your Inputs");
title.setBackgroundColor(Color.DKGRAY);
title.setPadding(10, 16, 10, 10);
title.setGravity(Gravity.CENTER);
title.setTextColor(Color.WHITE);
title.setTextSize(20);
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
View loginForm = inflater.inflate(R.layout.set_dialog, null, false);
builder.setView(loginForm);
builder.setCustomTitle(title);
AlertDialog dialog = builder.create();
dialog.getWindow().getAttributes().windowAnimations = R.style.customdialog;
dialog.show();
} else if (item.getTitle().equals("Remove")) {
} else if (item.getTitle().equals("Add Note")) {
} else if (item.getTitle().equals("All Notes")) {
}
return super.onContextItemSelected(item);
}
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_menu, menu);
return super.onCreateOptionsMenu(menu);
}
public boolean onOptionsItemSelected(MenuItem item) {
ListView listView = findViewById(R.id.list_view);
EditText nameInput = findViewById(R.id.edittext_name);
EditText addressInput = findViewById(R.id.editText_address);
RadioGroup types = findViewById(R.id.radiogroup_type);
int id = item.getItemId();
switch (id) {
case R.id.clearlist:
helper.deleteDatabase(this);
listView.setAdapter(null);
break;
case R.id.clearforum:
nameInput.setText("");
addressInput.setText("");
types.check(0);
break;
case R.id.settings:
break;
case R.id.exit:
finish();
System.exit(0);
break;
}
return super.onOptionsItemSelected(item);
}
private View.OnClickListener onSave = new View.OnClickListener() {
#Override
public void onClick(View v) {
String type = null;
switch (types.getCheckedRadioButtonId()) {
case R.id.sitdown:
type = ("sitdown");
break;
case R.id.take_away:
type = ("take_away");
break;
case R.id.phone_order:
type = ("phone_order");
break;
}
if (ffname.getText().toString().isEmpty()) {
Toast.makeText(MainActivity.this, "Please enter a name to continue", Toast.LENGTH_SHORT).show();
Animation right = AnimationUtils.loadAnimation(MainActivity.this, R.anim.alert);
ffname.startAnimation(right);
btn.startAnimation(right);
} else if (ffaddress.getText().toString().isEmpty()) {
Toast.makeText(MainActivity.this, "Please enter an address to continue", Toast.LENGTH_SHORT).show();
Animation shake = AnimationUtils.loadAnimation(MainActivity.this, R.anim.alert);
ffaddress.startAnimation(shake);
btn.startAnimation(shake);
} else if (type.equals("")) {
Toast.makeText(MainActivity.this, "Please select a type", Toast.LENGTH_SHORT).show();
Animation shake = AnimationUtils.loadAnimation(MainActivity.this, R.anim.alert);
types.startAnimation(shake);
} else {
helper.insert(ffname.getText().toString(), ffaddress.getText().toString(), type, null);
model.requery();
Toast.makeText(MainActivity.this, "Total number of FastFoods in the list:" + listview.getAdapter().getCount(), Toast.LENGTH_SHORT).show();
}
}
};
class RestaurantAdapter extends CursorAdapter {
RestaurantAdapter(Cursor cursor) {
super(MainActivity.this, cursor);
}
public void bindView(View row, Context context, Cursor cursor) {
RestaurantHolder holder = (RestaurantHolder) row.getTag();
holder.populateFrom(cursor, helper);
}
public View newView(Context context, Cursor cursor, ViewGroup parent) {
LayoutInflater inflater = getLayoutInflater();
View row = inflater.inflate(R.layout.row_layout, parent, false);
Animation animation = AnimationUtils.loadAnimation(MainActivity.this, R.anim.fadein);
row.startAnimation(animation);
RestaurantHolder holder = new RestaurantHolder(row);
row.setTag(holder);
return (row);
}
}
static class RestaurantHolder {
private TextView nameV = null;
private TextView addressV = null;
private ImageView icon = null;
RestaurantHolder(View row) {
nameV = row.findViewById(R.id.listview_name);
addressV = row.findViewById(R.id.listview_address);
icon = row.findViewById(R.id.type_ic);
}
void populateFrom(Cursor cursor, RestaurantHelper helper) {
nameV.setText(helper.getName(cursor));
addressV.setText(helper.getName(cursor));
if (helper.getType(cursor).equals("sitdown")) {
icon.setImageResource(R.drawable.sitdownn);
} else if (helper.getType(cursor).equals("take_away")) {
icon.setImageResource(R.drawable.takeaway);
} else if (helper.getType(cursor).equals("phone_order")) {
icon.setImageResource(R.drawable.phoneorderr);
}
}
}
}
sqlopenhelper
package com.test.fastfoodfinder;
import android.content.Context;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteQueryBuilder;
class RestaurantHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME="lunchlist.db";
private static final int SCHEMA_VERSION=1;
public RestaurantHelper(Context context) {
super(context, DATABASE_NAME, null, SCHEMA_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE IF NOT EXISTS restaurants (_id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, address TEXT, type TEXT, notes TEXT);");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// no-op, since will not be called until 2nd schema
// version exists
}
public Cursor getAll() {
return(getReadableDatabase()
.rawQuery("SELECT _id, name, address, type, notes FROM restaurants ORDER BY name",
null));
}
public void deleteDatabase(Context mContext) {
mContext.deleteDatabase(DATABASE_NAME);
}
public void insert(String name, String address,
String type, String notes) {
ContentValues cv=new ContentValues();
cv.put("name", name);
cv.put("address", address);
cv.put("type", type);
cv.put("notes", notes);
getWritableDatabase().insert("restaurants", "name", cv);
}
public String getName(Cursor c) {
return(c.getString(1));
}
public String getAddress(Cursor c) {
return(c.getString(2));
}
public String getType(Cursor c) {
return(c.getString(3));
}
public String getNotes(Cursor c) {
return(c.getString(4));
}
}
dialog
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp"><![CDATA[>
]]>
<TextView
android:id="#+id/address"
style="#style/texts"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="48dp"
android:text="Address"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/name" />
<TextView
android:id="#+id/type"
style="#style/texts"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="52dp"
android:text="Type"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/address" />
<TextView
android:id="#+id/name"
style="#style/texts"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:text="Name"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"></TextView>
<EditText
android:id="#+id/edittext_name"
style="#style/texts"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="60dp"
android:layout_marginLeft="60dp"
android:hint="Please enter fast food name"
app:layout_constraintStart_toEndOf="#+id/name"
app:layout_constraintTop_toTopOf="parent" />
<EditText
android:id="#+id/editText_address"
style="#style/texts"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="46dp"
android:layout_marginLeft="46dp"
android:layout_marginTop="16dp"
android:hint="Please enter fast food address"
app:layout_constraintStart_toEndOf="#+id/address"
app:layout_constraintTop_toBottomOf="#+id/edittext_name" />
<RadioGroup
android:id="#+id/radiogroup_type"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="14dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toEndOf="#+id/type"
app:layout_constraintTop_toBottomOf="#+id/editText_address">
<RadioButton
android:id="#+id/sitdown"
style="#style/texts"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Sit Down" />
<RadioButton
android:id="#+id/take_away"
style="#style/texts"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Take away" />
<RadioButton
android:id="#+id/phone_order"
style="#style/texts"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Phone Order" />
</RadioGroup>
<Button
android:id="#+id/btn"
style="#style/texts"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:paddingTop="16dp"
android:text="Add"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/radiogroup_type" />
<androidx.constraintlayout.widget.Guideline
android:id="#+id/guideline"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
app:layout_constraintGuide_begin="0dp" />
<androidx.constraintlayout.widget.Barrier
android:id="#+id/barrier"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:barrierDirection="left" />
</androidx.constraintlayout.widget.ConstraintLayout>
any help would be appreciated
first you should create your method for update and delete in your RestaurantHelper.java.
This example of updating an item.
public boolean UpdateData(String name, String address, String type, String note) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(YOUR_COLUMN_NAME, name);
contentValues.put(YOUR_COLUMN_ADDRESS, address);
contentValues.put(YOUR_COLUMN_TYPE, type);
contentValues.put(YOUR_COLUMN_NOTE, note);
db.update(YOUR_TABLE, contentValues, "name= ? AND address = ?", new String[] { name, address } ); // update the item WHERE name = 'name' and address = 'address'
return true;
}
Then create also the method for deleting.
public Cursor deleteData(String your_uniqure_id) {
SQLiteDatabase db = this.getReadableDatabase();
db.execSQL("DELETE FROM your_table WHERE _id = " + your_uniqure_id);
return null;
}
call this method whenever you want.

Android: Open a new layout file on button click and apply SQLite data to it

I have a gridview here:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/colorPrimaryDark"
tools:context=".MainActivity">
<LinearLayout
android:id="#+id/topContent"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:weightSum="7">
<TextView
android:id="#+id/textView0"
android:background="#color/white"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="ID: "
android:textSize="18sp"
android:textColor="#color/black"
android:gravity="center"
/>
<TextView
android:id="#+id/textView1"
android:background="#color/purple"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="#string/gridCode"
android:textSize="18sp"
android:textColor="#color/black"
android:gravity="center"
/>
<TextView
android:id="#+id/textView2"
android:background="#color/green"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="#string/gridDay"
android:textSize="18sp"
android:textColor="#color/black"
android:gravity="center"
/>
<TextView
android:id="#+id/textView3"
android:background="#color/orange"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="#string/gridStart"
android:textSize="18sp"
android:textColor="#color/black"
android:gravity="center"
/>
<TextView
android:id="#+id/textView4"
android:background="#color/blue"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="#string/gridDuration"
android:textSize="18sp"
android:textColor="#color/black"
android:gravity="center"
/>
<TextView
android:id="#+id/textView5"
android:background="#color/yellow"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="#string/gridType"
android:textSize="18sp"
android:textColor="#color/black"
android:gravity="center"
/>
<TextView
android:id="#+id/textView6"
android:background="#color/red"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="#string/gridRoom"
android:textSize="18sp"
android:textColor="#color/black"
android:gravity="center"
/>
</LinearLayout>
<GridView
android:id="#+id/gridTable"
android:layout_below="#+id/topContent"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:horizontalSpacing="10dip"
android:verticalSpacing="15dip"
android:stretchMode="columnWidth"
android:gravity="center"
android:numColumns="7"
android:background="#color/colorPrimary"
android:textSize="14sp"
>
</GridView>
</RelativeLayout>
And a database helper:
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseHelper extends SQLiteOpenHelper
{
//database information
public static final String DATABASE_NAME = "timetable.db";
public static final String TABLE_NAME = "timetable_data";
//the data each column will store
public static final String COL_1 = "ID";
public static final String COL_2 = "CODE";
public static final String COL_3 = "DAY";
public static final String COL_4 = "START";
public static final String COL_5 = "DURATION";
public static final String COL_6 = "TYPE";
public static final String COL_7 = "ROOM";
//construct the database
public DatabaseHelper(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,CODE TEXT,DAY TEXT,START TEXT,DURATION TEXT,TYPE TEXT,ROOM 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 code, String day, String start, String duration, String type, String room)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_2,code);
contentValues.put(COL_3,day);
contentValues.put(COL_4,start);
contentValues.put(COL_5,duration);
contentValues.put(COL_6,type);
contentValues.put(COL_7, room);
long result = db.insert(TABLE_NAME,null,contentValues);
if(result == -1)
return false;
else
return true;
}
public Cursor getAllData()
{
SQLiteDatabase db = this.getWritableDatabase();
Cursor data = db.rawQuery("select * from "+TABLE_NAME,null);
return data;
}
public Integer deleteEntry(String id)
{
SQLiteDatabase db = this.getWritableDatabase();
return db.delete(TABLE_NAME,"ID = ?", new String [] {id});
}
}
What I'm trying to do, is create an adapter that can be applied to that gridview when a button is pressed. The adapter should pull all of the information from the database and insert each bit of data into each cell of the grid. I'd like all of this to happen when a button is pressed, pressing the button will show the grid in a new layout, and when the back button is pressed go back to the main_acitivty layout.
but I'm not sure if I need the other layout file there, or where the button goes, or even if this is possible to do, so any help would be appreciated! thanks!
Main_activity source:
import android.app.AlertDialog;
import android.content.Intent;
import android.database.Cursor;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Adapter;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.Spinner;
import android.widget.Toast;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
DatabaseHelper timetableDB;
EditText roomInput, codeInput, idInput;
Spinner dayInput, durationInput, timeInput, sessionInput;
Button button_add, button_display, button_delete, button_display_grid;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
timetableDB = new DatabaseHelper(this);
codeInput = (EditText) findViewById(R.id.codeInput);
dayInput = (Spinner) findViewById(R.id.dayInput);
timeInput = (Spinner) findViewById(R.id.timeInput);
durationInput = (Spinner) findViewById(R.id.durationInput);
sessionInput = (Spinner) findViewById(R.id.sessionInput);
roomInput = (EditText) findViewById(R.id.roomInput);
idInput = (EditText) findViewById(R.id.idInput);
button_add = (Button) findViewById(R.id.button_add);
button_display = (Button) findViewById(R.id.button_display);
button_display_grid = (Button) findViewById(R.id.button_display_grid);
button_delete = (Button) findViewById(R.id.button_delete);
AddData();
displayData();
deleteData();
}
button_display_grid.setOnClickListener(new View.OnClickListener()
{
//This method starts the GridView activity when the button is pressed
#Override
public void onClick (View v)
{
Intent i = new Intent(MainActivity.this, GridViewActivity.class);
startActivity(i);
}
}
public void deleteData()
{
button_delete.setOnClickListener(
new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Integer deletedData = timetableDB.deleteEntry(idInput.getText().toString());
if(deletedData > 0)
Toast.makeText(MainActivity.this, "Entry Removed", Toast.LENGTH_SHORT).show();
else
Toast.makeText(MainActivity.this, "Error Removing Entry", Toast.LENGTH_SHORT).show();
}
}
);
}
public void AddData()
{
button_add.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
boolean isInserted = timetableDB.insertData(
codeInput.getText().toString(),
dayInput.getSelectedItem().toString(),
timeInput.getSelectedItem().toString(),
durationInput.getSelectedItem().toString(),
sessionInput.getSelectedItem().toString(),
roomInput.getText().toString());
if (isInserted = true)
Toast.makeText(MainActivity.this, "Module Added", Toast.LENGTH_SHORT).show();
else
Toast.makeText(MainActivity.this, "Error Adding Data", Toast.LENGTH_SHORT).show();
}
}
);
}
public void displayData()
{
button_display.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Cursor data = timetableDB.getAllData();
if(data.getCount() == 0)
{
//show message
return;
}
StringBuilder buffer = new StringBuilder();
while (data.moveToNext())
{
buffer.append("ID :"+ data.getString(0)+"\n");
buffer.append("Code :"+ data.getString(1)+"\n");
buffer.append("Day :"+ data.getString(2)+"\n");
buffer.append("Start :"+ data.getString(3)+"\n");
buffer.append("Duration: "+ data.getString(4)+"\n");
buffer.append("Type :"+ data.getString(5)+"\n");
buffer.append("Room :"+ data.getString(6)+"\n\n");
}
showMessage("My Timetable:", buffer.toString());
}
}
);
}
public void showMessage(String title, String Message)
{
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setCancelable(true);
builder.setTitle(title);
builder.setMessage(Message);
builder.show();
}
}
GridViewActivity.java:
import android.database.Cursor;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.Toast;
import java.util.ArrayList;
/**
* Created by natha on 17/02/2016.
*
* This class gets all of the information in the getAllData() method, adds it to an array list,
* then an array adapter reads the data from this array list and applies that data to the GridView.
*
*/
public class GridViewActivity extends MainActivity
{
private GridView gridTable;
private ArrayList<String> moduleList;
private ArrayAdapter<String> adapter;
private Cursor data;
DatabaseHelper timetableDB;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState); setContentView(R.layout.gridview);
//GridView
gridTable=(GridView) findViewById(R.id.gridTable);
//ArrayList
moduleList = new ArrayList<>();
adapter = new ArrayAdapter<>(getApplicationContext(),
android.R.layout.simple_spinner_item,moduleList);
String id, code, day, time, duration, type, room;
id = "";
code = "";
day = "";
time = "";
duration = "";
type = "";
room = "";
timetableDB = new DatabaseHelper(getBaseContext());//getting the context object
timetableDB.getAllData();
try
{
//for holding retrieve data from query and store in the form of rows
Cursor data=timetableDB.getAllData();
//Move the cursor to the first row.
if(data.moveToFirst())
{
do
{
id = data.getString(data.getColumnIndex ("id"));
code = data.getString(data.getColumnIndex ("code"));
day = data.getString(data.getColumnIndex ("day"));
time = data.getString(data.getColumnIndex ("time"));
duration = data.getString(data.getColumnIndex ("duration"));
type = data.getString(data.getColumnIndex ("type"));
room = data.getString(data.getColumnIndex ("room"));
//add in to array list
moduleList . add(id);
moduleList . add(code);
moduleList . add(day);
moduleList . add(time);
moduleList . add(duration);
moduleList . add(type);
moduleList . add(room);
gridTable.setAdapter(adapter);
}
while(data.moveToNext());//Move the cursor to the next row.
}
else
{
Toast.makeText(getApplicationContext(),
"No data found", Toast.LENGTH_LONG).show();
}
}catch(Exception e)
{
Toast.makeText(getApplicationContext(),
"No data found "+e.getMessage(), Toast.LENGTH_LONG).show();
}
timetableDB.close();
}
}
You should move the button_display_grid.setOnClickListener, inside the onCreate of your activity, after its initialization.

android.widget.TextView cannot be cast to android.widget.EditView

when i tried to run this code it is showing error. what is the problem. please tell me if u find.
But i did not cast Textview to EditText but it showing error.
My xml file:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
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.dailyexpenses.LoginTypeConfirmation" >
<TextView
android:id="#+id/Confirmation_password_info"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/Confirmation_password"
android:layout_alignParentTop="true"
android:layout_marginTop="38dp"
android:text="#string/loginType_confirm" />
<EditText
android:id="#+id/Confirmation_password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/Confirmation_password_info"
android:layout_centerHorizontal="true"
android:layout_marginTop="44dp"
android:ems="10"
android:hint="#string/confirm_password"
android:inputType="textPassword" />
<Button
android:id="#+id/Confirmation_password_submit"
android:layout_width="match_parent"
android:layout_height="35dp"
android:layout_alignLeft="#+id/Confirmation_password"
android:layout_below="#+id/Confirmation_password"
android:layout_marginTop="34dp"
android:background="#color/project_theme"
android:text="#string/submit"
android:textColor="#color/font_color" />
My Java code:
import android.support.v7.app.ActionBarActivity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.text.InputType;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class LoginTypeConfirmation extends ActionBarActivity {
private TextView info;
private EditText old_password;
private Button save;
private SQLiteDatabase db;
String login_type = null, password = null, pin_password = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login_type_confirmation_ui);
db = openOrCreateDatabase("DailyExpenses", Context.MODE_PRIVATE, null);
info = (TextView) findViewById(R.id.Confirmation_password_info);
old_password = (EditText) findViewById(R.id.Confirmation_password);
save = (Button) findViewById(R.id.Confirmation_password_submit);
checkLoginType();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.login_type_confirmation, menu);
return true;
}
public void checkLoginType()
{
Cursor c = db.rawQuery("select login_type password, pin_password from user_information", null);
while(c.moveToNext())
{
login_type = c.getString(0);
password = c.getString(1);
pin_password = c.getString(2);
}
if (login_type.equals("pin_password"))
{
info.setText("Enter your old pin");
old_password.setText("Confirm Pin");
old_password.setInputType(InputType.TYPE_NUMBER_VARIATION_PASSWORD);
}
}
public void validatePassword(View view)
{
if (old_password.getText().toString().equals(password))
{
Intent loginType = new Intent(this, LoginType.class);
startActivity(loginType);
}
else
{
Toast.makeText(this, "Incorrect Password", Toast.LENGTH_SHORT).show();
}
}
}
if i remove checkLoginType() method it's working fine.
thanks in advance.
You need to pass View to your checkLoginType() method, it will look like below code:
public void checkLoginType(View v)
{
Cursor c = db.rawQuery("select login_type password, pin_password from user_information", null);
while(c.moveToNext())
{
login_type = c.getString(0);
password = c.getString(1);
pin_password = c.getString(2);
}
if(login_type.equals("pin_password"))
{
info.setText("Enter your old pin");
old_password.setText("Confirm Pin");
old_password.setInputType(InputType.TYPE_NUMBER_VARIATION_PASSWORD);
}
}
Let me know if you still facing issue...
Just Change public void checkLoginType() to public void checkLoginType(View v)

sqlite database practice in android

I have made an application simple in android for database practice,as i have no idea about Sqlite database I've gone through so many links for it,But most of them are complex,I have created 4 activities 1st (mainActivity) contains 3 Buttons "add","Edit", and "View" in 2nd activity (AddActivity) I have made 3 EditTexts its entered values should be stored in database.So can you please tell me easy steps for doing same?
MainActivity.java
package com.example.db;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button add=(Button)findViewById(R.id.button1);
Button edit=(Button)findViewById(R.id.button2);
Button view=(Button)findViewById(R.id.button3);
add.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub]
Intent i=new Intent(MainActivity.this,AddActivity.class);
startActivity(i);
}
});
edit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i=new Intent(MainActivity.this,EditActivity.class);
startActivity(i);
}
});
view.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i=new Intent(MainActivity.this,ViewActivity.class);
startActivity(i);
}
});
}
}
AddActivity.java
package com.example.db;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class AddActivity extends Activity {
EditText name,addres,phon;
Button ad,cn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add);
name = (EditText)findViewById(R.id.name);
addres=(EditText)findViewById(R.id.address);
phon = (EditText)findViewById(R.id.phone);
ad =(Button)findViewById(R.id.add);
cn=(Button)findViewById(R.id.cancel);
final SQLiteDatabase db = openOrCreateDatabase("Mydb",MODE_PRIVATE, null);
db.execSQL("create table if not exists simple(name varchar,address varchar,phone varchar");
ad.setOnClickListener(new OnClickListener() {
String n=name.getText().toString();
String a=addres.getText().toString();
String p= phon.getText().toString();
#Override
public void onClick(View v) {
db.execSQL("insert into simple values('n','a','p')");
Cursor c =db.rawQuery("select * from simple",null);
c.moveToFirst();
}
});
cn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i =new Intent(AddActivity.this,MainActivity.class);
startActivity(i);
}
});
}
}
main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="100dp"
android:layout_marginTop="92dp"
android:text="Add" />
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="#+id/button1"
android:layout_below="#+id/button1"
android:layout_marginTop="28dp"
android:text="Edit" />
<Button
android:id="#+id/button3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="#+id/button2"
android:layout_below="#+id/button2"
android:layout_marginTop="37dp"
android:text="View" />
</RelativeLayout>
Add.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".AddActivity" >
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/textView2"
android:layout_marginTop="60dp"
android:text="phone"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/textView3"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="17dp"
android:layout_marginTop="14dp"
android:text="Name"
android:textAppearance="?android:attr/textAppearanceMedium" />
<EditText
android:id="#+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/textView1"
android:layout_alignBottom="#+id/textView1"
android:layout_alignParentRight="true"
android:ems="10" >
<requestFocus />
</EditText>
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginTop="80dp"
android:layout_toLeftOf="#+id/editText2"
android:text="Address"
android:textAppearance="?android:attr/textAppearanceMedium" />
<EditText
android:id="#+id/address"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignTop="#+id/textView2"
android:ems="10"
android:inputType="textPostalAddress" />
<EditText
android:id="#+id/phone"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/textView3"
android:layout_alignParentRight="true"
android:ems="10"
android:inputType="phone" />
<Button
android:id="#+id/add"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/phone"
android:layout_marginTop="62dp"
android:layout_toRightOf="#+id/textView1"
android:text="Add" />
<Button
android:id="#+id/cancel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/add"
android:layout_marginLeft="36dp"
android:layout_toRightOf="#+id/add"
android:text="Cancel" />
</RelativeLayout>
ok I think you want to add the value of edit text into your db
package com.example.databasesample;
import java.util.ArrayList;
import android.app.Activity;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
public class MainActivity extends Activity implements OnClickListener {
static EditText edtAdd;
Button btnAdd, btnShow;
ListView listName;
static DataBaseSqlLiteHelper mBaseSqlLiteHelper;
DBModel mDbModel;
ArrayList<DBModel> mArrayList;
ListAdapter mAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initialize();
mArrayList = new ArrayList<DBModel>();
mBaseSqlLiteHelper = new DataBaseSqlLiteHelper(MainActivity.this);
mBaseSqlLiteHelper.getReadableDatabase();
mBaseSqlLiteHelper.getWritableDatabase();
}
public void initialize() {
edtAdd = (EditText) findViewById(R.id.edtEnterName);
btnAdd = (Button) findViewById(R.id.btnAdd);
btnAdd.setOnClickListener(this);
btnShow = (Button) findViewById(R.id.btnShow);
btnShow.setOnClickListener(this);
listName = (ListView) findViewById(R.id.listName);
listName.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
deleteItem(mArrayList.get(arg2).getId());
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.btnAdd:
addName(edtAdd.getText().toString());
break;
case R.id.btnShow:
showNames();
break;
default:
break;
}
}
// for adding values
public void addName(String name) {
SQLiteDatabase mOpenHelper = mBaseSqlLiteHelper.getWritableDatabase();
ContentValues mContentValues = new ContentValues();
mContentValues.put("name", name);
mOpenHelper.insert("NAMES", null, mContentValues);
mOpenHelper.close();
}
//showing values in list
public void showNames() {
String selectQuery = "SELECT * FROM NAMES";
SQLiteDatabase mDatabase = mBaseSqlLiteHelper.getWritableDatabase();
Cursor mCursor = mDatabase.rawQuery(selectQuery, null);
if (mCursor.moveToFirst()) {
do {
mDbModel = new DBModel();
mDbModel.setId(mCursor.getString(0));
mDbModel.setName(mCursor.getString(1));
mArrayList.add(mDbModel);
} while (mCursor.moveToNext());
}
mAdapter = new ListAdapter(MainActivity.this, mArrayList);
listName.setAdapter(mAdapter);
}
deleteing values
public void deleteItem(String id) {
SQLiteDatabase mDatabase = mBaseSqlLiteHelper.getWritableDatabase();
String delete = "Delete from NAMES Where _id =" + id;
mDatabase.execSQL(delete);
mDatabase.close();
mAdapter.notifyDataSetChanged();
mArrayList.remove(id);
}
//updating item
public static void updateItem(String id) {
SQLiteDatabase mDatabase = mBaseSqlLiteHelper.getWritableDatabase();
String update = "Update NAMES set name=\""
+ edtAdd.getText().toString() + "\" where _id=" + id;
mDatabase.execSQL(update);
mDatabase.close();
}
}
package com.example.databasesample;
public class DatabaseConstants {
public static final String CREATE_TABLE_PROFILE_QUERY = "CREATE TABLE NAMES("
+ " _id integer primary key autoincrement," + " name VARCHAR"
+ ")";
}
package com.example.databasesample;
import android.content.Context;
android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DataBaseSqlLiteHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "My Sample DataBase";
private static final int DATABASE_VERSION = 1;
public DataBaseSqlLiteHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db)
{
db.execSQL(DatabaseConstants.CREATE_TABLE_PROFILE_QUERY);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
package com.example.databasesample;
public class DBModel {
String id;
String name;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
package com.example.databasesample;
import java.util.ArrayList;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.TextView;
public class ListAdapter extends BaseAdapter {
Context mContext;
ArrayList<DBModel> mArrayList;
public ListAdapter(Context mContext, ArrayList<DBModel> models) {
// TODO Auto-generated constructor stub
this.mArrayList = models;
this.mContext = mContext;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return mArrayList.size();
}
#Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return arg0;
}
#Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return arg0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
if (convertView == null) {
LayoutInflater mLayoutInflater = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = mLayoutInflater.inflate(R.layout.list_layout, parent,
false);
TextView txtId = (TextView) convertView.findViewById(R.id.txtId);
txtId.setText(mArrayList.get(position).getId());
TextView txtName = (TextView) convertView
.findViewById(R.id.txtName);
txtName.setText(mArrayList.get(position).getName());
Button btnUpdate=(Button)convertView.findViewById(R.id.btnUpdate);
btnUpdate.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
MainActivity.updateItem(mArrayList.get(position).getId());
}
});
}
return convertView;
}
}
//activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
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=".MainActivity" >
<EditText
android:id="#+id/edtEnterName"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="Enter Name" />
<Button
android:id="#+id/btnAdd"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/edtEnterName"
android:text="Add to Database" />
<Button
android:id="#+id/btnShow"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/btnAdd"
android:text="Show" />
<ListView
android:id="#+id/listName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/btnShow" >
</ListView>
//listlayout.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="#+id/txtId"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/txtName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_toRightOf="#+id/txtId" />
<Button
android:id="#+id/btnUpdate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/txtName"
android:text="Update" />
Here I make an app in which you can add ,edit and update your database.i use Two main classes First DataBaseSqlLiteHelper.java to create databse and DatabaseConstants.java to create table. To delete item from db click on list and for update first enter value in edit text.comment on this if you need further help.
Ok if you want only a single value to show on database then you can do like this
take a textView
TextView txtName;
initialize it in my above method of initialize();
then make a method to get single value
// Getting single Name to textView
public void getContact(String id) {
SQLiteDatabase db = mBaseSqlLiteHelper.getReadableDatabase();
String select="Select name from NAMES Where _id ="+id;
Cursor mCursor=db.rawQuery(select,null);
if (mCursor!=null) {
mCursor.moveToFirst();
String name=mCursor.getString(0);
txtName.setText(name);
}
db.close();
}
then call this method on the click of some button and pass the id of the row you want to select.

Android: ListView with CheckBox, populated from SQLite database not quite working

As with several other posts here, I am trying to create a ListView that includes a CheckBox for each row, and use a SQLite database to store the current state of the selection.
Starting with the example at http://appfulcrum.com/?p=351, which did not quite work as is, I created a simple app that creates the database, populates it with 20 items, and displays the list.
It successfully retrieves the state and stores the state of the selection.
BUT, it does not correctly show the CheckBox state if I change it, scroll to the other end of the list, and scroll back. e.g. if I select the first CheckBox, scroll to the bottom, and come back to the top, the CheckBox is no longer set. This is being run on an Android 2.1 Samsung handset.
If I return to the main screen, come back into the list, the CheckBox is correctly set, so the database has indeed been updated.
The example extends SimpleCursorAdapter, and the getView() invokes setChecked() with true or false as appropriate based on the value of the selection column in the table.
Below are all the sources.
I'd certainly appreciate being told, "Duh, here's your problem..."
CustomListViewDB.java
// src/CustomListViewDB.java
package com.appfulcrum.blog.examples.listviewcustomdb;
import android.app.ListActivity;
import android.database.Cursor;
import android.database.SQLException;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
public class CustomListViewDB extends ListActivity {
private ListView mainListView = null;
CustomSqlCursorAdapter adapter = null;
private SqlHelper dbHelper = null;
private Cursor currentCursor = null;
private ListView listView = null;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.simple);
if (this.dbHelper == null) {
this.dbHelper = new SqlHelper(this);
}
listView = getListView();
listView.setItemsCanFocus(false);
listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
//listView.setClickable(true);
Button btnClear = (Button) findViewById(R.id.btnClear);
btnClear.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Toast.makeText(getApplicationContext(),
" You clicked Clear button", Toast.LENGTH_SHORT).show();
ClearDBSelections();
}
});
new SelectDataTask().execute();
this.mainListView = getListView();
mainListView.setCacheColorHint(0);
}
#Override
protected void onRestart() {
super.onRestart();
new SelectDataTask().execute();
}
#Override
protected void onPause() {
super.onPause();
this.dbHelper.close();
}
protected void ClearDBSelections() {
this.adapter.ClearSelections();
}
private class SelectDataTask extends AsyncTask<Void, Void, String> {
protected String doInBackground(Void... params) {
try {
CustomListViewDB.this.dbHelper.createDatabase(dbHelper.dbSqlite);
CustomListViewDB.this.dbHelper.openDataBase();
CustomListViewDB.this.currentCursor = CustomListViewDB.this.dbHelper
.getCursor();
} catch (SQLException sqle) {
throw sqle;
}
return null;
}
// can use UI thread here
protected void onPostExecute(final String result) {
startManagingCursor(CustomListViewDB.this.currentCursor);
int[] listFields = new int[] { R.id.txtTitle };
String[] dbColumns = new String[] { SqlHelper.COLUMN_TITLE };
CustomListViewDB.this.adapter = new CustomSqlCursorAdapter(
CustomListViewDB.this, R.layout.single_item,
CustomListViewDB.this.currentCursor, dbColumns, listFields,
CustomListViewDB.this.dbHelper);
setListAdapter(CustomListViewDB.this.adapter);
}
}
}
CustomSqlCursorAdapter.java
// src/CustomSqlCursorAdapter.java
package com.appfulcrum.blog.examples.listviewcustomdb;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
public class CustomSqlCursorAdapter extends SimpleCursorAdapter {
private Context mContext;
private SqlHelper mDbHelper;
private Cursor mCurrentCursor;
public CustomSqlCursorAdapter(Context context, int layout, Cursor c,
String[] from, int[] to, SqlHelper dbHelper) {
super(context, layout, c, from, to);
this.mCurrentCursor = c;
this.mContext = context;
this.mDbHelper = dbHelper;
}
public View getView(int pos, View inView, ViewGroup parent) {
View v = inView;
if (v == null) {
LayoutInflater inflater = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = inflater.inflate(R.layout.single_item, null);
}
if (!this.mCurrentCursor.moveToPosition(pos)) {
throw new SQLException("CustomSqlCursorAdapter.getView: Unable to move to position: "+pos);
}
CheckBox cBox = (CheckBox) v.findViewById(R.id.bcheck);
// save the row's _id value in the checkbox's tag for retrieval later
cBox.setTag(Integer.valueOf(this.mCurrentCursor.getInt(0)));
if (this.mCurrentCursor.getInt(SqlHelper.COLUMN_SELECTED_idx) != 0) {
cBox.setChecked(true);
Log.w("SqlHelper", "CheckBox true for pos "+pos+", id="+this.mCurrentCursor.getInt(0));
} else {
cBox.setChecked(false);
Log.w("SqlHelper", "CheckBox false for pos "+pos+", id="+this.mCurrentCursor.getInt(0));
}
//cBox.setOnClickListener(this);
cBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
Log.w("SqlHelper", "Selected a CheckBox and in onCheckedChanged: "+isChecked);
Integer _id = (Integer) buttonView.getTag();
ContentValues values = new ContentValues();
values.put(SqlHelper.COLUMN_SELECTED,
isChecked ? Integer.valueOf(1) : Integer.valueOf(0));
mDbHelper.dbSqlite.beginTransaction();
try {
if (mDbHelper.dbSqlite.update(SqlHelper.TABLE_NAME, values, "_id=?",
new String[] { Integer.toString(_id) }) != 1) {
throw new SQLException("onCheckedChanged failed to update _id="+_id);
}
mDbHelper.dbSqlite.setTransactionSuccessful();
} finally {
mDbHelper.dbSqlite.endTransaction();
}
Log.w("SqlHelper", "-- _id="+_id+", isChecked="+isChecked);
}
});
TextView txtTitle = (TextView) v.findViewById(R.id.txtTitle);
txtTitle.setText(this.mCurrentCursor.getString(this.mCurrentCursor
.getColumnIndex(SqlHelper.COLUMN_TITLE)));
return (v);
}
public void ClearSelections() {
this.mDbHelper.clearSelections();
this.mCurrentCursor.requery();
}
}
ListViewWithDBActivity.java
package com.appfulcrum.blog.examples.listviewcustomdb;
import android.app.Activity;
import android.os.Bundle;
public class ListViewWithDBActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
}
SqlHelper
// SqlHelper.java
package com.appfulcrum.blog.examples.listviewcustomdb;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteQueryBuilder;
import android.database.sqlite.SQLiteStatement;
import android.util.Log;
public class SqlHelper extends SQLiteOpenHelper {
private static final String DATABASE_PATH = "/data/data/com.appfulcrum.blog.examples.listviewcustomdb/databases/";
public static final String DATABASE_NAME = "TODOList";
public static final String TABLE_NAME = "ToDoItems";
public static final int ToDoItems_VERSION = 1;
public static final String COLUMN_ID = "_id"; // 0
public static final String COLUMN_TITLE = "title"; // 1
public static final String COLUMN_NAME_DESC = "description";// 2
public static final String COLUMN_SELECTED = "selected"; // 3
public static final int COLUMN_SELECTED_idx = 3;
public SQLiteDatabase dbSqlite;
private Context mContext;
public SqlHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
mContext = context;
}
#Override
public void onCreate(SQLiteDatabase db) {
createDB(db);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w("SqlHelper", "Upgrading database from version " + oldVersion
+ " to " + newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS ToDoItems;");
createDB(db);
}
public void createDatabase(SQLiteDatabase db) {
createDB(db);
}
private void createDB(SQLiteDatabase db) {
if (db == null) {
db = mContext.openOrCreateDatabase(DATABASE_NAME, 0, null);
}
db.execSQL("CREATE TABLE IF NOT EXISTS ToDoItems (_id INTEGER PRIMARY KEY, title TEXT, "
+" description TEXT, selected INTEGER);");
db.setVersion(ToDoItems_VERSION);
//
// Generate a few rows for an example
//
// find out how many rows already exist, and make sure there's some minimum
SQLiteStatement s = db.compileStatement("select count(*) from ToDoItems;");
long count = s.simpleQueryForLong();
for (int i = 0; i < 20-count; i++) {
db.execSQL("INSERT INTO ToDoItems VALUES(NULL,'Task #"+i+"','Description #"+i+"',0);");
}
}
public void openDataBase() throws SQLException {
String myPath = DATABASE_PATH + DATABASE_NAME;
dbSqlite = SQLiteDatabase.openDatabase(myPath, null,
SQLiteDatabase.OPEN_READWRITE);
}
#Override
public synchronized void close() {
if (dbSqlite != null)
dbSqlite.close();
super.close();
}
public Cursor getCursor() {
SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
queryBuilder.setTables(TABLE_NAME);
String[] asColumnsToReturn = new String[] { COLUMN_ID, COLUMN_TITLE,
COLUMN_NAME_DESC, COLUMN_SELECTED };
Cursor mCursor = queryBuilder.query(dbSqlite, asColumnsToReturn, null,
null, null, null, COLUMN_ID+" ASC");
return mCursor;
}
public void clearSelections() {
ContentValues values = new ContentValues();
values.put(COLUMN_SELECTED, 0);
this.dbSqlite.update(SqlHelper.TABLE_NAME, values, null, null);
}
}
Start.java
//src/Start.java
package com.appfulcrum.blog.examples.listviewcustomdb;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class Start extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button btnSimple = (Button) findViewById(R.id.btnSimple);
btnSimple.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Toast.makeText(getApplicationContext(),
" You clicked ListView From DB button", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(v.getContext(), CustomListViewDB.class);
startActivityForResult(intent, 0);
}
});
}
}
layout/main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/buttonlayout" android:orientation="vertical"
android:layout_width="fill_parent" android:layout_height="fill_parent"
android:gravity="left|top" android:paddingTop="2dp"
android:paddingBottom="2dp">
<TextView android:id="#+id/txtTest" android:layout_width="fill_parent"
android:layout_height="wrap_content" android:textStyle="bold"
android:text="#string/app_name" android:textSize="15sp"
android:textColor="#FF0000" android:gravity="center_vertical"
android:paddingLeft="5dp">
</TextView>
<Button android:id="#+id/btnSimple"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="15sp"
android:text="Listview from DB"
android:textColor="#000000"
>
</Button>
</LinearLayout>
layout/simple.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent">
<LinearLayout android:id="#+id/buttonlayout"
android:orientation="horizontal" android:layout_width="fill_parent"
android:layout_height="wrap_content" android:height="32dp"
android:gravity="left|top" android:paddingTop="2dp"
android:paddingBottom="2dp">
<LinearLayout android:id="#+id/buttonlayout2"
android:orientation="horizontal" android:layout_height="wrap_content"
android:gravity="left|center_vertical" android:layout_width="wrap_content"
android:layout_gravity="left|center_vertical">
<TextView android:id="#+id/txtTest"
android:layout_width="fill_parent"
android:layout_height="fill_parent" android:textStyle="bold"
android:text="#string/list_header" android:textSize="15sp"
android:gravity="center_vertical" android:paddingLeft="5dp">
</TextView>
<Button android:id="#+id/btnClear"
android:layout_width="wrap_content"
android:layout_height="wrap_content" android:text="Clear"
android:textSize="15sp" android:layout_marginLeft="10px"
android:layout_marginRight="10px"
android:layout_marginBottom="2px"
android:layout_marginTop="2px" android:height="15dp"
android:width="70dp"></Button>
</LinearLayout>
</LinearLayout>
<TableLayout android:id="#+id/TableLayout01"
android:layout_width="fill_parent" android:layout_height="fill_parent"
android:stretchColumns="*">
<TableRow>
<ListView android:id="#android:id/list"
android:layout_width="wrap_content"
android:layout_height="wrap_content"></ListView>
</TableRow>
</TableLayout>
</LinearLayout>
layout/single_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent" android:layout_height="wrap_content"
android:orientation="horizontal" android:gravity="center_vertical">
<CheckBox android:id="#+id/bcheck"
android:layout_width="wrap_content"
android:layout_height="fill_parent" />
<TextView android:id="#+id/txtTitle"
android:layout_width="wrap_content" android:gravity="left|center_vertical"
android:layout_height="?android:attr/listPreferredItemHeight"
android:layout_alignParentLeft="true"
android:textSize="20sp" android:text="Test"
android:textStyle="bold" android:paddingLeft="5dp"
android:paddingRight="2dp" android:focusable="false"
android:focusableInTouchMode="false"></TextView>
<LinearLayout android:layout_width="fill_parent"
android:layout_height="wrap_content" android:orientation="horizontal"
android:gravity="right|center_vertical">
</LinearLayout>
</LinearLayout>
values/strings.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="hello">Hello World, ListViewWithDBActivity!</string>
<string name="app_name">ListViewWithDB</string>
<string name="list_header">List Headers</string>
</resources>
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
android:versionCode="1" android:versionName="1.0"
package="com.appfulcrum.blog.examples.listviewcustomdb">
<application android:icon="#drawable/icon"
android:label="#string/app_name"
android:theme="#android:style/Theme.NoTitleBar">
>
<activity android:name=".Start" android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".CustomListViewDB"></activity>
</application>
<uses-sdk android:minSdkVersion="7" /> <!-- android 1.6 -->
</manifest>
If you want to build, throw some arbitrary icon.png into drawable.
Thanks in advance.
I found the most complete solution to the problem off-site.
At Android ListView with CheckBox : Retain State
Appreciate the help folks.
The Views in a ListView are recycled, and this sounds like an issue with that. You probably need to invalidate your onCheckedChangedListener so that when you do setChecked() it isn't calling the previous listener inadvertently. There could be other ramifications of the recycling as well, so keep that in mind.
So try:
cBox.setOnCheckedChangeListener(null);
...
cBox.setChecked();
...
cBox.setOnCheckedChangeListner(<real listener);

Categories

Resources