Android Trouble saving text from Edit Text View to database - android

In my application, I am allowing user to send a alert message to some numbers. User can write any text of his own choice in the EditText or he can select a text from the pre-defined text from the spinner. Earlier I was saving the text to the SharedPreferences but now I want it to be in SQLite.I am able to save the contact numbers to the database for which user wants to send the message but I am having trouble in saving the message to database. I want that when user entered his own text or selected any text from the spinner after that he press save button and the text is saved to database.Please Help.
P.S _ I think am having trouble in calling method from database to button onclick.
Please have a look on my code and suggest me what to do.
MainActivity.java
public class MainActivity extends Activity implements LocationListener {
String separator = "; ";
private Button btn_cntct;
private EditText message;
LinearLayout linearLayoutSec;
private Button GPSState;
Button b_alert;
Button b_save_message;
public int REQUESTCODE = 1;
int temp;
ScrollView ScrView;
Context c = MainActivity.this;
Button AlertMessages;
private static ArrayList<ContactItems> selectedContactList = new ArrayList<ContactItems>();
static CustomAdapter adapter;
public static String[] myvalue = new String[1];
Spinner spinner;
static String[] alert = { " ", "I am in danger", "Help Me", "Watch Out",
"Look For Me", "Cover ME" };
MySQLiteHelper dbHelper;
String savedMessage;
Button save;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
message = (EditText) findViewById(R.id.et_message);
// message.setFocusable(false);
dbHelper = new MySQLiteHelper(this);
String dis = dbHelper.getMsg();
if (dis != null) {
message.setText(dis);
}
bsave = (Button) findViewById(R.id.b_save);
bsave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String str = message.getText().toString();
dbHelper.updateMsg(str);
}
});
spinner = (Spinner) findViewById(R.id.Spin_alert_message);
ArrayAdapter<String> adp = new ArrayAdapter<String>(
getApplicationContext(), android.R.layout.simple_spinner_item,
alert);
spinner.setAdapter(adp);
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int position, long id) {
String selectedItem = alert[position];
message.setText(selectedItem);
// loads the text that has been stored to SP and set it to
// EditText
//message.setText(pref.getString("AutoSave", ""));
// to bring cursor to front
message.setSelection(message.getText().length());
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
/************************** saving custom message *****************************/
// for saving text that user can change as per need
ListView contactlist = (ListView) findViewById(R.id.contactListitems);
Resources res = getResources();
adapter = new CustomAdapter(MainActivity.this, selectedContactList, res,MainActivity.this);
contactlist.setAdapter(adapter);
/********************************* GPS *******************************/
// checking if GPS is already on or not.
// If not then displaying the alert dialog
// requesting user to On GPS.
GPSState = (Button) findViewById(R.id.bGPSstate);
boolean isGPSEnabled = false; //
// Declaring a Location Manager
LocationManager locationManager;
locationManager = (LocationManager) getApplicationContext()
.getSystemService(LOCATION_SERVICE);
// getting GPS status
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
if (!isGPSEnabled) {
// no GPS provider is enabled
// displaying GPS status on the button and and opening GPS settings
GPSState.setText("GPS is off.turn it on");
GPSState.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
startActivityForResult(
new Intent(
android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS),
REQUESTCODE);
}
});
// setting up the dialog box for GPS Settings
// creating alertdialog
AlertDialog.Builder builder = new AlertDialog.Builder(c);
builder.setTitle("Settings");
builder.setMessage("Enable GPS for the Application");
builder.setPositiveButton("GPS Setting",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
startActivity(new Intent(
android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));
dialog.dismiss();
}
});
builder.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
new AlertDialog.Builder(MainActivity.this)
.setTitle("How to use Application")
.setMessage(
"You must enable the GPS in order to use this application. Press Activate and then press Power Button twice in order to send the alert message to the selected contacts")
.setNeutralButton(
"OK",
new DialogInterface.OnClickListener() {
#Override
public void onClick(
DialogInterface dialog,
int which) {
// do something // for //
// returning back to // //
// application
dialog.cancel();
}
}).show();
dialog.dismiss();
}
});
builder.show();
} else {
GPSState.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
startActivityForResult(
new Intent(
android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS),
REQUESTCODE);
}
});
}
// defining button elements for picking contacts from phone-book
btn_cntct = (Button) findViewById(R.id.bpickperson);
btn_cntct.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
if (selectedContactList.size() < 4) {
// TODO Auto-generated method stub
// using Intent for fetching contacts from phone-book
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE);
startActivityForResult(intent, REQUESTCODE);
} else {
// print toast for not allowing user to add more contacts
Toast.makeText(getApplicationContext(),
"You Can Only Add 4 Contacts ", Toast.LENGTH_SHORT)
.show();
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
// calling onActivityResult when contacts has been selected from the
// phone-book, giving back the REQUESTCODE i started it with, the RC it
// returned with
// any additional data from it.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
boolean isGPSEnabled = false;
GPSState = (Button) findViewById(R.id.bGPSstate);
LocationManager locationManager;
locationManager = (LocationManager) getApplicationContext()
.getSystemService(LOCATION_SERVICE);
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
if (!isGPSEnabled)
GPSState.setText("GPS is off.Turn it on");
else
GPSState.setText("GPS is on");
if (data != null) {
Uri uri = data.getData();
Log.i("data", uri.toString());
if (uri != null) {
Cursor c = null;
try {
c = getContentResolver()
.query(uri,
new String[] {
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Phone.NUMBER,
ContactsContract.CommonDataKinds.Phone.TYPE },
null, null, null);
if (c != null && c.moveToFirst()) {
final ContactItems item = new ContactItems(
c.getString(0), c.getString(1), c.getInt(2));
item.setName(c.getString(0));
item.setNumber(c.getString(1));
item.setType(c.getInt(2));
selectedContactList.add(item);
Set<ContactItems> s = new TreeSet<ContactItems>(
new Comparator<ContactItems>() {
#Override
public int compare(ContactItems o1,
ContactItems o2) {
// for preventing duplicacy of contacts
// and calling toast
if (o1.number.equals(o2.number)) {
Toast.makeText(
getApplicationContext(),
"Selected Number Already Exists",
Toast.LENGTH_SHORT).show();
} else {
}
return o1.getNumber().compareTo(
o2.getNumber());
}
});
s.addAll(selectedContactList);
selectedContactList.clear();
selectedContactList.addAll(s);
adapter.notifyDataSetChanged();
// save the task list to preference
dbHelper.insertContact(item);
}
} finally {
if (c != null) {
c.close();
}
}
}
}
}
#Override
public void onLocationChanged(Location arg0) {
// TODO Auto-generated method stub
}
#Override
public void onProviderDisabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
// TODO Auto-generated method stub
}
/*
* #Override public void onSaveInstanceState(Bundle outState) {
* super.onSaveInstanceState(outState); // You put the content of your list,
* which is this.mCachedData, in the // state
* outState.putParcelableArrayList("ABC", selectedContactList); }
*/
#Override
public void onResume() {
super.onResume();
boolean isGPSEnabled = false;
GPSState = (Button) findViewById(R.id.bGPSstate);
LocationManager locationManager;
locationManager = (LocationManager) getApplicationContext()
.getSystemService(LOCATION_SERVICE);
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
if (!isGPSEnabled)
GPSState.setText("GPS is off.Turn it on");
else
GPSState.setText("GPS is on");
}
}// final parentheses
MySQLiteHelper.java
public class MySQLiteHelper extends SQLiteOpenHelper {
public static final String TABLE_NAME = "userdetails";
public static final String TABLE_NAME_MSG = "usermessage";
public static final String COLUMN_ID = "_id";
public static final String COLUMN_NUMBER = "NUMBER";
public static final String COLUMN_NAME = "name";
public static final String COLUMN_TYPE = "type";
public static final String COLUMN_ID_MSG = "_id";
public static final String COLUMN_MSG = "message";
private static final String DATABASE_NAME = "userInformation.db";
private static final int DATABASE_VERSION = 1;
private static final String LOG = "DatabaseHelper";
// Database creation sql statement
private static final String DATABASE_CREATE_TABLE_CONTACTS = "create table "
+ TABLE_NAME + "(" + COLUMN_ID
+ " integer primary key autoincrement, " + COLUMN_NAME
+ " text not null,"+COLUMN_NUMBER+" text not null,"+COLUMN_TYPE+" text not null);";
private static final String DATABASE_CREATE_TABLE_MSG = "create table "
+ TABLE_NAME_MSG + "(" + COLUMN_ID_MSG
+ " integer primary key autoincrement, " + COLUMN_MSG + " text not null);";
private static final String DATABASE_INSERT_MSG = "insert into "
+ TABLE_NAME_MSG + "(" + COLUMN_MSG+") VALUES('enter your message');";
public MySQLiteHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase database) {
database.execSQL(DATABASE_CREATE_TABLE_CONTACTS);
database.execSQL(DATABASE_CREATE_TABLE_MSG);
database.execSQL(DATABASE_INSERT_MSG);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(MySQLiteHelper.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);
}
public long insertContact(ContactItems contItem) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COLUMN_NAME, contItem.getName());
values.put(COLUMN_NUMBER, contItem.getNumber());
values.put(COLUMN_TYPE, contItem.getType());
// insert row
long result = db.insert(TABLE_NAME, null, values);
// assigning tags to todo
/*for (long tag_id : tag_ids) {
createTodoTag(todo_id, tag_id);
}*/
return result;
}
public ArrayList<ContactItems> getAllContacts() {
ArrayList<ContactItems> contactList = new ArrayList<ContactItems>();
String selectQuery = "SELECT * FROM " + TABLE_NAME;
Log.e(LOG, selectQuery);
SQLiteDatabase db = this.getReadableDatabase();
Cursor c = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (c.moveToFirst()) {
do {
ContactItems conItems = new ContactItems();
conItems.setName(c.getString((c.getColumnIndex(COLUMN_NAME))));
conItems.setNumber((c.getString(c.getColumnIndex(COLUMN_NUMBER))));
conItems.setType(Integer.parseInt(c.getString(c.getColumnIndex(COLUMN_TYPE))));
// adding to todo list
contactList.add(conItems);
} while (c.moveToNext());
}
return contactList;
}
public void updateMsg(String msg) {
// TODO Auto-generated method stub
// String selectQuery = "update " + TABLE_NAME_MSG+" set "+COLUMN_MSG+" = '"+msg+"' where "+COLUMN_ID_MSG+" = 1";
ContentValues values = new ContentValues();
values.put(COLUMN_MSG, msg);
SQLiteDatabase db = this.getReadableDatabase();
db.update(TABLE_NAME_MSG, values, null, null);
}
public String getMsg() {
String message ="";
String selectQuery = "SELECT * FROM " + TABLE_NAME_MSG;
SQLiteDatabase db = this.getReadableDatabase();
Cursor c = db.rawQuery(selectQuery, null);
if (c.moveToFirst()) {
do {
message = c.getString(c.getColumnIndex(COLUMN_MSG));
} while (c.moveToNext());
}
// TODO Auto-generated method stub
Log.e(LOG, "message = "+message);
return message;
}
public int removeData(String number) {
// TODO Auto-generated method stub
SQLiteDatabase db = this.getReadableDatabase();
//db.drawQuery(deleteQuery, null);
return db.delete(TABLE_NAME, COLUMN_NUMBER + "='" + number+"'", null) ;
}
}
CustomAdapter.java
public class CustomAdapter extends BaseAdapter {
/*********** Declare Used Variables *********/
private Activity activity;
private ArrayList<ContactItems> data;
private static LayoutInflater inflater = null;
public Resources res;
MySQLiteHelper dbHelper;
// ListModel tempValues=null;
int i = 0;
String selectedNum = " ";
Context contxt;
/************* CustomAdapter Constructor *****************/
public CustomAdapter(Activity a, ArrayList<ContactItems> d,
Resources resLocal,Context context) {
/********** Take passed values **********/
activity = a;
data = d;
res = resLocal;
contxt= context;
dbHelper= new MySQLiteHelper(contxt);
/*********** Layout inflator to call external xml layout () ***********/
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
/******** What is the size of Passed Arraylist Size ************/
public int getCount() {
if (data.size() <= 0)
return 1;
return data.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
/********* Create a holder Class to contain inflated xml file elements *********/
public static class ViewHolder {
public TextView text;
public TextView textNumber;
public ImageView image;
}
/****** Depends upon data size called for each row , Create each ListView row *****/
#SuppressLint("DefaultLocale")
public View getView(int position, View convertView, ViewGroup parent) {
final int pos = position;
View vi = convertView;
ViewHolder holder;
// check if converView is null, if it is null it probably means
if (convertView == null) {
/****** Inflate tabitem.xml file for each row ( Defined below ) *******/
vi = inflater.inflate(R.layout.contactlistitem, null);
/****** View Holder Object to contain tabitem.xml file elements ******/
// if it is not null, just reuse it from the recycler
holder = new ViewHolder();
holder.text = (TextView) vi.findViewById(R.id.contactname);
holder.textNumber = (TextView) vi.findViewById(R.id.contactnumber);
holder.image = (ImageView) vi.findViewById(R.id.deleteimage);
/************ Set holder with LayoutInflater ************/
vi.setTag(holder);
} else
holder = (ViewHolder) vi.getTag();
if (data.size() <= 0) {
holder.text.setText("Add");
holder.textNumber.setText(" ");
holder.image.setVisibility(View.GONE);
} else {
/***** Get each Model object from Arraylist ********/
/************ Set Model values in Holder elements ***********/
holder.text.setText("" + data.get(position).getName());
holder.textNumber.setText("" + data.get(position).getNumber());
holder.image.setVisibility(View.VISIBLE);
holder.image.setImageResource(res.getIdentifier("delete_button",
null, null));
holder.image.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder build = new AlertDialog.Builder(
activity);
build.setTitle("Delete");
build.setMessage("Are You Sure");
build.setPositiveButton("Delete",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
// TODO Auto-generated method stub
dbHelper.removeData(data.get(pos).getNumber());
data.remove(pos);
MainActivity.adapter.notifyDataSetChanged();
dialog.dismiss();
}
});
/*
* data.remove(pos);
* MainActivity.adapter.notifyDataSetChanged();
*/
build.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
// TODO Auto-generated method stub
dialog.dismiss();
}
});
build.show();
}
});
/******** Set Item Click Listner for LayoutInflater for each row *******/
}
// return the view for a single item in the listview
return vi;
}
}
ContactItems.java
public class ContactItems implements Parcelable {
String name = "";
String number = "";
int type = 0;
public ContactItems(String name, String number, int type) {
super();
this.name = name;
this.number = number;
this.type = type;
}
public ContactItems(Parcel source) {
// TODO Auto-generated constructor stub
this.name = source.readString();
this.number = source.readString();
this.type = source.readInt();
}
public ContactItems() {
// TODO Auto-generated constructor stub
super();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
#Override
public int describeContents() {
// TODO Auto-generated method stub
return 0;
}
public static final Parcelable.Creator<ContactItems> CREATOR = new Parcelable.Creator<ContactItems>() {
#Override
public ContactItems createFromParcel(Parcel source) {
return new ContactItems(source);
}
#Override
public ContactItems[] newArray(int size) {
return new ContactItems[size];
}
};
#Override
public void writeToParcel(Parcel dest, int flags) {
// TODO Auto-generated method stub
dest.writeString(name);
dest.writeString(number);
dest.writeInt(type);
}

Simply call the method for inserting or updating the message into database in your button's click and before calling that method just get the value of EditText into some variable and pass that variable as parameter for inserting into database.
Try out as below:
save.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
String str = message.getText().toString();
dbHelper.updateMsg(str);
}
});
EDITED:
public boolean updateMsg(String msg) {
ContentValues values = new ContentValues();
values.put(COLUMN_MSG, msg);
SQLiteDatabase db = this.getReadableDatabase();
return db.update(TABLE_NAME_MSG, values, COLUMN_ID_MSG +"=1"+, null)>0;
}

