Data not being inserted in Table on Button Press - android

When I tap the button for inserting the data it says it is successful, but when I check my listview there is no data. But If I add again, then only the data is inserted.
Why is the data only inserted on the second time?
Thanks in advance! :D
This is my Database Helper class:
public static final String DB_NAME = "CartDB";
public static final String TABLE_NAME = "Orders";
public static final String COLUMN_ID = "id";
public static final String NAME ="name";
public static final String SIZE ="size";
public static final String QUANTITY ="quantity";
private static final int DB_VERSION = 1;
public cartDatabaseHelper(Context context)
{
super(context,DB_NAME,null,DB_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String sql = "CREATE TABLE " + TABLE_NAME
+ "(" + COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ NAME + " VARCHAR, "
+ SIZE + " VARCHAR, "
+ QUANTITY + " VARCHAR);";
db.execSQL(sql);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
String sql = "DROP TABLE IF EXIST Orders";
db.execSQL(sql);
onCreate(db);
}
public boolean addPerson(String name, String size, String quantity){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(NAME,name);
contentValues.put(SIZE,size);
contentValues.put(QUANTITY,quantity);
long result = db.insert(TABLE_NAME,null ,contentValues);
if(result == -1)
return false;
else
return true;
}
public Cursor getListContents(){
SQLiteDatabase db = this.getWritableDatabase();
Cursor data = db.rawQuery("SELECT * FROM " + TABLE_NAME, null);
return data;
}
And this is my MainActivity class:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_alcohol_list);
db = new cartDatabaseHelper(this);
GridAlcoholAdapter adapter = new GridAlcoholAdapter(alcoholType.this, images, names);
gridView.setAdapter(adapter);
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
final int position, long id) {
btnAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String name = names.get(position);
String size = textSize.getText().toString().trim();
String quantityNumber = textQuantityNumber.getText().toString().trim();
String bottleCase = textBottleCase.getText().toString().trim();
String bottleCaseQuantity = textQuantity.getText().toString().trim();
textQuantity.setText(quantityNumber + " " + bottleCase);
db.addPerson(name,size,bottleCaseQuantity);
dialog.dismiss();
}
});
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Take appropriate action for each action item click
switch (item.getItemId()) {
case R.id.action_cart:
final Dialog dialog = new Dialog(context);
dialog.setContentView(R.layout.cartdialog);
dialog.setTitle("YOUR CART");
listView = (ListView) dialog.findViewById(R.id.listView);
final ListCartAdapter adapter = new ListCartAdapter(alcoholType.this, orderName, orderSize, orderQuantity);
listView.setAdapter(adapter);
Cursor data = db.getListContents();
data.moveToFirst();
while (data.moveToNext()) {
orderName.add(data.getString(1));
orderSize.add(data.getString(2));
orderQuantity.add(data.getString(3));
}
data.close();
dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialog) {
orderName.clear();
orderSize.clear();
orderQuantity.clear();
}
});
dialog.show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
This is my Adapter Class:
public class ListCartAdapter extends BaseAdapter {
private Context context;
private ArrayList<String> orderName;
private ArrayList<String> orderSize;
private ArrayList<String> orderQuantity;
public ListCartAdapter(Context context, ArrayList<String> orderName, ArrayList<String> orderSize, ArrayList<String> orderQuantity){
// public ListCartAdapter(Context context, ArrayList<String> orderName){
this.context = context;
this.orderName = orderName;
this.orderSize = orderSize;
this.orderQuantity = orderQuantity;
}
#Override
public int getCount() {
return orderName.size();
}
#Override
public Object getItem(int position) {
return orderName.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View listView;
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
listView = inflater.inflate(R.layout.cart_list_item, null);
TextView name = (TextView) listView.findViewById(R.id.textOrderName);
TextView size = (TextView) listView.findViewById(R.id.textOrderSize);
TextView quantity = (TextView) listView.findViewById(R.id.textOrderQuantity);
name.setText(orderName.get(position));
size.setText(orderSize.get(position));
quantity.setText(orderQuantity.get(position));
return listView;
}

Why is the data only inserted on the second time?
The problem is in your while loop. When there is only one order then your while loop body will not be executed because you have used data.moveToNext() as condition. If your order count more than one, only then it will enter into the while loop.
ERROR:
data.moveToFirst();
while (data.moveToNext()) {
orderName.add(data.getString(1));
orderSize.add(data.getString(2));
orderQuantity.add(data.getString(3));
}
SOLUTION:
if(data.moveToFirst())
{
do
{
orderName.add(data.getString(1));
orderSize.add(data.getString(2));
orderQuantity.add(data.getString(3));
} while(data.moveToNext());
}
Hope this will help~

this is happening because you are adding data to orderName,orderSize and orderQuantity after setting adapter to listView. and you are not even calling
adapter.notifyDataSetChanged();
to let the adapter know that dataSet has changed

The problem is that the adapter doesn't know that you have added an element to the database.
After:
db.addPerson(name,size,bottleCaseQuantity);
you should make
adapter.notifyDataSetChanged()

Well guys I fixed the problem
I made a do-while in retrieving the data and it works!
do{
orderName.add(data.getString(1));
orderSize.add(data.getString(2));
orderQuantity.add(data.getString(3));
} while (data.moveToNext());
thanks again to anyone who wanted and helped :D

Related

ListView onItemLongClick view isSelected always returns False

I have a class that extends ListFragment and uses a SimpleCursorAdapter. I have created 2 buttons that enables the user to select/deselect all in the list and this works fine. There could be 200 items in the list, so if they wanted to only select 190 of them, they could select all 200 then deselect 10.
The ListView uses setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
The problem is that I want the user to be able to individually deselect a row by long pressing the row. I use a setOnItemLongClickListener on the ListView but the view.isSelected is always returning false even when the row is selected.
Does anyone know why this is happening.
I've put log statements in to prove this fact.
I have also had a look around the net and some posts are saying that a possible problem is that I am using SimpleCursorAdapter and that it is too basic a component.
I'm not particularly good with adapters, lists and touch events, so could anyone point me in the right direction?
I suppose the obvious thing to tackle, is why the isSelected method always returns false.
public class CarerListForGroupMessageFragment extends ListFragment {
private static final String TAG = CarerListForGroupMessageFragment.class.getSimpleName();
RROnCallApplication rrOnCallApp;
Cursor cursor;
ListView listView;
MyAdapter myAdapter;
OnCarerForGroupMessageSelectedListener mListener;
EditText etext;
Button resetSearch;
Button selectAll;
Button deselectAll;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
rrOnCallApp = (RROnCallApplication) getActivity().getApplicationContext();
cursor = getCarerList(null);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragmentcarerlistforgroupmessage, container, false);
}
#SuppressWarnings("deprecation")
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
String[] from = new String[]{DBModel.C_CARER_FIRSTNAME, DBModel.C_CARER_LASTNAME, DBModel.C_CARER_PHONENUMBER};
int[] to = {R.id.carerrowfirstname, R.id.carerrowlastname, R.id.carerrowtelno};
myAdapter = (MyAdapter) new MyAdapter(getActivity(),R.layout.carerrow , cursor, from, to);
setListAdapter(myAdapter);
getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
getListView().setFastScrollEnabled(true);
getListView().setTextFilterEnabled(true);
selectAll = (Button) getActivity().findViewById(R.id.carerlistselectallgroupmessage);
selectAll.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
for(int i = 0; i < cursor.getCount(); i++){
getListView().setItemChecked(i, true);
}
myAdapter.notifyDataSetChanged();
}
});
deselectAll = (Button) getActivity().findViewById(R.id.carerlistdeselectallgroupmessage);
deselectAll.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
for(int i = 0; i < cursor.getCount(); i++) {
getListView().setItemChecked(i, false);
}
myAdapter.notifyDataSetChanged();
}
});
getListView().setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
//Toast.makeText(getActivity(), "On long click listener", Toast.LENGTH_LONG).show();
boolean ret = false;
if(! view.isSelected()) {
//row in list is not currently selected, so set it as selected
Log.e(TAG, "row postion " + position + " in list is not currently selected");
view.setSelected(true);
Cursor cursor = (Cursor) getListAdapter().getItem(position);
String carerID = cursor.getString(cursor.getColumnIndex(DBModel.C_CARER_ID));
String carerFirstName = cursor.getString(cursor.getColumnIndex(DBModel.C_CARER_FIRSTNAME));
String carerLastName = cursor.getString(cursor.getColumnIndex(DBModel.C_CARER_LASTNAME));
String carerTelNo = cursor.getString(cursor.getColumnIndex(DBModel.C_CARER_PHONENUMBER));
Log.e(TAG, "carerID = " + carerID);
mListener.onCarerForGroupMessageSelected(carerID, carerFirstName, carerLastName, carerTelNo, true);
getListView().setItemChecked(position, true);
myAdapter.notifyDataSetChanged();
ret = true;
} else {
Log.e(TAG, "row " + position + " in list is currently selected");
view.setSelected(false);
Cursor cursor = (Cursor) getListAdapter().getItem(position);
String carerID = cursor.getString(cursor.getColumnIndex(DBModel.C_CARER_ID));
String carerFirstName = cursor.getString(cursor.getColumnIndex(DBModel.C_CARER_FIRSTNAME));
String carerLastName = cursor.getString(cursor.getColumnIndex(DBModel.C_CARER_LASTNAME));
String carerTelNo = cursor.getString(cursor.getColumnIndex(DBModel.C_CARER_PHONENUMBER));
Log.e(TAG, "carerID = " + carerID);
mListener.onCarerForGroupMessageSelected(carerID, carerFirstName, carerLastName, carerTelNo, true);
getListView().setItemChecked(position, false);
myAdapter.notifyDataSetChanged();
ret = true;
}
return ret;
}
});
} // End of onActivityCreated
// Container Activity must implement this interface
public interface OnCarerForGroupMessageSelectedListener {
public void onCarerForGroupMessageSelected(String carerId, String carerFirstName, String carerLastName, String carerTelNo ,boolean longClick);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (OnCarerForGroupMessageSelectedListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString() + " must implement OnCarerForGroupMessageSelectedListener");
}
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
Log.e(TAG, "in onListItemClick");
v.setSelected(true);
//v.setBackgroundColor(Color.parseColor("#FF0000"));
TextView carerName = (TextView) getView().findViewById(R.id.textviewcarername);
Cursor cursor = (Cursor) getListAdapter().getItem(position);
String carerID = cursor.getString(cursor.getColumnIndex(DBModel.C_CARER_ID));
String carerFirstName = cursor.getString(cursor.getColumnIndex(DBModel.C_CARER_FIRSTNAME));
String carerLastName = cursor.getString(cursor.getColumnIndex(DBModel.C_CARER_LASTNAME));
String carerTelNo = cursor.getString(cursor.getColumnIndex(DBModel.C_CARER_PHONENUMBER));
Log.e(TAG, "carerID = " + carerID);
mListener.onCarerForGroupMessageSelected(carerID, carerFirstName, carerLastName, carerTelNo, false);
getListView().setItemChecked(position, true);
myAdapter.notifyDataSetChanged();
}
private class MyAdapter extends SimpleCursorAdapter {
#SuppressWarnings("deprecation")
public MyAdapter(Context context, int layout, Cursor c, String[] from, int[] to) {
super(context, layout, c, from, to);
}
#Override
public
View getView(int position, View convertView, ViewGroup parent) {
Log.e(TAG, "inside myadapter getview");
View v = super.getView(position, convertView, parent);
if(v == null)
return null;
Log.e(TAG, "clicked the listview!");
//Cursor c = (Cursor)getItem(position);
// String tagScanTime = c.getString(c.getColumnIndex(LoginValidate.C_TAG_SCAN_TIME));
// ((TextView)v.findViewById(R.id.rowcarername)).setText(name + " signed " + status +" at ");
return v;
}
}} //end of CarerListFragment
[EDIT 1]
DBModel class
public class DBModel {
private static final String TAG = DBModel.class.getSimpleName();
// table carer column names
public static final String C_CARER_ID_INDEX = BaseColumns._ID;
public static final String C_CARER_ID = "carerid";
public static final String C_CARER_FIRSTNAME = "carerfirstname";
public static final String C_CARER_LASTNAME = "carerlastname";
public static final String C_CARER_PHONENUMBER = "carerphonenumber";
public static final String C_CARER_EMAIL = "careremail";
Context context;
DBHelper dbhelper;
RROnCallApplication rrOnCallApplication;
public DBModel(Context context) {
this.context = context;
dbhelper = new DBHelper();
rrOnCallApplication = (RROnCallApplication) context.getApplicationContext();
}
/**
* inner class to create/open/upgrade database
*
* #author matt
*
*/
private class DBHelper extends SQLiteOpenHelper {
// database name and version number
public static final String DB_NAME = "roadrunneroncall.db";
public static final int DB_VERSION = 3;
// table names
public static final String TABLECARER = "carer";
public DBHelper() {
super(context, DB_NAME, null, DB_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
Log.e(TAG, "SQLiteOpenHelper oncreate ");
String sqlToCreateCarerTable = String
.format("create table %s ( %s INTEGER primary key, %s TEXT, %s TEXT, %s TEXT, %s TEXT, %s TEXT)",
TABLECARER, C_CARER_ID_INDEX, C_CARER_ID, C_CARER_FIRSTNAME,
C_CARER_LASTNAME, C_CARER_PHONENUMBER, C_CARER_EMAIL);
db.execSQL(sqlToCreateCarerTable);
Log.e(TAG, "oncreate " + sqlToCreateCarerTable);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}//end of onUpgrade
}//end of DBHelper
public SQLiteDatabase getDB(){
return dbhelper.getWritableDatabase(RROnCallApplication.getSecretKey().toString());
}
public void deleteTableCarer() {
// open database
SQLiteDatabase db = dbhelper.getWritableDatabase(RROnCallApplication.getSecretKey().toString());
// delete contents of table
db.delete(DBHelper.TABLECARER, null, null);
// close database
// db.close();
}
public void insertIntoCarer(ContentValues cv) {
SQLiteDatabase db = dbhelper.getWritableDatabase(RROnCallApplication.getSecretKey().toString());
db.insertWithOnConflict(DBHelper.TABLECARER, null, cv, SQLiteDatabase.CONFLICT_REPLACE);
// db.close();
}
public Cursor queryAllFromCarer() {
// open database
SQLiteDatabase db = dbhelper.getReadableDatabase(RROnCallApplication.getSecretKey().toString());
return db.query(DBHelper.TABLECARER, null, null, null, null, null, null);
}
Please check this code.
if(!getListView().isItemChecked(position))
instead of
if(! view.isSelected())
And keep boolean flag value inside DBModel class.

Properly delete an sqlite entry from a recyclerView click

my app stores name and result in SQLite database and displays that in RecycleViewer. Previously I use a listView where on LongClick I could delete an item like here LuckyNumbersApk/commit/4cec554359662d557626935046b8de68fb1b5c60
now I have switched to recyclerView I can't handle it properly. When I delete it, it disapears but when I reload the fragment the deleted entry reappears again. I assume it because the item is deleted only from the list in the adapter but how can I delete it from the list that is in the fragment that actually calls the recylerViewer?
This is my Adapter:
public class DatabaseAdapter extends RecyclerView.Adapter {
List dataModelArrayList;
Context context;
public DatabaseAdapter(List<DataModel> dataModelArrayList, Context context) {
this.dataModelArrayList = dataModelArrayList;
this.context = context;
}
class Myholder extends RecyclerView.ViewHolder implements CardView.OnLongClickListener {
TextView name, result;
public Myholder(View itemView) {
super(itemView);
name = (TextView) itemView.findViewById(R.id.card_name);
result = (TextView) itemView.findViewById(R.id.card_result);
CardView cardView = (CardView) itemView.findViewById(R.id.card_view);
cardView.setOnLongClickListener(this);
}
#Override
public boolean onLongClick(View v) {
new AlertDialog.Builder(context)
.setIcon(R.drawable.ic_warning_black_24dp)
.setTitle("Delete result")
.setMessage("Are you sure you want delete this result?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
/* This is where deletions should be handled */
int id = getAdapterPosition();
DataBHelper database = new DataBHelper(context);
database.deleteEntry(id);
dataModelArrayList.remove(id);
notifyItemRemoved(id);
notifyDataSetChanged();
database.close();
}
})
.setNegativeButton("No", null)
.show();
return true;
}
}
#Override
public Myholder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.row, null);
return new Myholder(view);
}
#Override
public void onBindViewHolder(Myholder holder, int position) {
DataModel dataModel = dataModelArrayList.get(position);
holder.name.setText(dataModel.getName());
holder.result.setText(dataModel.getResult());
}
#Override
public int getItemCount() {
return dataModelArrayList.size();
}}
This is DataBHelper:
public class DataBHelper extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 2;
public static final String DATABASE_NAME = "results_database";
public static final String RESULTS_TABLE_NAME = "results_table";
public static final String RESULTS_COLUMN_ID = "_id";
public static final String RESULTS_COLUMN_NAME = "name";
public static final String RESULTS_COLUMN_RESULT = "result";
public DataBHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
sqLiteDatabase.execSQL("CREATE TABLE " + RESULTS_TABLE_NAME + " (" +
RESULTS_COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
RESULTS_COLUMN_NAME + " TEXT, " +
RESULTS_COLUMN_RESULT + " TEXT" + ")");
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + RESULTS_TABLE_NAME);
onCreate(sqLiteDatabase);
}
public void saveToDB(String fname, String lname, String result) {
SQLiteDatabase database = getWritableDatabase();
ContentValues values = new ContentValues();
String name = fname + " " + lname;
values.put(DataBHelper.RESULTS_COLUMN_NAME, name);
values.put(DataBHelper.RESULTS_COLUMN_RESULT, result);
database.insert(DataBHelper.RESULTS_TABLE_NAME, null, values);
database.close();
}
public List<DataModel> readDB(){
List<DataModel> data=new ArrayList<>();
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery("select * from "+RESULTS_TABLE_NAME+" ;",null);
StringBuffer stringBuffer = new StringBuffer();
DataModel dataModel = null;
while (cursor.moveToNext()) {
dataModel= new DataModel();
String name = cursor.getString(cursor.getColumnIndexOrThrow("name"));
String result = cursor.getString(cursor.getColumnIndexOrThrow("result"));
dataModel.setName(name);
dataModel.setResult(result);
stringBuffer.append(dataModel);
data.add(dataModel);
}
return data;
}
public void clearDatabase() {
SQLiteDatabase sqLiteDatabase = getWritableDatabase();
String clearDBQuery = "DELETE FROM "+RESULTS_TABLE_NAME;
sqLiteDatabase.execSQL(clearDBQuery);
}
public void deleteEntry(long row) {
SQLiteDatabase sqLiteDatabase = getWritableDatabase();
sqLiteDatabase.delete(RESULTS_TABLE_NAME, RESULTS_COLUMN_ID + "=" + row, null);
}}
And this is the fragment which loads recyclerViewer
public class ResultsFragment extends Fragment {
DataBHelper database;
RecyclerView recyclerView;
DatabaseAdapter recycler;
public List<DataModel> datamodel;
#Override
public View onCreateView(LayoutInflater inflater, final ViewGroup container,
Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.fragment_results,
container, false);
datamodel =new ArrayList<DataModel>();
recyclerView = (RecyclerView) view.findViewById(R.id.app_recycle_view);
database = new DataBHelper(getActivity());
datamodel = database.readDB();
recycler = new DatabaseAdapter(datamodel, getActivity());
RecyclerView.LayoutManager reLayoutManager =new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(reLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(recycler);
ImageView imageView = (ImageView) view.findViewById(R.id.imageView);
if (datamodel.isEmpty()) {
recyclerView.setVisibility(View.GONE);
imageView.setVisibility(View.VISIBLE);
}
else {
recyclerView.setVisibility(View.VISIBLE);
imageView.setVisibility(View.GONE);
}
return view;
}}
In onCreateViwHolder:
#Override
public void onBindViewHolder(Myholder holder, int position) {
DataModel dataModel = dataModelArrayList.get(position);
holder.name.setText(dataModel.getName());
holder.result.setText(dataModel.getResult());
holder.id = dataModel.getId();
}
Add long id; into the ViewHolder, so your onClick you can delete the int id = getAdapterPosition(); and the id will be the id from the model.
To remove still use the adapter position:
dataModelArrayList.remove(getAdapterPosition());
notifyItemRemoved(getAdapterPosition());

