Why does not this AlertDialog dismiss in this situation? - android

I want to insert data from a text file into SQLite database :
public class SyncActivity extends Activity {
...
private MessageDialogView dlg = null; // an AlertDialog showing a message
private Patienter wait = null; // an AlertDialog containing an imageview showing an animation-list
...
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.synchro);
...
dlg = new MessageDialogView(SyncActivity.this, getLayoutInflater());
wait = new Patienter(SyncActivity.this, getLayoutInflater());
...
}
public void synchroniser(View view) { // called when a button is clicked
wait.show();
new RequestTask().execute("http://192.168.1.8/impots/data/syncro/webVersAndroid/parcelles.txt");
}
private class RequestTask extends AsyncTask<String, Void, Void> {
private String err = "";
private boolean error = false;
private String[] enregs;
#Override
protected Void doInBackground(String... s_url) {
enregs = new String[s_url.length];
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
if(networkInfo != null) {
if (networkInfo.isAvailable() && networkInfo.isConnected()) {
System.setProperty("http.keepAlive", "false");
HttpURLConnection con = null;
BufferedReader reader = null;
for (int u=0; u<s_url.length; u++) {
String tmp;
String lines = "";
try {
URL url = new URL(s_url[u]);
if (url != null) {
con = (HttpURLConnection) url.openConnection();
if (con != null && con.getResponseCode() == HttpURLConnection.HTTP_OK) {
InputStream in = con.getInputStream();
reader = new BufferedReader(new InputStreamReader(in));
boolean firstLine = true;
while ((tmp = reader.readLine()) != null) {
if (firstLine) {
firstLine = false;
lines += tmp;
}
else
lines += "\r\n" + tmp;
}
enregs[u] = lines;
}
}
} catch (MalformedURLException e) {
error = true;
err = getResources().getString(R.string.errBadUrl);
} catch (IOException e) {
error = true;
err = getResources().getString(R.string.errAccessError);
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
}
}
if (con != null)
con.disconnect();
}
}
}
else {
error = true;
err = getResources().getString(R.string.errNotConnected);
}
} else {
error = true;
err = getResources().getString(R.string.errNoNetwork);
}
return null;
}
#Override
protected void onPostExecute(Void result) {
if (error) {
wait.dismiss();
displayError(err);
} else {
populateDB();
wait.dismiss();
}
}
private void displayError(String msg) {
dlg.setTitre(getString(R.string.titreErrMsgBox));
dlg.setMsg(msg);
dlg.show();
}
private void populateDB() {
String[] enreg = SpliterString.Split(enregs[0], "\r\n"); // get each record of "parcelle"
db = new Db(SyncActivity.this).open();
for (int p=0; p<enreg.length; p++) {
Parcelle parcelle = new Parcelle(SpliterString.getColumnValueAt(enreg[p],0),
SpliterString.getColumnValueAt(enreg[p],1),
SpliterString.getColumnValueAt(enreg[p],2),
SpliterString.getColumnValueAt(enreg[p],3),
SpliterString.getColumnValueAt(enreg[p],4),
SpliterString.getColumnValueAt(enreg[p],5),
SpliterString.getColumnValueAt(enreg[p],6),
SpliterString.getColumnValueAt(enreg[p],7),
SpliterString.getColumnValueAt(enreg[p],8),
SpliterString.getColumnValueAt(enreg[p],9),
SpliterString.getColumnValueAt(enreg[p],10),
SpliterString.getColumnValueAt(enreg[p],11),
SpliterString.getColumnValueAt(enreg[p],12),
SpliterString.getColumnValueAt(enreg[p],13),
SpliterString.getColumnValueAt(enreg[p],14));
db.insertParcelle(parcelle);
}
db.close();
}
}
}
Data inside the text file is just one row ( data are represented like a csv but separator is | ) :
1||010-01-02|PARC-0001|PARCELLE DROUDOUDOU|10||2000.00|500.00|1500.00||10, Av Place de l'Independance - CENTRE VILLE|01/02/2000|10/02/2005|CENTRE VILLE|
The problem is that the AlertDialog is never dismissed ! There is no error ! So what is wrong ?
-- EDIT --
public class Patienter extends AlertDialog {
private View contenu;
AnimationDrawable frameAnimation = null;
public Patienter(Context context, LayoutInflater inflater) {
super(context);
contenu = inflater.inflate(R.layout.patienter, null);
setCancelable(false);
setCanceledOnTouchOutside(false);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(contenu);
ImageView img = (ImageView)contenu.findViewById(R.id.imgWait);
img.setBackgroundResource(R.drawable.wait);
frameAnimation = (AnimationDrawable) img.getBackground();
frameAnimation.start();
}
}
public class Db {
public static final String DB_NAME = "bdd_impot.bd", T_BIEN = "bien", T_PARCELLE = "parcelle", T_DECOUP_TERRIT = "decoupage_territoire";
public static int VERSION = 1;
private DbHelper DBHelper;
private SQLiteDatabase bd;
public Db(Context context) {
DBHelper = new DbHelper(context);
}
private class DbHelper extends SQLiteOpenHelper {
public DbHelper(Context context) {
super(context,DB_NAME, null, VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE IF NOT EXISTS "+T_BIEN+" (bien_code integer PRIMARY KEY AUTOINCREMENT,"
+ "bien_ident text,"
+ "bien_code_sig text);");
db.execSQL("CREATE TABLE IF NOT EXISTS "+T_PARCELLE+" (bien_code integer,"
+ "decoup_terri_code text,"
+ "dec_decoup_terri_code text,"
+ "bien_ident text,"
+ "parcel_denomination text,"
+ "parcel_porte_ppale text,"
+ "parcel_porte_second text,"
+ "parcel_superfi_totale numeric,"
+ "parcel_superf_batie numeric,"
+ "parcel_superf_non_batie numeric,"
+ "parcel_superf_plani numeric,"
+ "parcel_adresse text,"
+ "parcel_date_deb_construct text,"
+ "parcel_date_fin_construct text,"
+ "quartier_lib text);");
db.execSQL("CREATE TABLE IF NOT EXISTS "+T_DECOUP_TERRIT+" (decoup_terri_code TEXT PRIMARY KEY,"
+ "decoup_terri_nom TEXT);"); // rue
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS "+T_PARCELLE+";");
db.execSQL("DROP TABLE IF EXISTS "+T_DECOUP_TERRIT+";");
db.execSQL("DROP TABLE IF EXISTS "+T_BIEN+";");
onCreate(db);
}
}
public Db open() {
bd = DBHelper.getWritableDatabase();
return this;
}
public void close() {
bd.close();
}
public void insertBien(Bien b) {
ContentValues values = new ContentValues();
values.put("bien_ident", b.getBien_ident());
values.put("bien_code_sig", b.getBien_code_sig());
bd.insert(T_BIEN, null, values);
}
private int getBienLastInsertID() { // call this method after INSERT on table BIEN
Cursor c = bd.rawQuery("SELECT last_insert_rowid()", null);
if (c != null) {
c.moveToFirst();
int id = c.getInt(0);
c.close();
return id;
}
return 0;
}
public Parcelle getParcelle(int bien_code) {
Parcelle p = new Parcelle();
String[] columnsParcelle = {"bien_code","decoup_terri_code","dec_decoup_terri_code","bien_ident",
"parcel_denomination","parcel_porte_ppale","parcel_porte_second",
"parcel_superfi_totale","parcel_superf_batie","parcel_superf_non_batie",
"parcel_superf_plani","parcel_adresse","parcel_date_deb_construct","parcel_date_fin_construct","quartier_lib"};
Cursor c = bd.query(T_PARCELLE, columnsParcelle, "bien_code=?", new String[]{String.valueOf(bien_code)}, null, null, null);
if (c != null && c.getCount() > 0 ) {
c.moveToFirst();
p = new Parcelle(c.getString(0),c.getString(1),c.getString(2),c.getString(3),c.getString(4),c.getString(5),c.getString(6),c.getString(7),c.getString(8),c.getString(9),c.getString(10),c.getString(11),c.getString(12),c.getString(13),c.getString(14));
}
return p;
}
public ArrayList<Parcelle> getAllParcelles() {
ArrayList<Parcelle> parcelles = new ArrayList<Parcelle>();
String selectQuery = "SELECT * FROM " + T_PARCELLE;
Cursor c = bd.rawQuery(selectQuery, null);
if (c.moveToFirst()) {
do {
Parcelle p = new Parcelle();
p.setBien_code(c.getString(0));
p.setDecoup_terri_code(c.getString(1));
p.setDec_decoup_terri_code(c.getString(2));
p.setBien_ident(c.getString(3));
p.setParcel_denomination(c.getString(4));
p.setParcel_porte_ppale(c.getString(5));
p.setParcel_porte_second(c.getString(6));
p.setParcel_superfi_totale(c.getString(7));
p.setParcel_superf_batie(c.getString(8));
p.setParcel_superf_non_batie(c.getString(9));
p.setParcel_superf_plani(c.getString(10));
p.setParcel_adresse(c.getString(11));
p.setParcel_date_deb_construct(c.getString(12));
p.setParcel_date_fin_construct(c.getString(13));
p.setQuartier_lib(c.getString(14));
parcelles.add(p);
} while (c.moveToNext());
}
return parcelles;
}
public void insertParcelle(Parcelle p) {
ContentValues values = new ContentValues();
if (p.getBien_code() == "")
values.put("bien_code", getBienLastInsertID());
else
values.put("bien_code", p.getBien_code());
values.put("decoup_terri_code", p.getDecoup_terri_code());
values.put("dec_decoup_terri_code", p.getDec_decoup_terri_code());
values.put("bien_ident", p.getBien_ident());
values.put("parcel_denomination", p.getParcel_denomination());
values.put("parcel_porte_ppale", p.getParcel_porte_ppale());
values.put("parcel_porte_second", p.getParcel_porte_second());
values.put("parcel_superfi_totale", p.getParcel_superfi_totale());
values.put("parcel_superf_batie", p.getParcel_superf_batie());
values.put("parcel_superf_non_batie", p.getParcel_superf_non_batie());
values.put("parcel_superf_plani", p.getParcel_superf_plani());
values.put("parcel_adresse", p.getParcel_adresse());
values.put("parcel_date_deb_construct", p.getParcel_date_deb_construct());
values.put("parcel_date_fin_construct", p.getParcel_date_fin_construct());
values.put("quartier_lib", p.getQuartier_lib());
bd.insert(T_PARCELLE, null, values);
}
public int updateParcelle(Parcelle p) {
ContentValues values = new ContentValues();
values.put("decoup_terri_code", p.getDecoup_terri_code());
values.put("dec_decoup_terri_code", p.getDec_decoup_terri_code());
values.put("bien_ident", p.getBien_ident());
values.put("parcel_denomination", p.getParcel_denomination());
values.put("parcel_porte_ppale", p.getParcel_porte_ppale());
values.put("parcel_porte_second", p.getParcel_porte_second());
values.put("parcel_superfi_totale", p.getParcel_superfi_totale());
values.put("parcel_superf_batie", p.getParcel_superf_batie());
values.put("parcel_superf_non_batie", p.getParcel_superf_non_batie());
values.put("parcel_superf_plani", p.getParcel_superf_plani());
values.put("parcel_adresse", p.getParcel_adresse());
values.put("parcel_date_deb_construct", p.getParcel_date_deb_construct());
values.put("parcel_date_fin_construct", p.getParcel_date_fin_construct());
values.put("quartier_lib", p.getQuartier_lib());
return bd.update(T_PARCELLE, values, "bien_code = ?", new String[] { String.valueOf(p.getBien_code()) });
}
public int getParcelleCount() {
String countQuery = "SELECT count(*) as nb FROM " + T_PARCELLE;
Cursor cursor = bd.rawQuery(countQuery, null);
int nb = cursor.getInt(0);
cursor.close();
return nb;
}
}
Even if I write just this line inside the onPostExecute then the dialog does not dismiss :
#Override
protected void onPostExecute(Void result) { // appellé automatiquement quand le tache background est terminé
wait.dismiss();
}

private class RequestTask extends AsyncTask<String, Void, Void> {
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
}
#Override
protected Void doInBackground(String... s_url) {
return null;
}
#Override
protected void onPostExecute(Void result) {
pp.dismiss();
}
}
//=========================================//
public class Main extends Activity {
/** Called when the activity is first created. */
Patienter pp;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main); // This needs to be done before
// trying to findViewById
final View vv = findViewById(R.id.my_webview);
vv.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
pp = new Patienter(Main.this, getLayoutInflater());
pp.show();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
new RequestTask().execute();
}
}, 5*1000);
}
});
}
Its working in my project.
please use wait.dismiss(); before if condition in onPostExecute() method.

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());