Related

Update textview data sqlite Android

I have a textview that gets data from sqlite database but when I delete a row,or change it ,I also want to change what the textview has,the data the textview contains is basically the sum of all rows specific column,so how can I update the textview when updating sqlite data?
here is my main code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_logged_in);
getSupportActionBar().hide();
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
tinyDB = new TinyDB(getApplicationContext());
listView = findViewById(R.id.listt);
pharmacynme = findViewById(R.id.pharmacynme);
constraintLayout = findViewById(R.id.thelayout);
mBottomSheetDialog2 = new Dialog(LoggedIn.this, R.style.MaterialDialogSheet);
inflater2 = (LayoutInflater) LoggedIn.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mBottomSheetDialog = new Dialog(LoggedIn.this, R.style.MaterialDialogSheet);
content = inflater2.inflate(R.layout.activity_main2, null);
content2 = inflater2.inflate(R.layout.smalldialog, null);
total = (TextView) content2.findViewById(R.id.totalpriceofsmalldialog);
pharmacydescrr = findViewById(R.id.pharmacydiscribtion);
String nme = getIntent().getStringExtra("pharmacy_name");
String diskr = getIntent().getStringExtra("pharmacy_disk");
pharmacydescrr.setText(diskr);
pharmacynme.setText(nme);
//Listview Declaration
connectionClass = new ConnectionClass();
itemArrayList = new ArrayList<ClassListItems>();// Connection Class Initialization
etSearch = findViewById(R.id.etsearch);
etSearch.setSingleLine(true);
chat = findViewById(R.id.chat);
mDatabaseHelper = new DatabaseHelper(this);
mBottomSheetDialog2.setContentView(content2);
mBottomSheetDialog2.setCancelable(false);
mBottomSheetDialog2.getWindow().setLayout(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
mBottomSheetDialog2.getWindow().setGravity(Gravity.BOTTOM);
mBottomSheetDialog2.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
mBottomSheetDialog2.getWindow().setFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL,
WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL);
System.out.println("IDKSDKASDJKAS"+mDatabaseHelper.ifExists());
if (mDatabaseHelper.ifExists()){
mBottomSheetDialog2.show();
total.setText(mDatabaseHelper.getPriceSum());
}else {
}
chat.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String nameid = getIntent().getStringExtra("nameid");
Intent intent = new Intent(LoggedIn.this,ChatActivity.class);
intent.putExtra("nameid",nameid);
startActivity(intent);
}
});
etSearch.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
String text = etSearch.getText().toString().toLowerCase(Locale.getDefault());
// myAppAdapter.filter(text);
}
});
SyncData orderData = new SyncData();
orderData.execute("");
}
public void AddData(String newEntry,String price,String amount){
boolean insertData = mDatabaseHelper.addData(newEntry,price,amount);
if (insertData){
toastMessage("Data Successfully inserted!");
}else {
toastMessage("Al anta 4abebto da ya youssef >:(");
}
}
private void toastMessage(String message){
Toast.makeText(this,message,Toast.LENGTH_LONG).show();
}
private class SyncData extends AsyncTask<String, String, String> {
String msg;
ProgressDialog progress;
#Override
protected void onPreExecute() //Starts the progress dailog
{
progress = ProgressDialog.show(LoggedIn.this, "Loading...",
"Please Wait...", true);
}
#Override
protected String doInBackground(String... strings) // Connect to the database, write query and add items to array list
{
runOnUiThread(new Runnable() {
public void run() {
try {
Connection conn = connectionClass.CONN(); //Connection Object
if (conn == null) {
success = false;
msg = "Sorry something went wrong,Please check your internet connection";
} else {
// Change below query according to your own database.
String nme = getIntent().getStringExtra("pharmacy_name");
System.out.println(nme);
String query = "Select StoreArabicName,StoreEnglishName,StoreSpecialty,StoreCountry,StoreLatitude,StoreLongitude,Store_description,ProductData.ProductArabicName,ProductData.ProductImage,ProductData.ProductEnglishName,ProductData.ProductDescription,ProductData.ProductPrice FROM StoresData INNER JOIN ProductData ON StoresData.StoreID = ProductData.StoreID WHERE StoreEnglishName = '"+nme+"'";
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(query);
if (rs != null) // if resultset not null, I add items to itemArraylist using class created
{
while (rs.next()) {
try {
itemArrayList.add(new ClassListItems(rs.getString("ProductEnglishName"), rs.getString("ProductDescription"), rs.getString("ProductPrice"),rs.getString("ProductImage")));
System.out.println(rs.getString("ProductImage"));
} catch (Exception ex) {
ex.printStackTrace();
}
}
msg = "Found";
success = true;
} else {
msg = "No Data found!";
success = false;
}
}
} catch (Exception e) {
e.printStackTrace();
Writer writer = new StringWriter();
e.printStackTrace(new PrintWriter(writer));
msg = writer.toString();
Log.d("Error", writer.toString());
success = false;
}
}
});
return msg;
}
#Override
protected void onPostExecute(String msg) // disimissing progress dialoge, showing error and setting up my listview
{
progress.dismiss();
if (msg!=null){
Toast.makeText(LoggedIn.this, msg + "", Toast.LENGTH_LONG).show();
}
if (!success) {
} else {
try {
myAppAdapter = new MyAppAdapter(itemArrayList, LoggedIn.this);
listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
listView.setAdapter(myAppAdapter);
} catch (Exception ex) {
}
}
}
}
public class MyAppAdapter extends BaseAdapter//has a class viewholder which holds
{
private ArrayList<ClassListItems> mOriginalValues; // Original Values
private ArrayList<ClassListItems> mDisplayedValues;
public class ViewHolder {
TextView textName;
TextView textData;
TextView textImage;
ImageView producticon;
}
public List<ClassListItems> parkingList;
public Context context;
ArrayList<ClassListItems> arraylist;
private MyAppAdapter(List<ClassListItems> apps, Context context) {
this.parkingList = apps;
this.context = context;
arraylist = new ArrayList<ClassListItems>();
arraylist.addAll(parkingList);
}
#Override
public int getCount() {
return parkingList.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, final View convertView, ViewGroup parent) // inflating the layout and initializing widgets
{
View rowView = convertView;
ViewHolder viewHolder = null;
if (rowView == null) {
LayoutInflater inflater = getLayoutInflater();
rowView = inflater.inflate(R.layout.listcontent, parent, false);
viewHolder = new ViewHolder();
viewHolder.textName = rowView.findViewById(R.id.name);
viewHolder.textData = rowView.findViewById(R.id.details);
viewHolder.textImage = rowView.findViewById(R.id.sdadprice);
viewHolder.producticon = rowView.findViewById(R.id.producticon);
rowView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
// here setting up names and images
viewHolder.textName.setText(parkingList.get(position).getProname() + "");
viewHolder.textData.setText(parkingList.get(position).getData());
viewHolder.textImage.setText(parkingList.get(position).getImage());
Picasso.with(context).load(parkingList.get(position).getProducticon()).into(viewHolder.producticon);
mBottomSheetDialog.setCancelable(true);
mBottomSheetDialog.getWindow().setLayout(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
mBottomSheetDialog.getWindow().setGravity(Gravity.BOTTOM);
mBottomSheetDialog.setContentView(content);
total.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(LoggedIn.this,Listitemsbought.class);
startActivity(intent);
}
});
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
//What happens when you click on a place!
// Intent intent = new Intent(LoggedIn.this,MapsActivity.class);
// startActivity(intent);
final int count = 0;
final Float allitemscount = Float.parseFloat(parkingList.get(position).getImage());
TextView textView = (TextView) content.findViewById(R.id.mebuyss);
final TextView itemcount = (TextView) content.findViewById(R.id.itemcount);
Button plus = (Button) content.findViewById(R.id.plus);
Button minus = (Button) content.findViewById(R.id.minus);
Button finish = (Button) content.findViewById(R.id.finishgettingitem);
textView.setText(parkingList.get(position).getProname());
plus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
counter = counter + 1;
itemcount.setText(String.valueOf(counter));
}
});
minus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
counter --;
if(counter<0){
counter=0;
}
itemcount.setText(String.valueOf(counter));
}
});
finish.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String get = itemcount.getText().toString();
Float last = Float.parseFloat(get) * Float.parseFloat(parkingList.get(position).getImage());
mBottomSheetDialog.dismiss();
AddData(parkingList.get(position).getProname(),String.valueOf(last),String.valueOf(counter));
total.setText(mDatabaseHelper.getPriceSum());
mBottomSheetDialog2.show();
doneonce = true;
}
});
// if (doneonce = true){
// Float priceofitem = parseFloat(parkingList.get(position).getImage());
// Float currentprice = parseFloat(total.getText().toString());
// Float finalfloat = priceofitem * currentprice;
// total.setText(String.valueOf(finalfloat));
//
// }
if (!mBottomSheetDialog.isShowing()){
counter = 1;
}
//
mBottomSheetDialog.show();
// if (tinyDB.getString("selecteditem").equals("English")){
// Toast.makeText(LoggedIn.this,"Sorry this ability isn't here yet",Toast.LENGTH_LONG).show();
// }else {
// Toast.makeText(LoggedIn.this,"عفوا هذه الخاصية ليست متوفرة حاليا",Toast.LENGTH_LONG).show();
// }
}
});
return rowView;
}
public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
itemArrayList.clear();
if (charText.length() == 0) {
itemArrayList.addAll(arraylist);
} else {
for (ClassListItems st : arraylist) {
if (st.getProname().toLowerCase(Locale.getDefault()).contains(charText)) {
itemArrayList.add(st);
}
}
}
notifyDataSetChanged();
}
}
private Float parseFloat(String s){
if(s == null || s.isEmpty())
return 0.0f;
else
return Float.parseFloat(s);
}
And here is my DatabaseHelper.java
public class DatabaseHelper extends SQLiteOpenHelper {
private static final String TAG = "DatabaseHelper";
private static final String TABLE_NAME = "DatabaseHelper";
private static final String NAME = "Name";
private static final String PRICE = "Price";
private static final String AMOUNT = "Amount";
public DatabaseHelper(Context context) {
super(context, TABLE_NAME, null , 4);
}
#Override
public void onCreate(SQLiteDatabase db) {
String createTable = "CREATE TABLE " + TABLE_NAME + " ("+PRICE+" TEXT, "+ NAME + " TEXT,"+ AMOUNT +" TEXT)";
db.execSQL(createTable);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS "+ TABLE_NAME);
onCreate(db);
}
public boolean addData(String item, String Price,String amount){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(PRICE,Price);
contentValues.put(NAME, item);
contentValues.put(AMOUNT, amount);
Log.d(TAG, "addData: Adding " + item + " to " + TABLE_NAME);
long insert = db.insert(TABLE_NAME,null,contentValues);
if (insert == -1){
return false;
}else {
return true;
}
}
public Cursor getDataOfTable(){
SQLiteDatabase db = this.getWritableDatabase();
String query = "SELECT Name,Amount FROM " + TABLE_NAME ;
Cursor data = db.rawQuery(query, null);
return data;
}
public String getPriceSum(){
SQLiteDatabase db = this.getWritableDatabase();
String query = "SELECT COALESCE(SUM(Price), 0) FROM " + TABLE_NAME;
Cursor price = db.rawQuery(query, null);
String result = "" + price.getString(0);
price.close();
db.close();
return result;
}
public boolean ifExists()
{
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = null;
String checkQuery = "SELECT * FROM " + TABLE_NAME + " LIMIT 1";
cursor= db.rawQuery(checkQuery,null);
boolean exists = (cursor.getCount() > 0);
cursor.close();
return exists;
}
public void delete(String nameofrow) {
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL("delete from "+TABLE_NAME+" where "+NAME+"='"+nameofrow+"'");
}
}
Any help?!
The method getPriceSum() should return the sum and not a Cursor:
public String getPriceSum(){
SQLiteDatabase db = this.getWritableDatabase();
String query = "SELECT COALESCE(SUM(Price), 0) FROM " + TABLE_NAME;
Cursor c = db.rawQuery(query, null);
String result = "";
if (c.moveToFirst()) result = "" + c.getString(0);
c.close();
db.close();
return result;
}
I don't think that you need the if block:
if (mDatabaseHelper.ifExists()) {
.......................
}
All you need to do is:
total.setText(mDatabaseHelper.getPriceSum());