By long clicking on listview delete its contents from SQLite and listview that is clicked

Can anyone show me how to delete contents from an SQLite database and listview by long clicking on it? Also, do I have to delete only contents from SQLite database or from both SQLite database and listview?
Here are my project classes:
Database Helper
public class DatabaseHelper extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 3;
private static final String DATABASE_NAME = "products.db";
private static final String TABLE_NAME = "products";
private static final String COLUMN_ID = "_id";
private static final String MARKET = "market";
private static final String PRODUCT = "product";
private SQLiteDatabase db;
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + TABLE_NAME + "("
+ COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ MARKET + " TEXT, "
+ PRODUCT + " TEXT)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME + "");
onCreate(db);
}
public Cursor getRecords() {
db = getReadableDatabase();
return db.rawQuery(
"SELECT * FROM " + TABLE_NAME,
null);
}
public void addRecords(String market, String product) {
db = getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(MARKET, market);
contentValues.put(PRODUCT, product);
db.insert(TABLE_NAME, null, contentValues);
db.close();
}
public void deleteRecords(int id){
}}
MainActivity
public class MainActivity extends AppCompatActivity {
ListView lv;
DatabaseHelper databaseHelper;
ShoppingCartAdapter shoppingCartAdapter;
private static final int TIME_ENTRY_REQUEST_CODE = 1;
Cursor cursor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv = (ListView) findViewById(R.id.list_view_main);
databaseHelper = new DatabaseHelper(this);
ListView listView = (ListView) findViewById(R.id.list_view_main);
shoppingCartAdapter = new ShoppingCartAdapter(this, databaseHelper.getRecords(), CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
listView.setAdapter(shoppingCartAdapter);
lv.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(final AdapterView<?> parent, View view, int position, long id) {
final int pos = position;
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Are you sure you want to delete?");
builder.setPositiveButton("DELETE", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
builder.setNegativeButton("CANCEL", null);
builder.show();
return true;
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.menu_template, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.menu_add_id) {
Intent intent = new Intent(this, AddContentActivity.class);
startActivityForResult(intent, TIME_ENTRY_REQUEST_CODE);
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == TIME_ENTRY_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
String market = data.getStringExtra("market");
String product = data.getStringExtra("product");
databaseHelper.addRecords(market, product);
shoppingCartAdapter.changeCursor(databaseHelper.getRecords());
}
}
}
}
AddContentActivity
public class AddContentActivity extends AppCompatActivity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_addcontent);
}
public void onAddButton(View view){
Intent intent = getIntent();
EditText marketet = (EditText) findViewById(R.id.marketet_id);
EditText productet = (EditText) findViewById(R.id.productet_id);
intent.putExtra("market", marketet.getText().toString());
intent.putExtra("product", productet.getText().toString());
this.setResult(RESULT_OK, intent);
finish();
}
}
ShoppingCartAdapter
public class ShoppingCartAdapter extends CursorAdapter{
public ShoppingCartAdapter(Context context, Cursor cursor, int flags){
super(context, cursor, flags);
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
TextView marketTv = (TextView) view.findViewById(R.id.markettv_id);
TextView productTv = (TextView) view.findViewById(R.id.producttv_id);
marketTv.setText(cursor.getString(1));
productTv.setText(cursor.getString(2));
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View view = inflater.inflate(R.layout.list_view_template, parent, false);
return view;
}
}
After couple of days I found solution on my question.If there is better way of doing delete, please post answer.
I added following lines of code:
Main Activity
Cursor cursor = (Cursor) parent.getItemAtPosition(pos);
final int item_id = cursor.getInt(cursor.getColumnIndex("_id"));
databaseHelper.deleteRecords(item_id );
cursor.requery();
DatabaseHelper
public void deleteRecords(int id){
db.delete(TABLE_NAME, COLUMN_ID + "=" + id, null);
}
EDIT:
replaced cursor.requery(); with
shoppingCartAdapter.changeCursor(databaseHelper.getRecords());
because using requery(); is deprecated but both lines of code work.