Doesn't wait Timer for user to click on answers in Android Quiz Game, and quickly run

I have navigation drawer with menu nav items. Now I define for one item, for when clicking on it, open a new activity.Inside this activity, I design layout for start flag game quiz.When clicking on play game Button, the game started so fast without waiting for click user, and finish. Inside "PlayGame" layout, I define one imageView for flags and 4 buttons for answers. Flags name and answers come from the External database. When I debug the app, countDownTimer realise null amount, Everything is correct, Just Timer doesn't wait for use, and playing Quiz is so quickly.
this is my database.
WorldCountryDatabase
public class WorldCountryDatabase extends SQLiteOpenHelper {
private static final String TAG = "databaseHelper";
private static final String DB_NAME = "worldCountries.db";
private static final int DB_VERSION = 1;
private static final String TABLE_NAME = "country";
private static String DB_PATH = "";
private Context mContext;
private SQLiteDatabase database;
public WorldCountryDatabase(Context context) {
super(context, DB_NAME, null, DB_VERSION);
DB_PATH = context.getDatabasePath(DB_NAME).getPath();
File file = new File(DB_PATH + "worldCountries.db");
if (file.exists())
openDataBase();
this.mContext = context;
}
public void createDatabase() {
boolean dbExist = checkDatabase();
if (dbExist) {
Log.d("MIN1", "Database already Exist");
} else {
this.getReadableDatabase();
}
try {
copyDataBase();
} catch (IOException e) {
e.printStackTrace();
Log.i("MIN2", e.getMessage());
}
}
private boolean checkDatabase() {
SQLiteDatabase checkDB = null;
try {
String myPath = DB_PATH + DB_NAME;
checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);
} catch (SQLiteException e) {
e.printStackTrace();
Log.d("MIN3", e.getMessage());
}
if (checkDB != null) {
checkDB.close();
}
return checkDB != null;
}
public synchronized void close() {
if (database != null) {
database.close();
SQLiteDatabase.releaseMemory();
}
super.close();
}
private void copyDataBase() throws IOException {
try {
InputStream in = mContext.getAssets().open(DB_NAME);
String outFileName = DB_PATH + DB_NAME;
OutputStream out = new FileOutputStream(outFileName);
byte[] buffer = new byte[1024];
int length;
while ((length = in.read(buffer)) > 0) {
out.write(buffer, 0, length);
}
out.flush();
out.close();
in.close();
Log.d("MIN4", "Database copy");
} catch (SQLiteException e) {
Log.d("MIN5", e.getMessage());
}
}
public Cursor QueryData(String query) {
return database.rawQuery(query, null);
}
#Override
public void onCreate(SQLiteDatabase db) {
Log.d("MIN6", "onCreate");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
Log.v("LOG_TAG", "Upgrading Database from version" + oldVersion + "To" + newVersion +
"Which will destroy all oldest data");
if (newVersion > oldVersion) {
try {
copyDataBase();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void openDataBase() {
String myPath = DB_PATH + DB_NAME;
database = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);
Log.d("MIN7", "Opened database");
}
// CRUD Table
public List<Questions> getAllQuestions() {
List<Questions> questionsList = new ArrayList<>();
SQLiteDatabase db = this.getWritableDatabase();
Cursor c;
try {
c = db.rawQuery("SELECT * FROM country ORDER BY Random()", null);
if (c == null) return null;
c.moveToFirst();
do {
int Id = c.getInt(c.getColumnIndex("id"));
String Image = c.getString(c.getColumnIndex("Image"));
String AnswerA = c.getString(c.getColumnIndex("AnswerA"));
String AnswerB = c.getString(c.getColumnIndex("AnswerB"));
String AnswerC = c.getString(c.getColumnIndex("AnswerC"));
String AnswerD = c.getString(c.getColumnIndex("AnswerD"));
String CorrectAnswer = c.getString(c.getColumnIndex("CorrectAnswer"));
Questions question = new Questions(Id, Image, AnswerA, AnswerB, AnswerC, AnswerD, CorrectAnswer);
questionsList.add(question);
} while (c.moveToNext());
c.close();
} catch (Exception e) {
e.printStackTrace();
}
database.close();
return questionsList;
}
// Insert Score to Ranking table.
public void insertScore(double score) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues content = new ContentValues();
content.put("Score", score);
db.insert("Ranking", null, content);
}
// Get score and sort Ranking.
public List<Ranking> getRanking() {
List<Ranking> rankingList = new ArrayList<>();
SQLiteDatabase db = this.getWritableDatabase();
Cursor c;
try {
c = db.rawQuery("SELECT * FROM country ORDER BY Score DESC;", null);
if (c == null) return null;
c.moveToFirst();
do {
int ID = c.getInt(c.getColumnIndex("id"));
int Score = c.getInt(c.getColumnIndex("Score"));
Ranking ranking = new Ranking(ID, Score);
rankingList.add(ranking);
} while (c.moveToNext());
c.close();
} catch (Exception e) {
e.printStackTrace();
}
db.close();
return rankingList;
}
public int getPlayCount(int level)
{
int result = 0;
SQLiteDatabase db = this.getReadableDatabase();
Cursor c;
try{
c = db.rawQuery("SELECT PlayCount FROM UserPlayCount WHERE Level="+level+";",null);
if(c == null) return 0;
c.moveToNext();
do{
result = c.getInt(c.getColumnIndex("PlayCount"));
}while(c.moveToNext());
c.close();
}catch (Exception ex)
{
ex.printStackTrace();
}
return result;
}
public void updatePlayCount(int level,int playCount)
{
String query = String.format("UPDATE UserPlayCount Set PlayCount = %d WHERE Level = %d",playCount,level);
database.execSQL(query);
}
this is my ChoicGame class.
ChoiceGame
public class ChoiceGame extends AppCompatActivity {
TextView modeText;
SeekBar seekBarMode;
Button playGame, scoreGame;
WorldCountryDatabase worldCountryDatabase;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game_flag);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
if (getSupportActionBar() != null)
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
modeText = (TextView) findViewById(R.id.modeText);
seekBarMode = (SeekBar) findViewById(R.id.seekBarMode);
playGame = (Button) findViewById(R.id.playGame);
scoreGame = (Button) findViewById(R.id.scoreGame);
worldCountryDatabase = new WorldCountryDatabase(this);
try {
worldCountryDatabase.createDatabase();
} catch (Exception e) {
e.printStackTrace();
}
//Event
seekBarMode.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if (progress == 0)
modeText.setText(Common.MODE.EASY.toString());
else if (progress == 1)
modeText.setText(Common.MODE.MEDIUM.toString());
else if (progress == 2)
modeText.setText(Common.MODE.HARD.toString());
else if (progress == 3)
modeText.setText(Common.MODE.HARDEST.toString());
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
playGame.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), PlayGameCountry.class);
intent.putExtra("Mode", getPlayMode()); // Send Mode to Playing page
startActivity(intent);
finish();
}
});
scoreGame.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), ScoreGame.class);
startActivity(intent);
finish();
}
});
}
private String getPlayMode() {
if (seekBarMode.getProgress() == 0)
return Common.MODE.EASY.toString();
else if (seekBarMode.getProgress() == 1)
return Common.MODE.MEDIUM.toString();
else if (seekBarMode.getProgress() == 2)
return Common.MODE.HARD.toString();
else
return Common.MODE.HARDEST.toString();
}
}
and at last this is my PlayingGame class.
PlayingGmae
public class PlayGameCountry extends AppCompatActivity implements View.OnClickListener {
final static long INTERVAL = 1; // 1 second
final static long TIMEOUT = 7; // 1 second
CountDownTimer countDownTimer;
int progressValue = 0;
int score = 0, index = 0, thisQuestion = 0, correctAnswer, totalQuestions;
List<Questions> questionsList = new ArrayList<>();
String mode;
ProgressBar progressBar;
ImageView flagCountry;
TextView scoreText, numberQuestion;
Button answerA, answerB, answerC, answerD;
WorldCountryDatabase worldCountryDatabase;
ChoiceGame choiceGame;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_play_game_country);
// Get data from ChoiceGame
Bundle bundle = getIntent().getExtras();
if (bundle != null)
mode = bundle.getString("Mode");
worldCountryDatabase = new WorldCountryDatabase(this);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
if (getSupportActionBar() != null) {
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
flagCountry = (ImageView) findViewById(R.id.flagQuiz);
scoreText = (TextView) findViewById(R.id.scoreText);
numberQuestion = (TextView) findViewById(R.id.trueAnswer);
answerA = (Button) findViewById(R.id.firstAnswer);
answerB = (Button) findViewById(R.id.secondAnswer);
answerC = (Button) findViewById(R.id.thirthAnswer);
answerD = (Button) findViewById(R.id.forthAnswer);
progressBar = (ProgressBar) findViewById(R.id.progressUser);
answerA.setOnClickListener(this);
answerB.setOnClickListener(this);
answerC.setOnClickListener(this);
answerD.setOnClickListener(this);
}
#Override
protected void onResume() {
super.onResume();
questionsList = this.getQuestionMode(mode);
assert questionsList != null;
totalQuestions = questionsList.size();
countDownTimer = new CountDownTimer(INTERVAL, TIMEOUT) {
#Override
public void onTick(long millisUntilFinished) {
progressBar.setProgress(progressValue);
progressValue++;
}
#Override
public void onFinish() {
countDownTimer.cancel();
showQuestion(++index);
}
};
showQuestion(index);
}
private void showQuestion(int index) {
if (index < totalQuestions) {
thisQuestion++;
numberQuestion.setText(String.format("%d/%d", thisQuestion, totalQuestions));
progressBar.setProgress(0);
progressValue = 0;
int ImageId = this.getResources().getIdentifier(questionsList.get(index).getImage().toLowerCase(), "drawable", getPackageName());
flagCountry.setBackgroundResource(ImageId);
answerA.setText(questionsList.get(index).getAnswerA());
answerB.setText(questionsList.get(index).getAnswerB());
answerC.setText(questionsList.get(index).getAnswerC());
answerD.setText(questionsList.get(index).getAnswerD());
countDownTimer.start();
} else {
Intent scoreIntent = new Intent(getApplicationContext(), Done.class);
Bundle bundle = new Bundle();
bundle.putInt("SCORE", score);
bundle.putInt("TOTAL", totalQuestions);
bundle.putInt("CORRECT", correctAnswer);
scoreIntent.putExtras(bundle);
startActivity(scoreIntent);
finish();
}
}
#Override
public void onClick(View v) {
countDownTimer.cancel();
if (index < totalQuestions) {
Button clickedButton = (Button) v;
if (clickedButton.getText().equals(questionsList.get(index).getCorrectAnswer()))
{
score += 10; // increase score
correctAnswer++; //increase correct answer
showQuestion(++index);
} else
showQuestion(++index); // If choose right , just go to next question
scoreText.setText(String.format("%d", score));
}
}
private List<Questions> getQuestionMode(String mode) {
List<Questions> questionList = new ArrayList<>();
worldCountryDatabase = new WorldCountryDatabase(this);
try {
worldCountryDatabase.createDatabase();
worldCountryDatabase.openDataBase();
} catch (Exception e) {
e.printStackTrace();
}
int limit = 0;
if (mode.equals(Common.MODE.EASY.toString()))
limit = 30;
else if (mode.equals(Common.MODE.MEDIUM.toString()))
limit = 50;
else if (mode.equals(Common.MODE.HARD.toString()))
limit = 100;
else if (mode.equals(Common.MODE.HARDEST.toString()))
limit = 200;
try {
Cursor cursor = worldCountryDatabase.QueryData(String.format("SELECT * FROM country ORDER BY Random() LIMIT %d", limit));
if (cursor == null) return null;
if (cursor.moveToNext()) {
do {
int Id = cursor.getInt(cursor.getColumnIndex("id"));
String Image = cursor.getString(cursor.getColumnIndex("Image"));
String AnswerA = cursor.getString(cursor.getColumnIndex("AnswerA"));
String AnswerB = cursor.getString(cursor.getColumnIndex("AnswerB"));
String AnswerC = cursor.getString(cursor.getColumnIndex("AnswerC"));
String AnswerD = cursor.getString(cursor.getColumnIndex("AnswerD"));
String CorrectAnswer = cursor.getString(cursor.getColumnIndex("CorrectAnswer"));
Questions question = new Questions(Id, Image, AnswerA, AnswerB, AnswerC, AnswerD, CorrectAnswer);
questionList.add(question);
} while (cursor.moveToNext());
worldCountryDatabase.close();
}
} catch (Exception e) {
e.printStackTrace();
}
return questionList;
}
}
At the first, I defining "getQuestionMode" method inside WorldCountryDatabase, but the app doesn't go to the PlayingCountryGame layout and open ScoreGame class. After I define "getQuestionMode" method inside PlayingCountryGame class. I hope to tell clear my problem.
Please help me, good friends. Thanks to all of you.
I think that you problem is the constructor and values.
https://developer.android.com/reference/android/os/CountDownTimer.html#CountDownTimer(long, long)
The constructor need the time on milliseconds and not seconds. Y ou need convert 1 second to 1000 ms.
final static long INTERVAL = 1000; // 1 second -> 1000 milliseconds
final static long TIMEOUT = 7000; // 7 seconds -> 7000 milliseconds
And the order of the params.
If you want wait 7 second the constructor is:
countDownTimer = new CountDownTimer(TIMEOUT, INTERVAL){ ... }