Listview shows one item multiple times

I am trying to create a List for Android with a SQLite DB. While creating a new Item works without a problem, after it returns to the list activity, the Items are showed various times. Still in my DB only one new Item is inserted (as should), and when I restart the App and load the list, each Item is showed once. So here is my main activity, as I said DBHandler should be ok.
public class MainActivity extends Activity {
List<FavImages> FavImages = new ArrayList<FavImages>();
ListView favImageListView;
final Context context = this;
private SharedPreferences mPrefs;
private SharedPreferences.Editor mEditor;
//label logs
private static String logtag = "CameraApp";
//use main camera
private static int TAKE_PICTURE = 1;
private Uri imageUri;
public Uri imagePath = Uri.parse("android.resource://com.adrian/drawable/no_picture.png");
DataBaseHandler dbHandler;
int longClickedItemIndex;
ArrayAdapter<FavImages> favImagesAdapter;
private static final int EDIT = 0, DELETE = 1;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
favImageListView = (ListView) findViewById(R.id.listView);
dbHandler = new DataBaseHandler(getApplicationContext());
mPrefs = PreferenceManager.getDefaultSharedPreferences(context);
mEditor = mPrefs.edit();
//enter an Item
registerForContextMenu(favImageListView);
//maybe without long
favImageListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
//position of Item
longClickedItemIndex = position;
return false;
}
});
populateList();
//Button Action
Button cameraButton = (Button)findViewById(R.id.button_camera);
cameraButton.setOnClickListener(cameraListener);
}
private OnClickListener cameraListener = new OnClickListener(){
public void onClick(View v){
takePhoto(v);
}
};
//launch native camera app
private void takePhoto(View v){
final Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
//save Image and create file
// in Progress
LayoutInflater factory = LayoutInflater.from(this);
final View textEntryView = factory.inflate(R.layout.text_entry, null);
final EditText input1 = (EditText) textEntryView.findViewById(R.id.pictureName);
final AlertDialog.Builder alert = new AlertDialog.Builder(this);
//create Dialog
alert
.setTitle("Bitte bennenen Sie Ihr Bild!")
.setView(textEntryView)
.setPositiveButton(R.string.alert_dialog_ok,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
Log.i("AlertDialog","TextEntry 1 Entered "+input1.getText().toString());
/* User clicked OK so do some stuff */
String inputText = input1.getText().toString();
mEditor.putString("pictureName", inputText);
mEditor.commit();
File photo = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), replaceChars(mPrefs.getString("pictureName", "picture")) + ".jpg");
//access information of file
imageUri = Uri.fromFile(photo);
//save image path information
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
//for favImages
imagePath = imageUri;
mEditor.putString("picturePath", imagePath.toString());
mEditor.commit();
//
startActivityForResult(intent, TAKE_PICTURE);
//
Log.e("Dateipfad", imagePath.toString());
FavImages favImages = new FavImages(dbHandler.getFavCount(), mPrefs.getString("pictureName", "Bild"), imagePath);
dbHandler.createFav(favImages);
FavImages.add(favImages);
//favImagesAdapter.notifyDataSetChanged();
populateList();
List<FavImages> addableFavs = dbHandler.getAllFav();
int favCount = dbHandler.getFavCount();
for(int i = 0; i < favCount; i++){
FavImages.add(addableFavs.get(i));
}
if (!addableFavs.isEmpty())
populateList();
}
});
//show Dialog
alert.show();
}
public String replaceChars (String inputText){
inputText = inputText.replace("ä","ae");
inputText = inputText.replace("ö","oe");
inputText = inputText.replace("ü","ue");
inputText = inputText.replace("ß","ss");
return inputText;
}
//deal with output
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent){
super.onActivityResult(requestCode, resultCode, intent);
//user hits ok button (picture accepted)
if(resultCode == Activity.RESULT_OK){
Uri selectedImage = imageUri;
//communication between apps
getContentResolver().notifyChange(selectedImage, null);
/*get Image
ImageView imageView = (ImageView)findViewById(R.id.image_camera);
//hold Image data
ContentResolver cr = getContentResolver();
Bitmap bitmap;
//get bitmap data
try {
bitmap = MediaStore.Images.Media.getBitmap(cr, selectedImage);
//set Image
imageView.setImageBitmap(bitmap);
//notify user of success
Toast.makeText(MainActivity.this, selectedImage.toString(), Toast.LENGTH_LONG).show();
}catch (Exception e){ //catch exceptions along the way
Log.e(logtag, e.toString());
} */
}
}
//
public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo menuInfo){
super.onCreateContextMenu(menu, view, menuInfo);
menu.setHeaderTitle("Favorit bearbeiten");
menu.add(Menu.NONE, DELETE, menu.NONE, "Favorit löschen");
}
public boolean onContextItemSelected (MenuItem item){
switch (item.getItemId()){
case EDIT:
//TODO: edit Favorites
break;
case DELETE:
//
dbHandler.deleteFav(FavImages.get(longClickedItemIndex));
FavImages.remove(longClickedItemIndex);
favImagesAdapter.notifyDataSetChanged();
break;
}
return super.onContextItemSelected(item);
}
private void populateList(){
//ArrayAdapter<FavImages> adapter = new favImagesListAdapter();
//favImageListView.setAdapter(adapter);
favImagesAdapter = new favImagesListAdapter();
favImageListView.setAdapter(favImagesAdapter);
}
//Constructor for List Items
private class favImagesListAdapter extends ArrayAdapter<FavImages>{
public favImagesListAdapter(){
super (MainActivity.this, R.layout.listview_item, FavImages);
}
#Override
public View getView (int position, View view, ViewGroup parent){
if (view == null)
view = getLayoutInflater().inflate(R.layout.listview_item, parent, false);
FavImages currentFav = FavImages.get(position);
TextView favName = (TextView) view.findViewById(R.id.favName);
favName.setText(currentFav.getImageName());
ImageView ivFavsImage = (ImageView) view.findViewById(R.id.favImage);
ivFavsImage.setImageURI(currentFav.getImagePath());
return view;
}
}
So to sum it up, what am I doing wrong, that my Items are loaded various times.
EDIT:
as requested here is my DBHandler class:
<!-- language: lang-java -->
public class DataBaseHandler extends SQLiteOpenHelper{
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "favoritesManager",
TABLE_FAVS = "favorites",
KEY_ID = "id",
KEY_IMGName = "name",
KEY_IMGPATH = "imagePath";
//standard DB method
public DataBaseHandler(Context context){
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
//standard DB method
#Override
public void onCreate(SQLiteDatabase db){
db.execSQL("CREATE TABLE " + TABLE_FAVS + "(" + KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + KEY_IMGName + " TEXT, " + KEY_IMGPATH + " TEXT)");
}
//standard DB method
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion){
db.execSQL("DROP TABL IF EXISTS" + TABLE_FAVS);
onCreate(db);
}
public void createFav(FavImages favImages){
SQLiteDatabase db = getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_IMGName, favImages.getImageName());
values.put(KEY_IMGPATH, favImages.getImagePath().toString());
db.insert(TABLE_FAVS, null, values);
db.close();
}
public void deleteFav(FavImages favImages){
SQLiteDatabase db = getWritableDatabase();
db.delete(TABLE_FAVS, KEY_ID + "=?", new String[]{String.valueOf(favImages.getId())});
db.close();
}
public int getFavCount(){
SQLiteDatabase db = getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM " + TABLE_FAVS, null);
int count = cursor.getCount();
cursor.close();
db.close();
return count;
}
public List<FavImages> getAllFav(){
List<FavImages> favImages = new ArrayList<FavImages>();
SQLiteDatabase db = getWritableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM " + TABLE_FAVS, null);
if (cursor.moveToFirst()){
do {
favImages.add(new FavImages(Integer.parseInt(cursor.getString(0)), cursor.getString(1), Uri.parse(cursor.getString(2))));
}while (cursor.moveToNext());
}
cursor.close();
db.close();
return favImages;
}
Hi you need to use the view holder pattern see link provided below:
http://ricston.com/blog/optimising-listview-viewholder-pattern/
Ok after a fresh look on the code I found my mistake myself, I am adding multiple times the same Item to the List. Stupid mistake I know but now it works fine.
Still, thanks for your Help.