onItemClick in list doesnot open selected item in viewpager

onItemClick doesnot open selected item in viewpager
I have a list view which is populated using a sqlite db with a helperclass
when we click on a item in listview it should open the viewpager class and we can swipe through various details
the viewpager opens but always starts from the first list item
even though I have set the
Bundle b = getIntent().getExtras();
int index = b.getInt("position");
mViewPager.setCurrentItem(index);
I want to open the viewpager with the item that I have selected and not start from the first entry each time.
here is the listactivity
public class MyActivity extends Activity {
private CustomCursorAdapter customAdapter;
private PersonDatabaseHelper databaseHelper;
private static final int ENTER_DATA_REQUEST_CODE = 1;
private ListView listView;
private static final String TAG = MyActivity.class.getSimpleName();
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
databaseHelper = new PersonDatabaseHelper(this);
listView = (ListView) findViewById(R.id.list_data);
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Log.d(TAG, "clicked on item: " + position);
Toast.makeText(getApplicationContext(), "aa" + position,
Toast.LENGTH_LONG).show();
//startActivity(new Intent(getApplicationContext(), viepagerActivity.class));
Intent i = new Intent(MyActivity.this, viepagerActivity.class);
i.putExtra("position", position);
MyActivity.this.startActivity(i);
}
});
new Handler().post(new Runnable() {
#Override
public void run() {
customAdapter = new CustomCursorAdapter(MyActivity.this,
databaseHelper.getAllData());
listView.setAdapter(customAdapter);
}
});
}
public void onClickEnterData(View btnAdd) {
startActivityForResult(new Intent(this, EnterDataActivity.class),
ENTER_DATA_REQUEST_CODE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == ENTER_DATA_REQUEST_CODE && resultCode == RESULT_OK) {
databaseHelper.insertData(
data.getExtras().getString("tag_person_name"), data
.getExtras().getString("tag_person_pin"));
customAdapter.changeCursor(databaseHelper.getAllData());
}
}
}
adapter
public class CustomCursorAdapter extends CursorAdapter {
public CustomCursorAdapter(Context context, Cursor c) {
super(context, c);
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
// when the view will be created for first time,
// we need to tell the adapters, how each item will look
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View retView = inflater
.inflate(R.layout.single_row_item, parent, false);
return retView;
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
// here we are setting our data
// that means, take the data from the cursor and put it in views
TextView textViewPersonName = (TextView) view
.findViewById(R.id.tv_person_name);
textViewPersonName.setText(cursor.getString(cursor
.getColumnIndex(cursor.getColumnName(1))));
TextView textViewPersonPIN = (TextView) view
.findViewById(R.id.tv_person_pin);
textViewPersonPIN.setText(cursor.getString(cursor.getColumnIndex(cursor
.getColumnName(2))));
}
}
The viewpager
public class viepagerActivity extends Activity {
private List<String> testContactName = new ArrayList<String>();
private List<String> testContactNumber = new ArrayList<String>();
MyAdapter mAdapter;
private PersonDatabaseHelper databaseHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main1);
databaseHelper = new PersonDatabaseHelper(this);
ViewPager mViewPager = (ViewPager) findViewById(R.id.pager);
mAdapter = new MyAdapter();
mViewPager.setAdapter(mAdapter);
Bundle b = getIntent().getExtras();
int index = b.getInt("position");
mViewPager.setCurrentItem(index);
Toast.makeText(getApplicationContext(), "viepager" + index, Toast.LENGTH_LONG)
.show();
try {
getAllContacts();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void getAllContacts() {
SQLiteDatabase db = databaseHelper.database;
String[] columns = { PersonDatabaseHelper.PERSON_TABLE_COLUMN_ID,
PersonDatabaseHelper.PERSON_TABLE_COLUMN_NAME,
PersonDatabaseHelper.PERSON_TABLE_COLUMN_PIN, };
Cursor cursor = db.query(PersonDatabaseHelper.TABLE_NAME, columns,
null, null, null, null, null, null);
while (cursor.moveToNext()) {
String name = cursor.getString(cursor.getColumnIndex(cursor
.getColumnName(1)));
String phoneNumber = cursor.getString(cursor.getColumnIndex(cursor
.getColumnName(2)));
testContactName.add(name);
mAdapter.notifyDataSetChanged();
testContactNumber.add(phoneNumber);
mAdapter.notifyDataSetChanged();
}
cursor.close();
}
private class MyAdapter extends PagerAdapter {
public MyAdapter() {
super();
}
#Override
public int getCount() {
return testContactName.size();
}
#Override
public boolean isViewFromObject(View collection, Object object) {
return collection == ((View) object);
}
#Override
public Object instantiateItem(View collection, int position) {
Bundle b = getIntent().getExtras();
LayoutInflater inflater = (LayoutInflater) collection.getContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.viewpager_items, null);
TextView contactName = (TextView) view.findViewById(R.id.labelText);
TextView contactNumber = (TextView) view
.findViewById(R.id.answerText);
try {
contactName.setText(testContactName.get(position));
contactNumber.setText(testContactNumber.get(position));
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
((ViewPager) collection).addView(view, 0);
return view;
}
#Override
public void destroyItem(View collection, int position, Object view) {
((ViewPager) collection).removeView((View) view);
mAdapter.notifyDataSetChanged();
}
}
}
the helper class
public class PersonDatabaseHelper {
public static final String TAG = PersonDatabaseHelper.class
.getSimpleName();
// database configuration
// if you want the onUpgrade to run then change the database_version
public static final int DATABASE_VERSION = 1;
public static final String DATABASE_NAME = "mydatabase.db";
// table configuration
public static final String TABLE_NAME = "person_table"; // Table name
public static final String PERSON_TABLE_COLUMN_ID = "_id"; // a column
// named "_id"
// is required
// for cursor
public static final String PERSON_TABLE_COLUMN_NAME = "person_name";
public static final String PERSON_TABLE_COLUMN_PIN = "person_pin";
public DatabaseOpenHelper openHelper;
public SQLiteDatabase database;
// this is a wrapper class. that means, from outside world, anyone will
// communicate with PersonDatabaseHelper,
// but under the hood actually DatabaseOpenHelper class will perform
// database CRUD operations
public PersonDatabaseHelper(Context aContext) {
openHelper = new DatabaseOpenHelper(aContext);
database = openHelper.getWritableDatabase();
}
public void insertData(String aPersonName, String aPersonPin) {
// we are using ContentValues to avoid sql format errors
ContentValues contentValues = new ContentValues();
contentValues.put(PERSON_TABLE_COLUMN_NAME, aPersonName);
contentValues.put(PERSON_TABLE_COLUMN_PIN, aPersonPin);
database.insert(TABLE_NAME, null, contentValues);
}
public Cursor getAllData() {
String buildSQL = "SELECT * FROM " + TABLE_NAME;
Log.d(TAG, "getAllData SQL: " + buildSQL);
return database.rawQuery(buildSQL, null);
}
// this DatabaseOpenHelper class will actually be used to perform database
// related operation
private class DatabaseOpenHelper extends SQLiteOpenHelper {
public DatabaseOpenHelper(Context aContext) {
super(aContext, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
// Create your tables here
String buildSQL = "CREATE TABLE " + TABLE_NAME + "( "
+ PERSON_TABLE_COLUMN_ID + " INTEGER PRIMARY KEY, "
+ PERSON_TABLE_COLUMN_NAME + " TEXT, "
+ PERSON_TABLE_COLUMN_PIN + " TEXT )";
Log.d(TAG, "onCreate SQL: " + buildSQL);
sqLiteDatabase.execSQL(buildSQL);
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int oldVersion,
int newVersion) {
// Database schema upgrade code goes here
String buildSQL = "DROP TABLE IF EXISTS " + TABLE_NAME;
Log.d(TAG, "onUpgrade SQL: " + buildSQL);
sqLiteDatabase.execSQL(buildSQL); // drop previous table
onCreate(sqLiteDatabase); // create the table from the beginning
}
}
}

how to display data from sqlite in custom listfragment

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,.

Categories

Resources