Display Results in ListView from Database

I am trying to display result from Database in a listView which is clickable On long click ,items can be deleted and on click it go to another activity. So I create an activity called editdeletedoctor
public class editdeletedoctor extends Activity {
private ArrayList<String> results = new ArrayList<String>();
private String tableName = TableData.TableInfo.TABLE_DOCTOR;
private SQLiteDatabase newDB;
private ArrayList<doctorClass> doctor_List = new ArrayList<doctorClass>();
public static String MODEL_TO_EDIT = "MODEL_TO_EDIT";
public ListView list;
public ArrayAdapter<String> adapter;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
init();
openAndQueryDatabase();
displayResultList();
}
private void init() {
list = (ListView) findViewById(R.id.list);
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent intent = new Intent(editdeletedoctor.this,
registerdoctor.class);
intent.putExtra("theText", doctor_List.get(position).getUsername());
intent.putExtra(editdeletedoctor.MODEL_TO_EDIT,doctor_List.get(position));
editdeletedoctor.this.finish();
startActivity(intent);
}
});
list.setOnItemLongClickListener(new OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view,
final int position, long id) {
Builder dialog = new AlertDialog.Builder(editdeletedoctor.this);
dialog.setTitle("Are you sure you want to delete This doctor?");
dialog.setPositiveButton("Yes", new OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
doctorClass doctor = doctor_List.get(position);
doctor_List.remove(position);
DatabaseOperations db = new DatabaseOperations(getApplicationContext());
try {
db.open();
HashMap<String, String> conditionKV = new HashMap<String, String>();
conditionKV.put(TableData.TableInfo.DOCTOR_ID, doctor.getId() + "");
db.deleteDoctor(conditionKV);
results.remove(position);
adapter.notifyDataSetChanged();
} catch (SQLiteException se) {
Log.e(getClass().getSimpleName(),
"Could not create or Open the database");
} finally {
if (db != null)
db.close();
}
dialog.dismiss();
}
});
dialog.setNegativeButton("No", new OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
dialog.show();
return false;
}
});
}
private void displayResultList() {
adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, results);
list.setAdapter(adapter);
list.setTextFilterEnabled(true);
}
private void openAndQueryDatabase() {
DatabaseOperations db = new DatabaseOperations(getApplicationContext());
try {
db.open();
doctor_List = db.getDoctor(null);
for (doctorClass inc : doctor_List) {
if(inc.getId()==TableData.TableInfo.userID)
results.add("Name: " + inc.getUsername() + " Phone:"
+ inc.getPhone() + ",Address: "
+ inc.getAddress());
}
} catch (SQLiteException se) {
Log.e(getClass().getSimpleName(),
"Could not create or Open the database");
} finally {
if (db != null)
db.close();
}
}
}
And in the DatabaseOperations.java class :
public DatabaseOperations open() throws SQLException {
ourHelper = new DatabaseOperations(context);
ourDatabase = ourHelper.getWritableDatabase();
return this;
}
public void close() {
ourHelper.close();
}
public ArrayList<doctorClass> getDoctor(HashMap<String, String> conditionKV) {
Cursor m_cursor = get(TableData.TableInfo.TABLE_DOCTOR, conditionKV);
ArrayList<doctorClass> list = new ArrayList<doctorClass>();
if (m_cursor.moveToFirst()) {
do {
doctorClass model = new doctorClass();
if (m_cursor.getString(m_cursor.getColumnIndex(TableData.TableInfo.DOCTOR_ID)) != null)
model.setId(m_cursor.getInt(m_cursor.getColumnIndex(TableData.TableInfo.DOCTOR_ID)));
if (m_cursor.getString(m_cursor.getColumnIndex(TableData.TableInfo.DOCTOR_NAME)) != null)
model.setUsername(m_cursor.getString(m_cursor
.getColumnIndex(TableData.TableInfo.DOCTOR_NAME)));
if (m_cursor.getString(m_cursor.getColumnIndex(TableData.TableInfo.DOCTOR_PASS)) != null)
model.setPassword(m_cursor.getString(m_cursor
.getColumnIndex(TableData.TableInfo.DOCTOR_PASS)));
if (m_cursor.getString(m_cursor.getColumnIndex(TableData.TableInfo.DOCTOR_MAIL)) != null)
model.setEmail(m_cursor.getString(m_cursor
.getColumnIndex(TableData.TableInfo.DOCTOR_MAIL)));
if (m_cursor.getString(m_cursor.getColumnIndex(TableData.TableInfo.DOCTOR_PHONE)) != null)
model.setPhone(m_cursor.getString(m_cursor
.getColumnIndex(TableData.TableInfo.DOCTOR_PHONE)));
if (m_cursor.getString(m_cursor.getColumnIndex(TableData.TableInfo.DOCTOR_ADDRESS)) != null)
model.setAddress(m_cursor.getString(m_cursor
.getColumnIndex(TableData.TableInfo.DOCTOR_ADDRESS)));
if (m_cursor.getString(m_cursor.getColumnIndex(TableData.TableInfo.DOCTOR_GENDER)) != null)
model.setGender(m_cursor.getString(m_cursor
.getColumnIndex(TableData.TableInfo.DOCTOR_GENDER)));
list.add(model);
} while (m_cursor.moveToNext());
}// end if
return list;
}
public Cursor get(String tableName, HashMap<String, String> conditionKV) {
String whereClause = null;
if (conditionKV != null)
whereClause = formatWherecondition(conditionKV);
String completeQuery = "SELECT * FROM " + tableName + " ";
if (whereClause != null) {
completeQuery += " WHERE " + whereClause;
}
return ourDatabase.rawQuery(completeQuery, null);
}
public String formatWherecondition(HashMap<String, String> conditionKV) {
try {
String result = "";
if (conditionKV.size() < 1) {
throw new Exception("Hahsmap condition Empty");
}
Iterator l_iterator = conditionKV.keySet().iterator();
boolean isOneField = false;
while (l_iterator.hasNext()) {
String l_key = (String) l_iterator.next();
String l_value = conditionKV.get(l_key);
if (isOneField)
result = result + " AND ";
result = result + l_key + "='" + l_value + "' ";
isOneField = true;
}
return result;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public void deleteDoctor(HashMap<String, String> conditionKV) {
delete(TableData.TableInfo.TABLE_DOCTOR, conditionKV);
}
private void delete(String tableName, HashMap<String, String> conditionKV) {
String whereClause = null;
if (conditionKV == null)
return;
whereClause = formatWherecondition(conditionKV);
String completeQuery = "DELETE FROM " + tableName + " ";
if (whereClause != null) {
completeQuery += " WHERE " + whereClause;
ourDatabase.execSQL(completeQuery);
}
}
When running, an error occured, Here is the logcat
Please help me .
Thank you
Are you sure the "context" you are using here is not null ?
How about rewriting the open() function this way and calling it via open(getApplicationContext()); ?
public DatabaseOperations open(Context context) throws SQLException {
ourHelper = new DatabaseOperations(context);
ourDatabase = ourHelper.getWritableDatabase();
return this;
}

Android convert sqlite single record to csv

I want to convert a single row to a .csv file. How am I going to do that? All I've seen in the Internet are most of them the whole sqlite db is being converted/exported to a .csv file. But my requirement is only a single record? Do you have ideas as to how am I gonna achieve this? Help is much appreciated. Thanks!
Update:
public class CSVCreationActivity extends Activity {
TextView empidtxt,empnametxt,empsaltxt;
EditText empidet,empnameet,empsalet;
Button insetbt,viewbt;
SQLiteDatabase myDatabase=null;
String DataBase_Name="employeedata";
String Table_Name="employeedetails";
Cursor c1,c2;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
empidtxt=(TextView)findViewById(R.id.tv1);
empnametxt=(TextView)findViewById(R.id.tv2);
empsaltxt=(TextView)findViewById(R.id.tv3);
empidet=(EditText)findViewById(R.id.et1);
empnameet=(EditText)findViewById(R.id.et2);
empsalet=(EditText)findViewById(R.id.et3);
insetbt=(Button)findViewById(R.id.bt1);
viewbt=(Button)findViewById(R.id.bt2);
try {
myDatabase=this.openOrCreateDatabase(DataBase_Name, MODE_PRIVATE, null);
System.out.println("databse has been created.....");
myDatabase.execSQL("create table if not exists " + Table_Name + "(empid integer(10),empname varchar(50),empsal integer(10))");
System.out.println("table has been created.....");
c1 = myDatabase.rawQuery("select * from " + Table_Name, null);
c1.moveToFirst();
int count1 = c1.getCount();
System.out.println("columns --->" + count1);
if (count1 == 0) {
myDatabase.execSQL("insert into "+Table_Name+ "(empid,empname,empsal)" +"values(101,'asha',20000)");
System.out.println("data base has been inserted.....");
}
c2 = myDatabase.rawQuery("select * from " + Table_Name, null);
c2.moveToFirst();
int count2 = c2.getCount();
System.out.println("columns --->" + count2);
final int column1 = c2.getColumnIndex("empid");
final int column2 = c2.getColumnIndex("empname");
final int column3 = c2.getColumnIndex("empsal");
insetbt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (c2 != null) {
do {
int id = c2.getInt(column1);
String name = c2.getString(column2);
int salary = c2.getInt(column3);
System.out.println("empID --> "+id);
System.out.println("empNAME --> "+name);
System.out.println("empsalalry --> "+salary);
} while(c2.moveToNext());
}
}
});
viewbt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
new ExportDatabaseCSVTask().execute("");
} catch(Exception ex) {
Log.e("Error in MainActivity",ex.toString());
}
}
});
}
catch(SQLException ex) { ex.printStackTrace(); }
/*finally {
if (myDB != null) { myDB.close(); }
}*/
}
public class ExportDatabaseCSVTask extends AsyncTask<String, Void, Boolean> {
private final ProgressDialog dialog = new ProgressDialog(CSVCreationActivity.this);
#Override
protected void onPreExecute() {
this.dialog.setMessage("Exporting database...");
this.dialog.show();
}
protected Boolean doInBackground(final String... args) {
File dbFile = getDatabasePath("myDatabase.db");
System.out.println(dbFile); // displays the data base path in your logcat
File exportDir = new File(Environment.getExternalStorageDirectory(), "");
if (!exportDir.exists()) { exportDir.mkdirs(); }
File file = new File(exportDir, "myfile.csv");
try {
file.createNewFile();
CSVWriter csvWrite = new CSVWriter(new FileWriter(file));
Cursor curCSV = myDatabase.rawQuery("select * from " + Table_Name,null);
csvWrite.writeNext(curCSV.getColumnNames());
while(curCSV.moveToNext()) {
String arrStr[] ={curCSV.getString(0),curCSV.getString(1),curCSV.getString(2)};
// curCSV.getString(3),curCSV.getString(4)};
csvWrite.writeNext(arrStr);
}
csvWrite.close();
curCSV.close();
return true;
} catch(SQLException sqlEx) {
Log.e("MainActivity", sqlEx.getMessage(), sqlEx);
return false;
} catch (IOException e) {
Log.e("MainActivity", e.getMessage(), e);
return false;
}
}
protected void onPostExecute(final Boolean success) {
if (this.dialog.isShowing()) { this.dialog.dismiss(); }
if (success) {
Toast.makeText(CSVCreationActivity.this, "Export successful!", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(CSVCreationActivity.this, "Export failed", Toast.LENGTH_SHORT).show();
}
}
}
CSVWriter and CSVReader can be downloaded here
Better way to get specific record from database and then convert it to csv file ...
you just need to modify your query to achieve this
Replace this line
Cursor curCSV = myDatabase.rawQuery("select * from " + Table_Name,null);
with ur conditional query means using where operator or anything else...

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