How to check if database is empty in SQLite Android with DatabaseConnector class

I have a DatabaseConnector class where I want to check if the database is empty and then show an alert and a click on it will close the activity.
This is my DatabaseConnector class
public class DatabaseConnector {
// Declare Variables
private static final String DB_NAME = "MyNotes";
private static final String TABLE_NAME = "tablenotes";
private static final String TITLE = "title";
private static final String ID = "_id";
private static final String NOTE = "note";
private static final int DATABASE_VERSION = 2;
private SQLiteDatabase database;
private DatabaseHelper dbOpenHelper;
public static final String MAINCAT = "maincat";
public static final String SUBCAT = "subcat";
public DatabaseConnector(Context context) {
dbOpenHelper = new DatabaseHelper(context, DB_NAME, null,
DATABASE_VERSION);
}
// Open Database function
public void open() throws SQLException {
// Allow database to be in writable mode
database = dbOpenHelper.getWritableDatabase();
}
// Close Database function
public void close() {
if (database != null)
database.close();
}
// Create Database function
public void InsertNote(String title, String note , String maincat, String subcat) {
ContentValues newCon = new ContentValues();
newCon.put(TITLE, title);
newCon.put(NOTE, note);
newCon.put(MAINCAT, maincat);
newCon.put(SUBCAT, subcat);
open();
database.insert(TABLE_NAME, null, newCon);
close();
}
// Update Database function
public void UpdateNote(long id, String title, String note) {
ContentValues editCon = new ContentValues();
editCon.put(TITLE, title);
editCon.put(NOTE, note);
open();
database.update(TABLE_NAME, editCon, ID + "=" + id, null);
close();
}
// Delete Database function
public void DeleteNote(long id) {
open();
database.delete(TABLE_NAME, ID + "=" + id, null);
close();
}
// List all data function
//String selection = dbOpenHelper.MAINCAT + " = 'quiz'"
// +" AND " + dbOpenHelper.SUBCAT + " = 'test'";
// public Cursor ListAllNotes() {
// return database.query(TABLE_NAME, new String[] { ID, TITLE }, null,
// null, null, null, TITLE);
// }
public Cursor ListAllNotes(String selection) {
return database.query(TABLE_NAME, new String[] { ID, TITLE }, selection,
null, null, null, TITLE);
}
// Capture single data by ID
public Cursor GetOneNote(long id) {
return database.query(TABLE_NAME, null, ID + "=" + id, null, null,
null, null);
}
And here is the ListActivity wherein I want to close the Activity with an alert
public class dbMainactivty extends ListActivity {
// Declare Variables
public static final String ROW_ID = "row_id";
private static final String TITLE = "title";
private ListView noteListView;
private CursorAdapter noteAdapter;
#SuppressWarnings("deprecation")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Tracker t = ((AnalyticsSampleApp)this.getApplication()).getTracker(TrackerName.APP_TRACKER);
t.setScreenName("dbMainactivty");
t.send(new HitBuilders.AppViewBuilder().build());
// Locate ListView
noteListView = getListView();
// setContentView(R.layout.list_note);
//noteListView = (ListView) findViewById(R.id.listview);
// Prepare ListView Item Click Listener
noteListView.setOnItemClickListener(viewNoteListener);
// Map all the titles into the ViewTitleNotes TextView
String[] from = new String[] { TITLE };
int[] to = new int[] { R.id.ViewTitleNotes };
// Create a SimpleCursorAdapter
noteAdapter = new SimpleCursorAdapter(dbMainactivty.this,
R.layout.list_note, null, from, to);
// Set the Adapter into SimpleCursorAdapter
setListAdapter(noteAdapter);
}
// Capture ListView item click
OnItemClickListener viewNoteListener = new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// Open ViewNote activity
Intent viewnote = new Intent(dbMainactivty.this, ViewNote.class);
// Pass the ROW_ID to ViewNote activity
viewnote.putExtra(ROW_ID, arg3);
startActivity(viewnote);
}
};
#Override
protected void onResume() {
super.onResume();
// Execute GetNotes Asynctask on return to MainActivity
new GetNotes().execute((Object[]) null);
GoogleAnalytics.getInstance(dbMainactivty.this).reportActivityStart(this);
}
#Override
protected void onStop() {
Cursor cursor = noteAdapter.getCursor();
// Deactivates the Cursor
if (cursor != null)
cursor.deactivate();
noteAdapter.changeCursor(null);
super.onStop();
GoogleAnalytics.getInstance(dbMainactivty.this).reportActivityStop(this);
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
Intent i = null;
switch (item.getItemId()) {
case R.id.action_rate:
String webpage = "http://developer.android.com/index.html";
Intent intent2 = new Intent(Intent.ACTION_VIEW, Uri.parse(webpage));
startActivity(intent2);
overridePendingTransition(R.anim.slide_in, R.anim.slide_out);
case R.id.action_share:
i = new Intent();
i.setAction(Intent.ACTION_SEND);
//i.putExtra(Intent.EXTRA_TEXT, feed.getItem(pos).getTitle().toString()+ " to know the answer download http://developer.android.com/index.html");
i.setType("text/plain");
startActivity(i);
return true;
}
return super.onOptionsItemSelected(item);
};
// GetNotes AsyncTask
private class GetNotes extends AsyncTask<Object, Object, Cursor> {
DatabaseConnector dbConnector = new DatabaseConnector(dbMainactivty.this);
#Override
protected Cursor doInBackground(Object... params) {
// Open the database
dbConnector.open();
return dbConnector.ListAllNotes("maincat LIKE 'quiz' AND subcat LIKE 'test'");
}
#Override
protected void onPostExecute(Cursor result) {
noteAdapter.changeCursor(result);
// Close Database
dbConnector.close();
}
}
#Override
protected void onStart() {
super.onStart();
ConnectivityManager conMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
if (conMgr.getActiveNetworkInfo() == null) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(
"Please check your Internet Connection.")
.setTitle("tilte")
.setCancelable(false)
.setPositiveButton("Exit",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int id) {
//loader.cancel(true);
finish();
}
});
AlertDialog alert = builder.create();
alert.show();
} else {
Cursor cursor = noteAdapter.getCursor();
if(cursor != null && cursor.getCount() > 0){
cursor.moveToFirst();
//do your action
//Fetch your data
GoogleAnalytics.getInstance(dbMainactivty.this).reportActivityStart(this);
Toast.makeText(getBaseContext(), "Yipeee!", Toast.LENGTH_SHORT).show();
}
else {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(
"oops nothing pinned yet! ....")
.setTitle("title")
.setCancelable(false)
.setPositiveButton("Exit",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int id) {
//loader.cancel(true);
finish();
}
});
AlertDialog alert = builder.create();
alert.show();
Toast.makeText(getBaseContext(), "No records yet!", Toast.LENGTH_SHORT).show();
}
}
}
}
I am trying to check
cursor != null && cursor.getCount()>0 and if it turns false then show the alert that
nothing has been pinned yet
Should show up however even though if the cursor returns data the alert still shows up.
First step, take a look at the lifecycle of your activity: http://www.android-app-market.com/wp-content/uploads/2012/03/Android-Activity-Lifecycle.png
As you can see onResume() is called after onStart() which means that checking the cursor on the onStart() can not work.
Secondly you are starting an AsyncTask (GetNotes) on the onResume() method which means you are running a parallel thread at this point and can't check for the result after calling new GetNotes().execute((Object[]) null);
Your problem is you need to check the emptiness of your cursor (cursor != null && cursor.getCount()>0) AFTER the data is loader which mean after the AsyncTask has completed. In other words, move the check for emptiness on your cursor inside the onPostExecute(Cursor result) method.

