I was looking for an example/tutorial to insert datas in a sqlLite db and display the datas in a listview. Well this is a good example: http://androidsolution4u.blogspot.it/2013/09/android-populate-listview-from-sqlite.html And it works. I implemented the code in mine and works. The problem is that if i want insert another one filed nothing appears in the listview and the activity is empty.I added a field called address as string like the others and in every part of code i added what is need copying from the others (of course changing the names). But when i try to add the item not appears. Of course i update the xml files with new field. I can't write the whole code because it's too much. But if someone can help me to find a way out i'll write the part of code required. Thanks
EDIT: the code is equal at the example but with the field i need to add.
The DisplayActivity
public class DisplayActivity extends Activity {
private DbHelper mHelper;
private SQLiteDatabase dataBase;
private ArrayList<String> userId = new ArrayList<String>();
private ArrayList<String> user_fName = new ArrayList<String>();
private ArrayList<String> user_lName = new ArrayList<String>();
private ArrayList<String> user_address = new ArrayList<String>();
private ListView userList;
private AlertDialog.Builder build;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.display_activity);
userList = (ListView) findViewById(R.id.List);
mHelper = new DbHelper(this);
//add new record
findViewById(R.id.btnAdd).setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(), AddActivity.class);
i.putExtra("update", false);
startActivity(i);
}
});
//click to update data
userList.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
Intent i = new Intent(getApplicationContext(), AddActivity.class);
i.putExtra("Fname", user_fName.get(arg2));
i.putExtra("Lname", user_lName.get(arg2));
i.putExtra("address", user_address.get(arg2));
i.putExtra("ID", userId.get(arg2));
i.putExtra("update", true);
startActivity(i);
}
});
//long click to delete data
userList.setOnItemLongClickListener(new OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView<?> arg0, View arg1, final int arg2, long arg3) {
build = new AlertDialog.Builder(DisplayActivity.this);
build.setTitle("Delete " + user_fName.get(arg2) + " " + user_lName.get(arg2) + " " + user_address(arg2));
build.setMessage("Do you want to delete ?");
build.setPositiveButton("Yes",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Toast.makeText( getApplicationContext(),
user_fName.get(arg2) + " "
+ user_lName.get(arg2)
+ user_address.get(arg2)
+ " is deleted.", 3000).show();
dataBase.delete(
DbHelper.TABLE_NAME,
DbHelper.KEY_ID + "="
+ userId.get(arg2), null);
displayData();
dialog.cancel();
}
});
build.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
AlertDialog alert = build.create();
alert.show();
return true;
}
});
}
#Override
protected void onResume() {
displayData();
super.onResume();
}
/**
* displays data from SQLite
*/
private void displayData() {
dataBase = mHelper.getWritableDatabase();
Cursor mCursor = dataBase.rawQuery("SELECT * FROM " + DbHelper.TABLE_NAME, null);
userId.clear();
user_fName.clear();
user_lName.clear();
user_address.clear();
if (mCursor.moveToFirst()) {
do {
userId.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_ID)));
user_fName.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_FNAME)));
user_lName.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_LNAME)));
} while (mCursor.moveToNext());
}
DisplayAdapter disadpt = new DisplayAdapter(DisplayActivity.this,userId, user_fName, user_lName, user_address);
userList.setAdapter(disadpt);
mCursor.close();
}
}
The DisplayAdapter
public class DisplayAdapter extends BaseAdapter {
private Context mContext;
private ArrayList<String> id;
private ArrayList<String> firstName;
private ArrayList<String> lastName;
private ArrayList<String> address;
public DisplayAdapter(Context c, ArrayList<String> id,ArrayList<String> fname, ArrayList<String> lname, ArrayList<String> address) {
this.mContext = c;
this.id = id;
this.firstName = fname;
this.lastName = lname;
this.address = address;
}
public int getCount() {
// TODO Auto-generated method stub
return id.size();
}
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
public View getView(int pos, View child, ViewGroup parent) {
Holder mHolder;
LayoutInflater layoutInflater;
if (child == null) {
layoutInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
child = layoutInflater.inflate(R.layout.listcell, null);
mHolder = new Holder();
mHolder.txt_id = (TextView) child.findViewById(R.id.txt_id);
mHolder.txt_fName = (TextView) child.findViewById(R.id.txt_fName);
mHolder.txt_lName = (TextView) child.findViewById(R.id.txt_lName);
mHolder.txt_address = (TextView) child.findViewById(R.id.txt_address);
child.setTag(mHolder);
} else {
mHolder = (Holder) child.getTag();
}
mHolder.txt_id.setText(id.get(pos));
mHolder.txt_fName.setText(firstName.get(pos));
mHolder.txt_lName.setText(lastName.get(pos));
mHolder.txt_address.setText(address.get(pos));
return child;
}
public class Holder {
TextView txt_id;
TextView txt_fName;
TextView txt_lName;
TextView txt_address;
}
}
The DbHelper
public class DbHelper extends SQLiteOpenHelper {
static String DATABASE_NAME="userdata";
public static final String TABLE_NAME="user";
public static final String KEY_FNAME="fname";
public static final String KEY_LNAME="lname";
public static final String KEY_ID="id";
public static final String KEY_ADDRESS="address";
public DbHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_TABLE="CREATE TABLE "+TABLE_NAME+" ("+KEY_ID+" INTEGER PRIMARY KEY, "+KEY_FNAME+" TEXT, "+KEY_LNAME+" TEXT, "+KEY_ADDRESS+" TEXT)";
db.execSQL(CREATE_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME);
onCreate(db);
}
}
And the AddActivity
public class AddActivity extends Activity implements OnClickListener {
private Button btn_save;
private EditText edit_first,edit_last,edit_address;
private DbHelper mHelper;
private SQLiteDatabase dataBase;
private String id,fname,lname,address;
private boolean isUpdate;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_activity);
btn_save=(Button)findViewById(R.id.save_btn);
edit_first=(EditText)findViewById(R.id.frst_editTxt);
edit_last=(EditText)findViewById(R.id.last_editTxt);
edit_address=(EditText)findViewById(R.id.address_editTxt);
isUpdate=getIntent().getExtras().getBoolean("update");
if(isUpdate)
{
id=getIntent().getExtras().getString("ID");
fname=getIntent().getExtras().getString("Fname");
lname=getIntent().getExtras().getString("Lname");
address=getIntent().getExtras().getString("address");
edit_first.setText(fname);
edit_last.setText(lname);
edit_address.setText(address);
}
btn_save.setOnClickListener(this);
mHelper=new DbHelper(this);
}
// saveButton click event
public void onClick(View v) {
fname=edit_first.getText().toString().trim();
lname=edit_last.getText().toString().trim();
address=edit_address.getText().toString().trim();
if(fname.length()>0 && lname.length()>0 && address.length()>0)
{
saveData();
}
else
{
AlertDialog.Builder alertBuilder=new AlertDialog.Builder(AddActivity.this);
alertBuilder.setTitle("Invalid Data");
alertBuilder.setMessage("Please, Enter valid data");
alertBuilder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alertBuilder.create().show();
}
}
/**
* save data into SQLite
*/
private void saveData(){
dataBase=mHelper.getWritableDatabase();
ContentValues values=new ContentValues();
values.put(DbHelper.KEY_FNAME,fname);
values.put(DbHelper.KEY_LNAME,lname );
values.put(DbHelper.KEY_ADDRESS,address );
System.out.println("");
if(isUpdate)
{
//update database with new data
dataBase.update(DbHelper.TABLE_NAME, values, DbHelper.KEY_ID+"="+id, null);
}
else
{
//insert data into database
dataBase.insert(DbHelper.TABLE_NAME, null, values);
}
//close database
dataBase.close();
finish();
}
}
That's all. I can't find the problem. Helps?
Forgotten in displayData() user_address.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_ADDRESS)));
Related
This question already has answers here:
Deleting Row in SQLite in Android
(18 answers)
Closed 6 years ago.
I know there are lots of threads with more or less same topic but none of them covers my situation:
I have delete button that delete one item in a listView but when you close the app and reopen it the items reappears. I don't know how to fix this .
DatabaseHelper.java
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "todo.db";
public static final int DATABASE_VERSION = 1;
public static final String ITEMS_TABLE = "items";
private static DatabaseHelper instance = null;
public static DatabaseHelper getInstance(Context context) {
if(instance == null) {
instance = new DatabaseHelper(context);
}
return instance;
}
private DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String createQuery = "CREATE TABLE " + ITEMS_TABLE + " (" +
"_id INTEGER PRIMARY KEY AUTOINCREMENT," +
"description TEXT NOT NULL, " +
"completed INTEGER NOT NULL DEFAULT 0)";
db.execSQL(createQuery);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
The button works fine but it does not delete permently I don't know if it is the code or if it is where I am placing it in my MainActivity if someone would please tell that would much appreciated.
MainActivity.java
public class MainActivity extends AppCompatActivity {
private static final String LOG_TAG = "ToDoApp";
private ToDoListManager listManager;
private ToDoItemAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView todoList = (ListView) findViewById(R.id.todo_list);
listManager = new ToDoListManager(getApplicationContext());
adapter = new ToDoItemAdapter(
this,
listManager.getList()
);
todoList.setAdapter(adapter);
ImageButton addButton = (ImageButton) findViewById(R.id.add_item);
addButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onAddButtonClick();
}
});
}
#Override
protected void onPause() {
super.onPause();
}
private void onAddButtonClick() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(R.string.add_item);
final EditText input = new EditText(this);
input.setInputType(InputType.TYPE_CLASS_TEXT);
builder.setView(input);
builder.setPositiveButton(
R.string.ok,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
ToDoItem item = new ToDoItem(
input.getText().toString(),
false
);
listManager.addItem(item);
adapter.swapItems(listManager.getList());
}
});
builder.setNegativeButton(
R.string.cancel,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.show();
}
private class ToDoItemAdapter extends ArrayAdapter<ToDoItem> {
private Context context;
private List<ToDoItem> items;
private LayoutInflater inflater;
public ToDoItemAdapter(
Context context,
List<ToDoItem> items
) {
super(context, -1, items);
this.context = context;
this.items = items;
this.inflater = LayoutInflater.from(context);
}
public void swapItems(List<ToDoItem> items) {
this.items = items;
notifyDataSetChanged();
}
#Override
public int getCount() {
return items.size();
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ItemViewHolder holder;
if(convertView == null) {
convertView = inflater.inflate(R.layout.to_do_item_layout, parent, false);
holder = new ItemViewHolder();
holder.itemDescription = (TextView) convertView.findViewById(R.id.item);
holder.itemState = (CheckBox) convertView.findViewById(R.id.checkBox);
convertView.setTag(holder);
}else {
holder = (ItemViewHolder) convertView.getTag();
}
holder.itemDescription.setText(items.get(position).getDescription());
holder.itemState.setChecked(items.get(position).isComplete());
holder.itemState.setTag(items.get(position));
convertView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ToDoItem item = (ToDoItem) holder.itemState.getTag();
item.toggleComplete();
listManager.updateItem(item);
notifyDataSetChanged();
}
});
ImageButton deleteButton = (ImageButton) convertView.findViewById(R.id.delete_Button);
deleteButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
items.remove(items.get(position));
notifyDataSetChanged();
}
});
holder.itemState.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ToDoItem item = (ToDoItem) holder.itemState.getTag();
item.toggleComplete();
listManager.updateItem(item);
notifyDataSetChanged();
}
});
return convertView;
}
}
public static class ItemViewHolder{
public TextView itemDescription;
public CheckBox itemState;
}
}
ToDoListManager.java
public class ToDoListManager {
private DatabaseHelper dbHelper;
public ToDoListManager(Context context) {
dbHelper = DatabaseHelper.getInstance(context);
}
public List<ToDoItem> getList() {
SQLiteDatabase db = dbHelper.getReadableDatabase();
Cursor cursor = db.rawQuery(
"SELECT * FROM " + DatabaseHelper.ITEMS_TABLE,
null
);
List<ToDoItem> items = new ArrayList<>();
if(cursor.moveToFirst()) {
while(!cursor.isAfterLast()) {
ToDoItem item = new ToDoItem(
cursor.getString(cursor.getColumnIndex("description")),
cursor.getInt(cursor.getColumnIndex("completed")) != 0,
cursor.getLong(cursor.getColumnIndex("_id"))
);
items.add(item);
cursor.moveToNext();
}
}
cursor.close();
return items;
}
public void addItem(ToDoItem item) {
ContentValues newItem = new ContentValues();
newItem.put("description", item.getDescription());
newItem.put("completed", item.isComplete());
SQLiteDatabase db = dbHelper.getWritableDatabase();
db.insert(DatabaseHelper.ITEMS_TABLE, null, newItem);
}
public void updateItem(ToDoItem item) {
ContentValues editItem = new ContentValues();
editItem.put("description", item.getDescription());
editItem.put("completed", item.isComplete());
SQLiteDatabase db = dbHelper.getWritableDatabase();
String[] args = new String[] { String.valueOf(item.getId()) };
db.update(DatabaseHelper.ITEMS_TABLE, editItem, "_id=?", args);
}
}
ToDoItem.java
public class ToDoItem {
private String description;
private boolean isComplete;
private long id;
public ToDoItem(String description, boolean isComplete) {
this(description, isComplete, -1);
}
public ToDoItem(String description,boolean isComplete,long id) {
this.description = description;
this.isComplete = isComplete;
this.id = id;
}
public String getDescription() {
return description;
}
public boolean isComplete() {
return isComplete;
}
public void toggleComplete() {
isComplete = !isComplete;
}
public long getId() {return id;}
#Override
public String toString() {
return getDescription();
}
}
you just remove items in your adapter class that causes the item delete from the current listView. but you have not any function in your ToDoListManager.java that remove items from your database. deleting from a listView does not affect to your database items.
you can add this function to your ToDoListManager.java class
public void deleteItem(long itemId) {
SQLiteDatabase db = dbHelper.getWritableDatabase();
db.delete(DatabaseHelper.ITEMS_TABLE, "_id = ?",
new String[] { String.valueOf(itemId) });
}
and call it from your delete button's onClick, like this
ImageButton deleteButton = (ImageButton) convertView.findViewById(R.id.delete_Button);
deleteButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
long itemId = items.get(position).getId();
items.remove(items.get(position));
listManager.deleteItem(itemId);
notifyDataSetChanged();
}
});
Since you are fetching the data from data base and displaying it in listview,you need to delete the row from database too. make a method in you database adapter that looks some thing like this:
public boolean deleteItem(Long id) {
return Db.delete(DATABASE_TABLE,"_id="+id,null) > 0;
}
then on list view item delete,simply call this method and pass the row id as argument.
I want to display data from sqlite database and I will show to listfragment, but until now have not been able to be displayed
Class Barang.java
public class Barang {
private long id;
private String nama_barang;
private String merk_barang;
private String harga_barang;
public Barang()
{
}
/**
* #return the id
*/
public long getId() {
return id;
}
/**
* #param id the id to set
*/
public void setId(long id) {
this.id = id;
}
/**
* #return the nama_barang
*/
public String getNama_barang() {
return nama_barang;
}
/**
* #param nama_barang the nama_barang to set
*/
public void setNama_barang(String nama_barang) {
this.nama_barang = nama_barang;
}
/**
* #return the merk_barang
*/
public String getMerk_barang() {
return merk_barang;
}
/**
* #param merk_barang the merk_barang to set
*/
public void setMerk_barang(String merk_barang) {
this.merk_barang = merk_barang;
}
/**
* #return the harga_barang
*/
public String getHarga_barang() {
return harga_barang;
}
/**
* #param harga_barang the harga_barang to set
*/
public void setHarga_barang(String harga_barang) {
this.harga_barang = harga_barang;
}
#Override
public String toString()
{
return id +" "+ nama_barang +" "+ merk_barang + " "+ harga_barang;
}
}
DBHelper.java
public class DBHelper extends SQLiteOpenHelper{
public static final String TABLE_NAME = "data_inventori";
public static final String COLUMN_ID = "_id";
public static final String COLUMN_NAME = "nama_barang";
public static final String COLUMN_MERK = "merk_barang";
public static final String COLUMN_HARGA = "harga_barang";
private static final String db_name ="inventori.db";
private static final int db_version=1;
private static final String db_create = "create table "
+ TABLE_NAME + "("
+ COLUMN_ID +" integer primary key autoincrement, "
+ COLUMN_NAME+ " varchar(50) not null, "
+ COLUMN_MERK+ " varchar(50) not null, "
+ COLUMN_HARGA+ " varchar(50) not null);";
public DBHelper(Context context) {
super(context, db_name, null, db_version);
// TODO Auto-generated constructor stub
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(db_create);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
Log.w(DBHelper.class.getName(),"Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
}
DBDataSource.java
public class DBDataSource {
private SQLiteDatabase database;
private DBHelper dbHelper;
private String[] allColumns = { DBHelper.COLUMN_ID,
DBHelper.COLUMN_NAME, DBHelper.COLUMN_MERK,DBHelper.COLUMN_HARGA};
public DBDataSource(Context context)
{
dbHelper = new DBHelper(context);
}
public void open() throws SQLException {
database = dbHelper.getWritableDatabase();
}
public void close() {
dbHelper.close();
}
public Barang createBarang(String nama, String merk, String harga) {
ContentValues values = new ContentValues();
values.put(DBHelper.COLUMN_NAME, nama);
values.put(DBHelper.COLUMN_MERK, merk);
values.put(DBHelper.COLUMN_HARGA, harga);
long insertId = database.insert(DBHelper.TABLE_NAME, null,
values);
Cursor cursor = database.query(DBHelper.TABLE_NAME,
allColumns, DBHelper.COLUMN_ID + " = " + insertId, null,
null, null, null);
cursor.moveToFirst();
Barang newBarang = cursorToBarang(cursor);
cursor.close();
return newBarang;
}
private Barang cursorToBarang(Cursor cursor)
{
Barang barang = new Barang();
barang.setId(cursor.getLong(0));
barang.setNama_barang(cursor.getString(1));
barang.setMerk_barang(cursor.getString(2));
barang.setHarga_barang(cursor.getString(3));
return barang;
}
public ArrayList<Barang> getAllBarang() {
ArrayList<Barang> daftarBarang = new ArrayList<Barang>();
Cursor cursor = database.query(DBHelper.TABLE_NAME,
allColumns, null, null, null, null, null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
Barang barang = cursorToBarang(cursor);
daftarBarang.add(barang);
cursor.moveToNext();
}
cursor.close();
return daftarBarang;
}
public Barang getBarang(long id)
{
Barang barang = new Barang();
Cursor cursor = database.query(DBHelper.TABLE_NAME, allColumns, "_id ="+id, null, null, null, null);
cursor.moveToFirst();
barang = cursorToBarang(cursor);
cursor.close();
return barang;
}
public void updateBarang(Barang b)
{
String strFilter = "_id=" + b.getId();
ContentValues args = new ContentValues();
args.put(DBHelper.COLUMN_NAME, b.getNama_barang());
args.put(DBHelper.COLUMN_MERK, b.getMerk_barang());
args.put(DBHelper.COLUMN_HARGA, b.getHarga_barang() );
database.update(DBHelper.TABLE_NAME, args, strFilter, null);
}
public void deleteBarang(long id)
{
String strFilter = "_id=" + id;
database.delete(DBHelper.TABLE_NAME, strFilter, null);
}
}
MasterBarang.java
public class MasterBarang extends ListFragment implements OnItemLongClickListener {
private DBDataSource dataSource;
private ImageButton bTambah;
private ArrayList<Barang> values;
private Button editButton;
private Button delButton;
private AlertDialog.Builder alertDialogBuilder;
public MasterBarang(){}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_masterbarang, container, false);
bTambah = (ImageButton) rootView.findViewById(R.id.button_tambah);
bTambah.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(getActivity(), CreateData.class);
startActivity(intent);
getActivity().finish();
}
});
ListView lv = (ListView) rootView.findViewById(android.R.id.list);
lv.setOnItemLongClickListener(this);
return rootView;
}
public void OnCreate(Bundle savedInstanceStat){
dataSource = new DBDataSource(getActivity());
dataSource.open();
values = dataSource.getAllBarang();
ArrayAdapter<Barang> adapter = new ArrayAdapter<Barang>(getActivity(),
android.R.layout.simple_list_item_1, values);
setListAdapter(adapter);
}
#Override
public boolean onItemLongClick(final AdapterView<?> adapter, View v, int pos,
final long id) {
final Barang b = (Barang) getListAdapter().getItem(pos);
alertDialogBuilder.setTitle("Peringatan");
alertDialogBuilder
.setMessage("Pilih Aksi")
.setCancelable(false)
.setPositiveButton("Ubah",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
switchToEdit(b.getId());
dialog.dismiss();
}
})
.setNegativeButton("Hapus",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
dataSource.deleteBarang(b.getId());
dialog.dismiss();
getActivity().finish();
startActivity(getActivity().getIntent());
}
}).create().show();
return false;
}
public void switchToEdit(long id)
{
Barang b = dataSource.getBarang(id);
Intent i = new Intent(getActivity(), EditData.class);
Bundle bun = new Bundle();
bun.putLong("id", b.getId());
bun.putString("nama", b.getNama_barang());
bun.putString("merk", b.getMerk_barang());
bun.putString("harga", b.getHarga_barang());
i.putExtras(bun);
finale();
startActivity(i);
}
public void finale()
{
MasterBarang.this.getActivity().finish();
dataSource.close();
}
#Override
public void onResume() {
dataSource.open();
super.onResume();
}
#Override
public void onPause() {
dataSource.close();
super.onPause();
}
}
in simple not displayed
Here is the example code.
First create a layout for one list row.
example : list_row.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="8dp"
>
<TextView
android:id="#+id/name"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textStyle="bold" />
<TextView
android:id="#+id/merk"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#id/name"
android:layout_marginTop="5dp" />
<TextView
android:id="#+id/harga"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#id/merk"
android:layout_marginTop="5dp"/>
</RelativeLayout>
After creating this list_row.xml layout, create a adapter class.
create CustomListAdapter.java
public class CustomListAdapter extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
private ArrayList<Barang> barangList;
public CustomListAdapter(Activity activity, ArrayList<Barang> barangList) {
this.activity = activity;
this.barangList = barangList;
}
/*
get count of the barangList
*/
#Override
public int getCount() {
return barangList.size();
}
#Override
public Object getItem(int location) {
return barangList.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
/*
inflate the items in the list view
*/
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (inflater == null) {
inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
if (convertView == null) {
convertView = inflater.inflate(R.layout.list_row, null);
}
/*
creating objects to access the views
*/
TextView name = (TextView) convertView.findViewById(R.id.name);
TextView merk = (TextView) convertView.findViewById(R.id.merk);
TextView harga = (TextView) convertView.findViewById(R.id.harga);
// getting barang data for the row
Barang barang = barangList.get(position);
name.setText(barang.getNama_barang());
merk.setText(barang.getMerk_barang());
harga.setText(barang.getHarga_barang());
return convertView;
}}
Now in your MasterBarang.java, put the following code in your onCreate method.
values = dataSource.getAllBarang();
CustomListAdapter adapter;
adapter = new CustomListAdapter(getActivity(), values);
setListAdapter(adapter);
Now run the application.. Cheers !
You are using simple list templete as a list view. But in case of custom list view, you should create your custom list model and "BaseAdapter" for the custom list model.
Below links will help you to make custom list view in easier way.
https://www.caveofprogramming.com/guest-posts/custom-listview-with-imageview-and-textview-in-android.html
http://www.androidhive.info/2012/02/android-custom-listview-with-image-and-text/
The problem is you are closing your database in onPause() method, so the reference of the database will get destroyed. Then, you again trying to open the database in onResume() method. So here the null pointer exception occurs.
Solution:
change your onResume() method like this.
#Override
public void onResume() {
dataSource = new DBDataSource(getActivity());
dataSource.open();
super.onResume();
}
Now check it and if you got any error please post it here,.
I have created an application that a user can store player information. I am now looking to have a checkbox to confirm that the player is available. I know that sqlite cannot store a boolean value so was wondering if someone could help me with a way around this. I have added the checkbox but at the moment i have it stored as a 0 value with no functionality.
Below is the display adapter:
public class DisplayAdapter extends BaseAdapter {
private Context mContext;
private ArrayList<String> id;
private ArrayList<String> firstName;
private ArrayList<String> lastName;
private ArrayList<String> Email;
//private ArrayList<String> ConFirm;
public DisplayAdapter(Context c, ArrayList<String> id,ArrayList<String> fname, ArrayList<String> lname, ArrayList<String> email, ArrayList<String> check) {
this.mContext = c;
this.id = id;
this.firstName = fname;
this.lastName = lname;
this.Email = email;
this.ConFirm = check;
}
public int getCount() {
// TODO Auto-generated method stub
return id.size();
}
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
public View getView(int pos, View child, ViewGroup parent) {
Holder mHolder;
LayoutInflater layoutInflater;
if (child == null) {
layoutInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
child = layoutInflater.inflate(R.layout.listcell, null);
mHolder = new Holder();
mHolder.txt_id = (TextView) child.findViewById(R.id.txt_id);
mHolder.txt_fName = (TextView) child.findViewById(R.id.txt_fName);
mHolder.txt_lName = (TextView) child.findViewById(R.id.txt_lName);
mHolder.txt_eMail = (TextView) child.findViewById(R.id.txt_eMail);
mHolder.txt_cOnfirm = (CheckBox) child.findViewById(R.id.txt_cOnfirm);
child.setTag(mHolder);
} else {
mHolder = (Holder) child.getTag();
}
mHolder.txt_id.setText(id.get(pos));
mHolder.txt_fName.setText(firstName.get(pos));
mHolder.txt_lName.setText(lastName.get(pos));
mHolder.txt_eMail.setText(Email.get(pos));
return child;
}
public class Holder {
TextView txt_id;
TextView txt_fName;
TextView txt_lName;
TextView txt_eMail;
CheckBox txt_cOnfirm;
}
}
Here is the display call from the main activity:
private void displayData() {
dataBase = mHelper.getWritableDatabase();
Cursor mCursor = dataBase.rawQuery("SELECT * FROM "
+ DbHelper.TABLE_NAME, null);
userId.clear();
user_fName.clear();
user_lName.clear();
user_eMail.clear();
user_cOnfirm.clear();
if (mCursor.moveToFirst()) {
do {
userId.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_ID)));
user_fName.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_FNAME)));
user_lName.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_LNAME)));
user_eMail.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_EMAIL)));
user_cOnfirm.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_CONFIRM)));
} while (mCursor.moveToNext());
}
DisplayAdapter disadpt = new DisplayAdapter(getActivity(),userId, user_fName, user_lName, user_eMail, user_cOnfirm);
userList.setAdapter(disadpt);
mCursor.close();
}
{
}
And finally the Dbhelper:
public class DbHelper extends SQLiteOpenHelper {
public static String DATABASE_NAME="userdata";
public static final String TABLE_NAME="user";
public static final String KEY_FNAME="fname";
public static final String KEY_LNAME="lname";
public static final String KEY_EMAIL="email";
public static final String KEY_CONFIRM="confirm";
public static final String KEY_ID="id";
public DbHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_TABLE="CREATE TABLE " +TABLE_NAME+" ("+KEY_ID+" INTEGER PRIMARY KEY, "+KEY_FNAME+" TEXT, "+KEY_LNAME+" TEXT, "+KEY_EMAIL+" TEXT, "+KEY_CONFIRM+" TEXT DEFAULT 0)";
db.execSQL(CREATE_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME);
onCreate(db);
}
}
If you would like any more information or code just let me know. Thankyou in advance.
------UPDATED------
Below is the db update function from the FoursFragment.java class:
//add
view.findViewById(R.id.btnAdd).setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent i = new Intent(getActivity(),
AddActivity.class);
i.putExtra("update", false);
startActivity(i);
}
});
//Update
userList.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
Intent i = new Intent(getActivity(),
AddActivity.class);
i.putExtra("Confirm", user_cOnfirm.get(arg2));
i.putExtra("Mail", user_eMail.get(arg2));
i.putExtra("Fname", user_fName.get(arg2));
i.putExtra("Lname", user_lName.get(arg2));
i.putExtra("ID", userId.get(arg2));
i.putExtra("update", true);
startActivity(i);
}
});
//delete
userList.setOnItemLongClickListener(new OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
final int arg2, long arg3) {
build = new AlertDialog.Builder(getActivity());
build.setTitle("Delete " + user_fName.get(arg2) + " "
+ user_lName.get(arg2) + " " + user_eMail.get(arg2));
build.setMessage("Do you want to delete ?");
build.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
Toast.makeText(
getActivity(),
user_fName.get(arg2) + " "
+ user_lName.get(arg2)
+ " is deleted.", 3000).show();
dataBase.delete(
DbHelper.TABLE_NAME,
DbHelper.KEY_ID + "="
+ userId.get(arg2), null);
displayData();
dialog.cancel();
}
});
build.setNegativeButton("No",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
dialog.cancel();
}
});
AlertDialog alert = build.create();
alert.show();
return true;
}
});
return view;
}
}}
#Override
public void onResume() {
displayData();
super.onResume();
}
//display
#SuppressLint("UseValueOf")
private void displayData() {
dataBase = mHelper.getWritableDatabase();
Cursor mCursor = dataBase.rawQuery("SELECT * FROM "
+ DbHelper.TABLE_NAME, null);
userId.clear();
user_fName.clear();
user_lName.clear();
user_eMail.clear();
user_cOnfirm.clear();
if (mCursor.moveToFirst()) {
do {
userId.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_ID)));
user_fName.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_FNAME)));
user_lName.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_LNAME)));
user_eMail.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_EMAIL)));
user_cOnfirm.add(new Boolean((mCursor.getInt(mCursor.getColumnIndex(DbHelper.KEY_CONFIRM)) == 1)));
} while (mCursor.moveToNext());
}
DisplayAdapter disadpt = new DisplayAdapter(getActivity(),userId, user_fName, user_lName, user_eMail, user_cOnfirm);
userList.setAdapter(disadpt);
mCursor.close();
}
{
At first you should change your database table. Don't use the type 'TEXT' to store the boolean, use the type 'TINYINT' instead of that. TINYINT provides 1 byte to save the value. Because of that you can define a constraint (the check at the end), to avoid saving values like 3.
String CREATE_TABLE="CREATE TABLE " +TABLE_NAME+" ("+KEY_ID+" INTEGER PRIMARY KEY, "+KEY_FNAME+" TEXT, "+KEY_LNAME+" TEXT, "+KEY_EMAIL+" TEXT, "+KEY_CONFIRM+" TINYINT DEFAULT 0, check("+KEY_CONFIRM+"=0 OR "+KEY_CONFIRM+"=1)";
To read the value from the database change the loop.
while(mCursor.moveToNext()) {
userId.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_ID)));
user_fName.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_FNAME)));
user_lName.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_LNAME)));
user_eMail.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_EMAIL)));
user_cOnfirm.add(new Boolean((mCursor.getInt(mCursor.getColumnIndex(DbHelper.KEY_CONFIRM)) == 1)));
}
You request an Integer instead of a String as returning value from the database. If you need to get a boolean, you can add the comparision with 1.
Just a tip, you don't need your do-while. The cursor points at the beginning on a position before the first entry. With the call of moveToNext for the first time, you move it to the first entry. If there's no entry, the loop will be skipped.
You need to change the type of the ArrayList to Boolean (with a big B).
Add the initialization with the value for the checkbox
mHolder.txt_cOnfirm.setChecked(ConFirm.get(pos));
These are the necessary changes. I add the changed code below (not tested)
public class DisplayAdapter extends BaseAdapter {
private Context mContext;
private ArrayList<String> id;
private ArrayList<String> firstName;
private ArrayList<String> lastName;
private ArrayList<String> Email; // better name it email
private ArrayList<Boolean> ConFirm; //better name it confirm, it's one word
public DisplayAdapter(Context c, ArrayList<String> id,ArrayList<String> fname, ArrayList<String> lname, ArrayList<String> email, ArrayList<String> check) {
this.mContext = c;
this.id = id;
this.firstName = fname;
this.lastName = lname;
this.Email = email;
this.ConFirm = check;
}
public int getCount() {
// TODO Auto-generated method stub
return id.size();
}
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
public View getView(int pos, View child, ViewGroup parent) {
Holder mHolder; // the m shows that this shall be a member variable, this is just local for this method.
LayoutInflater layoutInflater;
if (child == null) {
layoutInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
child = layoutInflater.inflate(R.layout.listcell, null);
mHolder = new Holder();
mHolder.txt_id = (TextView) child.findViewById(R.id.txt_id);
mHolder.txt_fName = (TextView) child.findViewById(R.id.txt_fName);
mHolder.txt_lName = (TextView) child.findViewById(R.id.txt_lName);
mHolder.txt_eMail = (TextView) child.findViewById(R.id.txt_eMail);
mHolder.txt_cOnfirm = (CheckBox) child.findViewById(R.id.txt_cOnfirm);
child.setTag(mHolder);
} else {
mHolder = (Holder) child.getTag();
}
mHolder.txt_id.setText(id.get(pos));
mHolder.txt_fName.setText(firstName.get(pos));
mHolder.txt_lName.setText(lastName.get(pos));
mHolder.txt_eMail.setText(Email.get(pos));
mHolder.txt_cOnfirm.setChecked(ConFirm.get(pos).booleanValue());
return child;
}
public class Holder {
TextView txt_id;
TextView txt_fName;
TextView txt_lName;
TextView txt_eMail;
CheckBox txt_cOnfirm;
}
}
The part from your main activity
private void displayData() {
dataBase = mHelper.getWritableDatabase();
Cursor mCursor = dataBase.rawQuery("SELECT * FROM "
+ DbHelper.TABLE_NAME, null);
userId.clear();
user_fName.clear();
user_lName.clear();
user_eMail.clear();
user_cOnfirm.clear();
while(mCursor.moveToNext()) {
userId.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_ID)));
user_fName.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_FNAME)));
user_lName.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_LNAME)));
user_eMail.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_EMAIL)));
user_cOnfirm.add(new Boolean((mCursor.getInt(mCursor.getColumnIndex(DbHelper.KEY_CONFIRM)) == 1)));
}
DisplayAdapter disadpt = new DisplayAdapter(getActivity(),userId, user_fName, user_lName, user_eMail, user_cOnfirm);
userList.setAdapter(disadpt);
mCursor.close();
}
{
}
And your DBHelper
public class DbHelper extends SQLiteOpenHelper {
public static String DATABASE_NAME="userdata";
public static final String TABLE_NAME="user";
public static final String KEY_FNAME="fname";
public static final String KEY_LNAME="lname";
public static final String KEY_EMAIL="email";
public static final String KEY_CONFIRM="confirm";
public static final String KEY_ID="id";
public DbHelper(Context context) {
super(context, DATABASE_NAME, null, 2); // The 2 is the version. It have to be higher than the old, because we changed the database schema
}
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_TABLE="CREATE TABLE " +TABLE_NAME+" ("+KEY_ID+" INTEGER PRIMARY KEY, "+KEY_FNAME+" TEXT, "+KEY_LNAME+" TEXT, "+KEY_EMAIL+" TEXT, "+KEY_CONFIRM+" TINYINT DEFAULT 0, check("+KEY_CONFIRM+"=0 OR "+KEY_CONFIRM+"=1)";
db.execSQL(CREATE_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME);
onCreate(db);
}
}
I hope this solves your problem, if not feel free to ask another question, if please rate this answer as positive.
P.s.:
Take a look at the coding guidelines: https://source.android.com/source/code-style.html
I have list-view with check-box which loads data from database. And i have a button too, when i press a button spinner is popping up with 2 messages "EDIT" and "DELETE". Delete is working perfectly fine. and if i select Edit option and press OK then Edit-Text is coming in alert window with two button Ok and Cancel.
Now i want that Whatever i enter in edit-text and press Ok button a list-view data which is selected (Checked) should update with new text whatever i have entered in edit-text. So how to achieve this. Please help me. Any help would be appreciated. Thanks in advance.
My code for creating Database:
public class DataManipulatorClass {
public static final String KEY_ROWID = "id";
private static final String DATABASE_NAME = "mydatabaseclass.db";
private static final int DATABASE_VERSION = 1;
static final String TABLE_NAME = "newtableclass";
private static Context context;
static SQLiteDatabase db;
OpenHelper openHelper = null;
private SQLiteStatement insertStmt;
private static final String INSERT = "insert into " + TABLE_NAME
+ "(classname) values (?)";
public DataManipulatorClass(Context context) {
DataManipulatorClass.context = context;
OpenHelper openHelper = new OpenHelper(DataManipulatorClass.context);
DataManipulatorClass.db = openHelper.getWritableDatabase();
this.insertStmt = DataManipulatorClass.db.compileStatement(INSERT);
//this.db = openHelper.getWritableDatabase();
}
public long insert(String classname) {
this.insertStmt.bindString(1, classname);
return this.insertStmt.executeInsert();
}
public void close() {
if (openHelper != null) {
openHelper.close();
}
}
public void deleteAll() {
db.delete(TABLE_NAME, null, null);
}
public List<String[]> selectAll() {
List<String[]> list = new ArrayList<String[]>();
Cursor cursor = db.query(TABLE_NAME,
new String[] { "id", "classname" }, null, null, null, null,
"classname asc");
int x = 0;
if (cursor.moveToFirst()) {
do {
String[] b1 = new String[] { cursor.getString(0),
cursor.getString(1) };
list.add(b1);
x = x + 1;
} while (cursor.moveToNext());
}
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
cursor.close();
return list;
}
public boolean delete(long rowId) {
/** this method deletes by id, the first column in your database */
return db.delete(TABLE_NAME, KEY_ROWID + "=" + rowId, null) > 0;
}
private static class OpenHelper extends SQLiteOpenHelper {
OpenHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + TABLE_NAME
+ " (id INTEGER PRIMARY KEY, classname TEXT)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
}
}
My Activity class:
public class Classes extends Activity implements OnClickListener {
ImageView imageViewNewClass, imageViewDelete;
ListView mListView;
String[] stg1;
List<String[]> names2 = null;
DataManipulatorClass dataManipulator;
ArrayAdapter<CharSequence> adapterSpinner;
ArrayAdapter<String> adapter;
/** Sliding Menu */
boolean alreadyShowing = false;
private int windowWidth;
private Animation animationClasses;
private RelativeLayout classesSlider;
LayoutInflater layoutInflaterClasses;
#SuppressWarnings("deprecation")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.classes);
imageViewNewClass = (ImageView) findViewById(R.id.newclass);
imageViewDelete = (ImageView) findViewById(R.id.deletemenu);
mListView = (ListView) findViewById(R.id.displaydata);
Display display = getWindowManager().getDefaultDisplay();
windowWidth = display.getWidth();
display.getHeight();
layoutInflaterClasses = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
imageViewDelete.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
deleteMenuSpinner();
}
private void deleteMenuSpinner() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(
Classes.this);
final Spinner spinnerDelete = new Spinner(Classes.this);
alertDialog.setView(spinnerDelete);
adapterSpinner = ArrayAdapter.createFromResource(Classes.this,
R.array.delete_menu,
android.R.layout.simple_spinner_item);
adapterSpinner
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerDelete.setAdapter(adapterSpinner);
alertDialog.setPositiveButton("Ok",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
Delete operation code.....
}
} else {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
Classes.this);
final EditText updateClass = new EditText(
Classes.this);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT);
updateClass.setLayoutParams(lp);
alertDialogBuilder.setView(updateClass);
alertDialogBuilder
.setTitle("Edit Operation");
alertDialogBuilder
.setMessage("Enter New Class Name")
.setCancelable(false)
.setPositiveButton(
"Yes",
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface dialog,
int id) {
}
})
.setNegativeButton(
"No",
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface dialog,
int id) {
dialog.cancel();
}
});
AlertDialog alertDialog = alertDialogBuilder
.create();
alertDialog.show();
}
}
});
alertDialog.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
dialog.cancel();
}
});
alertDialog.show();
}
});
findViewById(R.id.skirrmenu).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (!alreadyShowing) {
alreadyShowing = true;
openSlidingMenu();
}
}
});
imageViewNewClass.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(Classes.this, Class_Create.class);
startActivity(intent);
}
});
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View item,
int position, long id) {
// Toast.makeText(getApplicationContext(),
// "Listview item clicked", Toast.LENGTH_LONG).show();
SparseBooleanArray sp = mListView.getCheckedItemPositions();
StringBuffer str = new StringBuffer();
for (int i = 0; i < sp.size(); i++) {
if (sp.valueAt(i) == true) {
String s = ((TextView) mListView.getChildAt(i))
.getText().toString();
str = str.append(" " + s);
}
}
Toast.makeText(Classes.this,
"Selected items are " + str.toString(),
Toast.LENGTH_LONG).show();
// Intent intent = new Intent(Classes.this, PlayAudio.class);
// startActivity(intent);
}
});
dataManipulator = new DataManipulatorClass(this);
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
names2 = dataManipulator.selectAll();
stg1 = new String[names2.size()];
int x = 0;
String stg;
for (String[] name : names2) {
stg = "Class Name : " + name[1];
stg1[x] = stg;
x++;
}
adapter = new ArrayAdapter<String>(this,
R.layout.custom_list_item_multiple_choice, stg1);
mListView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
mListView.setBackgroundResource(R.drawable.assignmentheader);
mListView.setCacheColorHint(Color.TRANSPARENT);
mListView.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
if (dataManipulator != null)
dataManipulator.close();
}
}
You can try to use adapter.notifyDataSetChanged() when OK button pressed. But it will update whole list. If this is what you need, then here is the solution.
To update one list item you can try this:
private void updateView(int index, String updateText){
View v = yourListView.getChildAt(index -
yourListView.getFirstVisiblePosition());
TextView someText = (TextView) v.findViewById(R.id.sometextview);
someText.setText(updateText);
}
I have stored three values into the database and i want to make search on button click, after clicking on search button it will be move on search screen and there is only search box is presented.
DatabaseHelper.java
public class DatabaseHelper extends SQLiteOpenHelper {
public static String DATABASENAME = "Aadhaar";
public static String PRODUCTTABLE = "Enrolled";
private ArrayList<CandidateModel> cartList = new ArrayList<CandidateModel>();
Context c;
public DatabaseHelper(Context context) {
super(context, DATABASENAME, null, 33);
c = context;
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE if not exists Enrolled(id INTEGER PRIMARY KEY AUTOINCREMENT,"
+ "_id"
+ " TEXT ,"
+ "FirstName"
+ " TEXT,"
+ "LastName"
+ " TEXT)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS" + PRODUCTTABLE);
onCreate(db);
}
public void addProduct(CandidateModel productitem) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("_id", productitem.idno);
contentValues.put("FirstName", productitem.productname);
contentValues.put("LastName", productitem.productprice);
db.insert("Enrolled", null, contentValues);
db.close();
}
// update
public void updateProduct(CandidateModel productList) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("FirstName", productList.productname);
contentValues.put("LastName", productList.productprice);
db.update("Enrolled", contentValues, "_id=" + productList.idno, null);
db.close();
}
public void emptyProduct() {
try {
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL("delete from Enrolled");
db.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public void removeProduct(String productid, String pname, String pprice) {
try {
// SQLiteDatabase db = this.getWritableDatabase();
// db.execSQL("delete from producttable where productidno="
// + productid);
// db.close();
String[] args = { productid };
getWritableDatabase().delete("Enrolled", "_id=?", args);
} catch (Exception e) {
e.printStackTrace();
}
}
public ArrayList<CandidateModel> getProudcts() {
cartList.clear();
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery("select * from Enrolled", null);
if (cursor.getCount() != 0) {
if (cursor.moveToFirst()) {
do {
CandidateModel item = new CandidateModel();
item.idno = cursor.getString(cursor.getColumnIndex("_id"));
item.productname = cursor.getString(cursor
.getColumnIndex("FirstName"));
item.productprice = cursor.getString(cursor
.getColumnIndex("LastName"));
cartList.add(item);
} while (cursor.moveToNext());
}
}
cursor.close();
db.close();
return cartList;
}
}
Aadhar.java
public class Aadhar extends Activity implements OnClickListener {
private Button btn_add, btn_view, btn_search;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btn_add = (Button) findViewById(R.id.btn_add);
btn_view = (Button) findViewById(R.id.btn_view);
btn_search = (Button) findViewById(R.id.btn_search);
btn_add.setOnClickListener(this);
btn_view.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_add:
Intent addintent = new Intent(Aadhar.this, AddRecord.class);
startActivity(addintent);
break;
case R.id.btn_view:
Intent viewintent = new Intent(Aadhar.this, ViewRecord.class);
startActivity(viewintent);
break;
case R.id.btn_search:
Intent searchIntent = new Intent (Aadhar.this, SearchRecord.class);
startActivity(searchIntent);
default:
break;
}
}
}
SearchRecord.java
public class SearchRecord extends Activity implements OnClickListener {
String TAG = "SearchRecord";
private ListView lv;
// Button searchButton;
private EditText search;
CandidateModel cm;
DatabaseHelper db;
public ArrayList<CandidateModel> _candidatelist = new ArrayList<CandidateModel>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search_candidate);
Log.v(TAG, "Searching Candidates");
lv = (ListView) findViewById(R.id.search_listview);
search = (EditText) findViewById(R.id.edit_search);
Log.v(TAG, "Going to enter into TextWatcher");
lv.setTextFilterEnabled(true);
search.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
public void onTextChanged(CharSequence s, int start, int before,
int count) {
Log.v(TAG, "Entered into the Text Changed Method");
((Filterable) _candidatelist).getFilter().filter(s.toString());
Log.v(TAG, "Finished Filtering");
lv.setAdapter((android.widget.ListAdapter) _candidatelist);
}
});
}
CandidateModel.java
public class CandidateModel {
public String getFirstname() {
return fname;
}
public void setFirstname(String fname) {
this.fname = fname;
}
public String getLastname() {
return lname;
}
public void setLastname(String lname) {
this.lname = lname;
}
public String idno="", fname="", lname="";
public String getIdno() {
return idno;
}
public void setIdno(String idno) {
this.idno = idno;
}
}
ViewRecord.java
public class ViewRecord extends Activity {
private ListView listview;
// private EditText search;
String TAG = "ViewRecord";
TextView totalrecords;
DatabaseHelper db;
public ArrayList<CandidateModel> _candidatelist = new ArrayList<CandidateModel>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.view_candidates);
totalrecords = (TextView) findViewById(R.id.totalrecords);
listview = (ListView) findViewById(R.id.listview);
}
#Override
protected void onResume() {
super.onResume();
_candidatelist.clear();
db = new DatabaseHelper(getApplicationContext());
db.getWritableDatabase();
ArrayList<CandidateModel> cand_list = db.getCandidates();
for (int i = 0; i < cand_list.size(); i++) {
String tidno = cand_list.get(i).getIdno();
System.out.println("tidno>>>>>" + tidno);
String tname = cand_list.get(i).getFirstname();
String tprice = cand_list.get(i).getLastname();
CandidateModel _CandidateModel = new CandidateModel();
_CandidateModel.setIdno(tidno);
_CandidateModel.setFirstname(tname);
_CandidateModel.setLastname(tprice);
_candidatelist.add(_CandidateModel);
}
totalrecords.setText("Total Enrollments :-" + _candidatelist.size());
listview.setAdapter(new ListAdapter(this));
db.close();
}
public class ListAdapter extends BaseAdapter {
LayoutInflater inflater;
ViewHolder viewHolder;
public ListAdapter(Context context) {
inflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
return _candidatelist.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = inflater.inflate(R.layout.listview_row, null);
viewHolder = new ViewHolder();
viewHolder._id = (TextView) convertView
.findViewById(R.id.txtdisplaypname);
viewHolder.fname = (TextView) convertView
.findViewById(R.id.txtdisplaypprice);
viewHolder.lname = (TextView) convertView
.findViewById(R.id.txtdisplaypid);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder._id.setText(_candidatelist.get(position).getFirstname()
.trim());
viewHolder.fname.setText(_candidatelist.get(position).getLastname()
.trim());
viewHolder.lname.setText(_candidatelist.get(position).getIdno()
.trim());
final int temp = position;
(convertView.findViewById(R.id.btn_update))
.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
String _id = String.valueOf(_candidatelist
.get(temp).getIdno());
String _fname = _candidatelist.get(temp)
.getFirstname();
String _lname = _candidatelist.get(temp)
.getLastname();
Intent intent = new Intent(ViewRecord.this,
AddUpdateValues.class);
Bundle bundle = new Bundle();
bundle.putString("id", _id);
bundle.putString("name", _fname);
bundle.putString("price", _lname);
intent.putExtras(bundle);
startActivity(intent);
}
});
(convertView.findViewById(R.id.btn_delete))
.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
AlertDialog.Builder alertbox = new AlertDialog.Builder(
ViewRecord.this);
alertbox.setCancelable(true);
alertbox.setMessage("Are you sure you want to delete ?");
alertbox.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface arg0, int arg1) {
Log.i(">>>TEMP>>>", temp + "");
Log.i(">>>getIdno>>>>>>",
_candidatelist.get(temp)
.getIdno().trim()
+ "");
System.out
.println(">>>getIdno>>>>>>"
+ _candidatelist
.get(temp)
.getIdno()
.trim());
db.removeCandidate(
_candidatelist.get(temp)
.getIdno().trim(),
"", "");
ViewRecord.this.onResume();
Toast.makeText(
getApplicationContext(),
"Record Deleted...",
Toast.LENGTH_SHORT).show();
}
});
alertbox.setNegativeButton("No",
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface arg0, int arg1) {
}
});
alertbox.show();
}
});
return convertView;
}
}
public class ViewHolder {
TextView _id;
TextView fname;
TextView lname;
}
}
ArrayList is not Filterable. It says in the Filterable documentation :
Defines a filterable behavior. A filterable class can have its data
constrained by a filter. Filterable classes are usually Adapter
implementations.
I think you should replace your ArrayList by an ArrayAdapter