reloading ListView data from Adapter class in Onclick of Button

I am trying to build up a application which has a custom adapter and all ListView row has three Button. I have onClick operation for all Button in custom adapter. I can change the data source when Button clicked however I can not reload the data from custom adapter.
public class CallListViewCustomAdapter extends ArrayAdapter<Person> {
Context context;
SQLiteDatabase sb;
private static final String SAMPLE_DB_NAME = "androidData.sqlite";
private static final String SAMPLE_TABLE_NAME = "calldetails";
int layoutResourceId;
ArrayList<Person> data = new ArrayList<Person>();
public CallListViewCustomAdapter(Context context, int layoutResourceId, ArrayList<Person> data) {
super(context, layoutResourceId,data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
}
public void refresh(ArrayList<Person>list)
{
data = list;
notifyDataSetChanged();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
convertView = null;
View row = convertView;
final int fPosition = position;
if(row == null)
{
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
final WeatherHolder holder = new WeatherHolder();
holder.phoneNumber = (TextView)row.findViewById(R.id.number);
holder.fname = (TextView)row.findViewById(R.id.fName);
holder.call = (Button)row.findViewById(R.id.callButton);
holder.skip = (Button)row.findViewById(R.id.skip);
holder.called = (Button)row.findViewById(R.id.called);
holder.called.setTag(position);
Person weather = data.get(position);
holder.phoneNumber.setText(weather.number);
holder.fname.setText(weather.fName);
holder.call.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
holder.called.setVisibility(View.VISIBLE);///error comes
holder.skip.setVisibility(View.VISIBLE);///error comes
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:" + data.get(fPosition).number));
callIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(callIntent);
}
});
holder.called.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
//business logic for data source change
refresh(data);///I want listview change here
sb.close();
Log.v("ONMESSAGE", "HARD");
}
});
// holder.desc= (TextView)row.findViewById(R.id.txtViewDescription);
// holder.switchState = (Switch)row.findViewById(R.id.switch1);
row.setTag(holder);
}
return row;
}
static class WeatherHolder
{
TextView phoneNumber;
TextView fname;
Switch switchState;
Button call,skip,called;
}
}
Fragment where The list is used
public class NewFragment extends Fragment{
View rootView;
ProgressDialog pDialog;
private ListView listView1;
CallListViewCustomAdapter adapter;
private static final String SAMPLE_DB_NAME = "androidData.sqlite";
private SQLiteDatabase sampleDB;
ArrayList<Person>list;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
rootView = inflater.inflate(R.layout.newfragment, container, false);
initDB();
list = new ArrayList<Person>();
new CallLogDetails().execute();
return rootView;
}
public int checkTable() {
int return_var = 0;
sampleDB = getActivity().openOrCreateDatabase(SAMPLE_DB_NAME, Context.MODE_PRIVATE, null);
Cursor cc = sampleDB.rawQuery("SELECT * FROM " + "calldetails", null);
if (cc != null){
if (cc.moveToFirst()) {
do {
return_var = cc.getInt(1);
} while (cc.moveToNext());
}
}
return return_var;
}
public void parseandStoreOpearation()
{
try{
CSVReader reader = new CSVReader(new InputStreamReader(getActivity().getAssets().open("batch2.csv")));
String [] nextLine;
sampleDB = getActivity().openOrCreateDatabase(SAMPLE_DB_NAME, Context.MODE_PRIVATE, null);
while ((nextLine = reader.readNext()) != null) {
//Log.v("ONMESSAGE", "YES");
Log.v("ONMESSAGE", "Name: [" + nextLine[0] + "]\nAddress: [" + nextLine[1] + "]\nEmail: [" + nextLine[2] + "]");
if(!nextLine[0].equals("First Name"))
{
//Person newPerson = new Person(nextLine[0],nextLine[1], nextLine[2], 1);
ContentValues cv = new ContentValues();
cv.put("callNumber", nextLine[2]);
cv.put("fName", nextLine[0]);
cv.put("lName", nextLine[1]);
cv.put("callflag", 1);
sampleDB.insert("calldetails", null, cv);
//list.add(newPerson);
}
}
}
catch(Exception e)
{
Log.v("ONMESSAGE", "EXCEPTION " + e.toString());
}
}
public ArrayList<Person> getList()
{
ArrayList<Person> arr = new ArrayList<Person>();
sampleDB= getActivity().openOrCreateDatabase(SAMPLE_DB_NAME, Context.MODE_PRIVATE, null);
Cursor cc = sampleDB.rawQuery("SELECT * FROM " +"calldetails", null);
if(cc != null)
if(cc.moveToFirst()){
do
{ Log.v("Datas",cc.getString(2)+ " " +cc.getString(3) + " " + cc.getString(1) + " " + cc.getInt(4));
Person ph = new Person(cc.getString(2), cc.getString(3), cc.getString(1),cc.getInt(4),cc.getInt(0));
arr.add(ph);
}while(cc.moveToNext());
}
sampleDB.close();
Log.v("ONMESSAGE", new Integer(arr.size()).toString());
return arr;
}
private void initDB() {
sampleDB = getActivity().openOrCreateDatabase(SAMPLE_DB_NAME, Context.MODE_PRIVATE, null);
sampleDB.execSQL("CREATE TABLE IF NOT EXISTS " +
"calldetails" +" (callid INTEGER PRIMARY KEY AUTOINCREMENT,"+ "callNumber TEXT," +
" fName TEXT," + "lName TEXT," + "callflag INTEGER);");
}
private class CallLogDetails extends AsyncTask<Void,Void,Void>{
#Override
protected void onPreExecute(){
pDialog = new ProgressDialog(getActivity());
pDialog.setTitle("Processing");
pDialog.setMessage("Loading Number List");
pDialog.setIndeterminate(true);
pDialog.setCancelable(false);
pDialog.show();
}
protected void onPostExecute(Void params){
super.onPostExecute(params);
pDialog.dismiss();
if(list.size() == 0)
{
list.add(new Person("No Data", "NO Data", "No Data", 0,0));
}
Collections.reverse(list);
if(adapter != null)
adapter.clear();
adapter = new CallListViewCustomAdapter(getActivity(),
R.layout.listview_row, list);
listView1 = (ListView)getActivity().findViewById(R.id.lvAlbumList);
listView1.setOnItemLongClickListener(new OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
final int arg2, long arg3) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Delete Record");
builder.setMessage("Do you want to delete the record?");
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
// TODO Auto-generated method stub
if(list.size() > 0){
sampleDB=getActivity().openOrCreateDatabase(SAMPLE_DB_NAME, SQLiteDatabase.OPEN_READWRITE, null);
//sampleDB.execSQL("DELETE FROM "+ SAMPLE_DB_NAME + " " + "WHERE callDesc= " + desc);
//sampleDB.execSQL("DELETE FROM calldetails WHERE callDesc='"+desc+"';");
Toast.makeText(getActivity(), "Row Deleted", Toast.LENGTH_LONG).show();
sampleDB.close();
new CallLogDetails().execute();
}
else
Toast.makeText(getActivity(), "This is a default object. You can not delete this.", Toast.LENGTH_LONG).show();
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
// TODO Auto-generated method stub
arg0.cancel();
}
});
builder.show();
return false;
}
});
listView1.setAdapter(adapter);
}
#Override
protected Void doInBackground(Void... arg0) {
list.clear();
if(checkTable() == 0)
{
parseandStoreOpearation();
}
list = getList();
Log.v("ONMESSAGE", "Doing");
return null;
}
}
}
For an ArrayAdapter, notifyDataSetChanged() only works if you use the add, insert, remove, and clear functions on the Adapter.
Try following code:
public void refresh(ArrayList<Person>list)
{
data.clear();
data.addAll(list);
this.notifyDataSetChanged();
}
Do something like this inside activity
CallListViewCustomAdapter thadapter=new CallListViewCustomAdapter(MainActivity.this, R.layout.list,numAl);
NumberList.setAdapter(thadapter);
#Override
public void onClick(View v) {
thadapter.notifyDataSetChanged();
}
});
Call notifyDataSetChanged() and recall adapter
Call notifyDataSetChanged() method to the ListView adapter object.

android sqlite query search error

I have been stuck on this one for the past couple of hours (sadly).
I am building an application with SQLite where the application can do all the flexible SQL commands. I am currently stuck on how to search the query from columns other than the ID.
SQLiteDb:
public class SqliteDbTab extends SQLiteOpenHelper
{
public static String DATABASENAME = "androidadvancesqlite";
public static String TABTABLE = "TABTABLE";
public static String ID = "ID";
public static String NAME = "name";
public static String PHONE = "PhOnE";
public static String MAIL = "mail";
public static String ADDRESS = "address";
public static String IMAGE = "image";
private ArrayList<Helperdb> cartList = new ArrayList<Helperdb>();
Context c;
public SqliteDbTab(Context context)
{
super(context, DATABASENAME, null, 33);
c = context;
}
#Override
public void onCreate(SQLiteDatabase db)
{
// TODO Auto-generated method stub
db.execSQL("CREATE TABLE if not exists TABTABLE(ID INTEGER PRIMARY KEY AUTOINCREMENT,"
+ NAME+ " text, "
+ IMAGE + " BLOB , "
+ PHONE + " text , "
+ MAIL + " text , "
+ ADDRESS + " TEXT)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int arg1, int arg2)
{
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS" + TABTABLE);
onCreate(db);
}
public void addContact(Helperdb productitem)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("NAME", productitem.name);
contentValues.put("PHONE", productitem.phone);
contentValues.put("MAIL", productitem.mail);
contentValues.put("ADDRESS", productitem.address);
contentValues.put("IMAGE", productitem.image);
db.insert(TABTABLE, null, contentValues);
db.close();
}
// update
public void updateContact(Helperdb productList)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("NAME", productList.name);
contentValues.put("PHONE", productList.phone);
contentValues.put("MAIL", productList.mail);
contentValues.put("ADDRESS", productList.address);
contentValues.put("IMAGE", productList.image);
db.update(TABTABLE, contentValues, "ID="+ productList.id, null);
db.close();
}
public void emptyProduct()
{
try {
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL(TABTABLE);
db.close();
} catch (Exception e)
{
e.printStackTrace();
}
}
public void removeProduct(String id,String name, String phone, String mail,String address,byte[] blob)
{
try {
String[] args = { id };
getWritableDatabase().delete(TABTABLE, "ID=?", args);
} catch (Exception e)
{
e.printStackTrace();
}
}
public ArrayList<Helperdb> getProudcts()
{
cartList.clear();
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery("select * from TABTABLE", null);
if (cursor.getCount() != 0)
{
if (cursor.moveToFirst())
{
do
{
Helperdb item = new Helperdb();
item.id = cursor.getString(cursor.getColumnIndex("ID"));
item.name = cursor.getString(cursor.getColumnIndex("name"));
item.phone = cursor.getString(cursor.getColumnIndex("PhOnE"));
item.mail = cursor.getString(cursor.getColumnIndex("mail"));
item.address = cursor.getString(cursor.getColumnIndex("address"));
item.image = cursor.getBlob(cursor.getColumnIndex("image"));
cartList.add(item);
}
while (cursor.moveToNext());
}
}
cursor.close();
db.close();
return cartList;
}
public ArrayList<Helperdb> getProudcts(String record)
{
cartList.clear();
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor=db.query(true,TABTABLE,new String[]{"ID","name","PhOnE","mail","address","image"},"name"+"=?",new String[]{record},null,null,null,null);
if (cursor.getCount() != 0)
{
if (cursor.moveToFirst())
{
do {
Helperdb item = new Helperdb();
item.id = cursor.getString(cursor.getColumnIndex("ID"));
item.name = cursor.getString(cursor.getColumnIndex("name"));
item.phone = cursor.getString(cursor.getColumnIndex("PhOnE"));
item.mail = cursor.getString(cursor.getColumnIndex("mail"));
item.address = cursor.getString(cursor.getColumnIndex("address"));
item.image = cursor.getBlob(cursor.getColumnIndex("image"));
cartList.add(item);
} while (cursor.moveToNext());
}
}
cursor.close();
db.close();
return cartList;
}
}
java file:
package com.example.simpletablist;
public class Tab3 extends Activity implements TextWatcher
{
EditText _searchbox;
private ProgressBar showprogress;
searchtask dotask;
private ArrayList<Helperdb> _productList;
ListView _listview;
SqliteDbTab db;
public AutoCompleteTextView myAutoComplete;
private ArrayList<Helperdb> _productList_Temp;
String query = "";
#Override
protected void onCreate(Bundle savedInstanceState)
{
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activitytab3);
_searchbox = (EditText) findViewById(R.id.txtsearchproduct);
showprogress = (ProgressBar) findViewById(R.id.showprogress);
_listview = (ListView) findViewById(R.id.searchlistview);
_searchbox.addTextChangedListener(textwatcher);
}
Runnable runn = new Runnable()
{
#Override
public void run()
{
// TODO Auto-generated method stub
handlersearch.sendEmptyMessage(0);
}
};
TextWatcher textwatcher = new TextWatcher()
{
public void onTextChanged(CharSequence s, int start, int before,int count)
{
Log.i("---onTextChanged ----", "---------onTextChanged ----");
if (_searchbox.getText().toString().length() > 2)
{
query = _searchbox.getText().toString().replace(" ", "%20");
handlersearch.removeCallbacks(runn);
handlersearch.post(runn);
} else
{
showprogress.setVisibility(View.GONE);
if (dotask != null)
{
if (dotask.getStatus().equals(AsyncTask.Status.RUNNING))
{
dotask.cancel(true);
}
}
handlersearch.removeCallbacks(runn);
_productList = new ArrayList<Helperdb>();
_productList.clear();
_listview.setAdapter(new CustomBaseAdapter(Tab3.this,_productList));
}
}
public void beforeTextChanged(CharSequence s, int start, int count,int after)
{
// TODO Auto-generated method stub
}
public void afterTextChanged(Editable s)
{
// TODO Auto-generated method stub
}
};
Handler handlersearch = new Handler()
{
public void handleMessage(android.os.Message msg)
{
dotask = new searchtask();
dotask.execute();
};
};
private class searchtask extends AsyncTask<Void, Void, Void>
{
protected void onPreExecute()
{
showprogress.setVisibility(View.VISIBLE);
};
protected void onPostExecute(Void param)
{
// animation.dismiss();
showprogress.setVisibility(View.GONE);
if (_productList == null)
return;
ArrayList<String> item = new ArrayList<String>();
for (int i = 0; i < _productList.size(); i++)
{
item.add(_productList.get(i).name);
}
myAutoComplete = (AutoCompleteTextView) findViewById(R.id.myautocomplete);
myAutoComplete.addTextChangedListener(Tab3.this);
myAutoComplete.setAdapter(new ArrayAdapter<String>(Tab3.this,android.R.layout.simple_dropdown_item_1line, item));
_productList_Temp = new ArrayList<Helperdb>();
for (int i = 0; i < _productList.size(); i++)
{
_productList_Temp.add(_productList.get(i));
}
_listview.setAdapter(new CustomBaseAdapter(Tab3.this,_productList_Temp));
}
#Override
protected Void doInBackground(Void... params)
{
db = new SqliteDbTab(getApplicationContext());
db.getWritableDatabase();
ArrayList<Helperdb> product_list = db.getProudcts(query);
for (int i = 0; i < product_list.size(); i++)
{
String tidno = product_list.get(i).getid();
System.out.println("tidno>>>>>" + tidno);
String tname = product_list.get(i).getName();
String tphone = product_list.get(i).getPhone();
Helperdb _ProductModel = new Helperdb();
_ProductModel.setid(tidno);
_ProductModel.setName(tname);
_ProductModel.setPhone(tphone);
_productList.add(_ProductModel);
}
// _productList = _parser.getProductList();
return null;
}
}
private class CustomBaseAdapter extends BaseAdapter
{
LayoutInflater _inflater;
List<Helperdb> productList;
public CustomBaseAdapter(Context context, List<Helperdb> productList)
{
_inflater = LayoutInflater.from(context);
this.productList = productList;
}
public int getCount()
{
// TODO Auto-generated method stub
return productList.size();
}
public Object getItem(int position)
{
// TODO Auto-generated method stub
return position;
}
public long getItemId(int position)
{
// TODO Auto-generated method stub
return position;
}
public View getView(int position, View convertView, ViewGroup parent)
{
ViewHolder _holder;
if (convertView == null)
{
convertView = _inflater.inflate(R.layout.contactlist, null);
_holder = new ViewHolder();
_holder.name = (TextView) convertView.findViewById(R.id.txt_title_text);
_holder.phone = (TextView) convertView.findViewById(R.id.txt_price);
convertView.setTag(_holder);
} else
{
_holder = (ViewHolder) convertView.getTag();
}
_holder.name.setText(productList.get(position).name.trim());
_holder.phone.setText(productList.get(position).phone);
return convertView;
}
private class ViewHolder
{
TextView name;
TextView phone;
}
}
#Override
public void afterTextChanged(Editable arg0)
{
// TODO Auto-generated method stub
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,int after)
{
// TODO Auto-generated method stub
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count)
{
// TODO Auto-generated method stub
}
}
logcat file:
12-13 10:47:50.269: I/---onTextChanged ----(2307): ---------onTextChanged ----
12-13 10:47:50.489: I/---onTextChanged ----(2307): ---------onTextChanged ----
12-13 10:47:50.729: I/---onTextChanged ----(2307): ---------onTextChanged ----
12-13 10:47:51.569: I/---onTextChanged ----(2307): ---------onTextChanged ----
12-13 10:47:51.769: I/---onTextChanged ----(2307): ---------onTextChanged ----
12-13 10:47:51.909: I/---onTextChanged ----(2307): ---------onTextChanged ----
12-13 10:47:52.649: I/---onTextChanged ----(2307): ---------onTextChanged ----
12-13 10:47:53.749: I/---onTextChanged ----(2307): ---------onTextChanged ----
12-13 10:47:53.808: I/---onTextChanged ----(2307): ---------onTextChanged ----
12-13 10:47:55.478: I/---onTextChanged ----(2307): ---------onTextChanged ----
12-13 10:47:55.598: I/System.out(2307): tidno>>>>>5
please help me:i am doing search retrieving full name..not getting at i entered first letter only...
![Search UI]
I think you should try "name"+"='"+record+"%'"
you can try a query like this
String SEARCH_QUERY = "SELECT * FROM TABTABLE WHERE name like '"+record+"%'";
Cursor cursor = db.rawQuery(SEARCH_QUERY, null);
cursor.moveToFirst();
if (cursor.getCount() > 0)
{
do {
Helperdb item = new Helperdb();
item.id = cursor.getString(cursor.getColumnIndex("ID"));
item.name = cursor.getString(cursor.getColumnIndex("name"));
item.phone = cursor.getString(cursor.getColumnIndex("PhOnE"));
item.mail = cursor.getString(cursor.getColumnIndex("mail"));
item.address = cursor.getString(cursor.getColumnIndex("address"));
item.image = cursor.getBlob(cursor.getColumnIndex("image"));
cartList.add(item);
} while (cursor.moveToNext());
}
cursor.close();

Categories

Resources