Android convert sqlite single record to csv - android

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

Related

Why does not this AlertDialog dismiss in this situation?

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.

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;
}

Getting a unique row in SQLite

I am trying to search an item in sqlite by using String, & trying to return description contained in that row. items are stored in the table named Articles with column name A_name, Description column name is AS_name
This is my code, the cursor is not null, but the while loop is not getting executed once
public String searchData(String text)
{
Cursor cursor = sdb.query("Articles", new String[] {"A_name","AS_name"}, " A_name=?",new String[]{text}, null, null, null);
Log.e("running", "cursor run");
String temp = null,temp2 = null;
if(cursor!=null)
{
Log.e("running", "curosr is not null");
while(cursor.moveToFirst())
{
Log.e("running", "curosr while loop enter");
temp = (cursor.getString(cursor.getColumnIndex("A_name")));
//temp2 =(cursor.getString(cursor.getColumnIndex("AS_name")));
Log.e("running", "id email" +temp+ " name"+temp2);
}
}
return temp;
}
I want to return the corresponding element of AS_name, also I am confused what should I wrote in while loop ?
Can anyone please identify my mistake, Thanks in advance...
UPDATE DBAdapter.java
public class DBAdapter extends SQLiteOpenHelper
{
//CustomAdapter adapter;
static String name = "law6.sqlite";
static String path = "";
static ArrayList<GS> gs;
static SQLiteDatabase sdb;
#Override
public void onCreate(SQLiteDatabase db)
{
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
// TODO Auto-generated method stub
}
private DBAdapter(Context v)
{
super(v, name, null, 1);
path = "/data/data/" + v.getApplicationContext().getPackageName() + "/databases";
}
public boolean checkDatabase()
{
SQLiteDatabase db = null;
try
{
db = SQLiteDatabase.openDatabase(path + "/" + name, null, SQLiteDatabase.OPEN_READONLY);
} catch (Exception e)
{
e.printStackTrace();
}
if (db == null)
{
return false;
}
else
{
db.close();
return true;
}
}
public static synchronized DBAdapter getDBAdapter(Context v)
{
return (new DBAdapter(v));
}
public void createDatabase(Context v)
{
this.getReadableDatabase();
try
{
InputStream myInput = v.getAssets().open(name);
// Path to the just created empty db
String outFileName = path +"/"+ name;
// Open the empty db as the output stream
OutputStream myOutput = new FileOutputStream(outFileName);
// transfer bytes from the inputfile to the outputfile
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer)) > 0)
{
myOutput.write(buffer, 0, length);
}
// Close the streams
myOutput.flush();
myOutput.close();
myInput.close();
/*
InputStream is = v.getAssets().open("quiz.sqlite");
// System.out.println(is.available());
System.out.println(new File(path + "/" + name).getAbsolutePath());
FileOutputStream fos = new FileOutputStream(path + "/" + name);
int num = 0;
while ((num = is.read()) > 0) {
fos.write((byte) num);
}
fos.close();
is.close();*/
} catch (IOException e)
{
System.out.println(e);
}
}
public void openDatabase()
{
try
{
sdb = SQLiteDatabase.openDatabase(path + "/" + name, null,
SQLiteDatabase.OPEN_READWRITE);
} catch (Exception e)
{
System.out.println(e);
}
}
public ArrayList<GS> getData()
{
try{
Cursor c1 = sdb.rawQuery("SELECT DISTINCT * FROM Articles", null);
gs = new ArrayList<GS>();
while (c1.moveToNext())
{
GS q1 = new GS();
q1.setId(c1.getString(0));
q1.setA_id(c1.getString(1));
q1.setA_name(c1.getString(2));
q1.setAS_name(c1.getString(3));
q1.setDesc_art(c1.getString(4));
// q1.setAct(c1.getString(5));
q1.setExtra(c1.getString(6));
q1.setPart(c1.getString(7));
q1.setItalic(c1.getString(8));
Log.v("AS_name",q1.AS_name);
gs.add(q1);
}
}
catch (Exception e) {
e.printStackTrace();
}
return gs;
}
public String searchData(String text)
{
Cursor cursor = sdb.query("Articles", new String[] {"A_name","AS_name"}, " A_name=?",new String[]{text}, null, null, null);
Log.e("running", "cursor run");
String temp = null,temp2 = null;
if(cursor!=null)
{
Log.e("running", "curosr is not null");
Log.v("", ""+cursor.getCount());
while(cursor.moveToNext())
{
Log.e("running", "curosr while loop enter");
temp = (cursor.getString(cursor.getColumnIndex("AS_name")));
// temp2 =(cursor.getString(cursor.getColumnIndex(name)));
Log.e("running", "desc" +temp);
}
}
return temp;
}
}
UPDATE after implementing rajaji answer, I got this error :
try this it will help you
create the raw query for getting the data
public String searchData(String text)
{
String strvalue=null;
SQliteDatabase db=this.getwritabledatabase();
Cursor cur=null;
String strquery="select * from youurtablename where A_name="+text;
cur=db.rawQuery(strquery,null);
if(cur!=null&&cur.moveToFirst())
{
do
{
strvalue=cur.getString(0);
}
while(cur.moveToNext());
}
}
let me inform once you complete
Is your Uri correct??
create Uri depends on your package name and table name, like the code below :
private static final String AUTHORITY = "com.sample.test_db_provider";
private static final String BASE_PATH = "Tables";
private static final Uri Sample_URI = Uri.parse("content://" + AUTHORITY
+ "/" + BASE_PATH
+ "/SampleTable");
Then in your get Method, query the db like the below code with Uri
cur = m_Resolver.query(Sample_URI, new String[] {"A_name","AS_name"},
"SampleTable.A_name = " + text, null, null);
if(cur != null && cur.moveToFirst())
{
do
{
...
}
while(cur.moveToNext());
}
cur.close();
I use the inline where clause but you can do it your way with a parameter. Is this what you are looking for?

Using listviews with a database

and good day. My project is having 2 activities, first one to insert data into the database which works well, but then I want to show a list view of the data within the database in another activity.
I've tried local data eg fred, george in an array and the list view works great however, when I try to use the database. The activity crashes. It seems that I am unable to use "database.open"
public class MyListActivity extends Activity{
DatabaseAdapter database;
//Creates item_details based on the ListItemDetails class
ListItemDetails item_details;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
//Uses the arraylist and set the result
ArrayList<ListItemDetails> result = GetSearchResults();
ListView lv = (ListView)findViewById(R.id.listView1);
lv.setAdapter(new CustomListAdapter(getApplicationContext(),result));
}
private ArrayList<ListItemDetails> GetSearchResults() {
ArrayList<ListItemDetails> results = new ArrayList<ListItemDetails>();
item_details = new ListItemDetails();
/*
database.open();
Cursor c = database.getAllContacts();
if (c.moveToFirst())
{
do {
item_details.setFirstName(c.getString(1));
results.add(item_details);
} while (c.moveToNext());
}
*/
return results;
}
}
Here is the main activity. The database opens fine when I use the buttonShow, so I tried buttonTest and storing them into the list but it got a bit confusing for me.
public class FamousPersonActivity extends Activity {
EditText editFirstName, editLastName;
Button buttonAdd, buttonShow, buttonTest;
ListView lv;
ListItemDetails item_details;
DatabaseAdapter database;
int request_Code = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_famous_person);
database = new DatabaseAdapter(this);
lv = (ListView)findViewById(R.id.listView1);
//ArrayList<ListItemDetails> result = GetSearchResults();
//lv.setAdapter(new CustomListAdapter(getApplicationContext(),result));
editFirstName = (EditText)findViewById(R.id.editFirstName);
editLastName = (EditText)findViewById(R.id.editLastName);
buttonAdd = (Button)findViewById(R.id.buttonAdd);
buttonShow = (Button)findViewById(R.id.buttonShow);
buttonTest = (Button)findViewById(R.id.buttonTest);
buttonAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Toast.makeText(getApplicationContext(), "added to database", Toast.LENGTH_SHORT).show();
database.open();
long id = database.insertContact("Test Contact", "Test Email") ;
database.close();
}
});
buttonTest.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent("com.id11020260.exercise6part2.MyListActivity");
startActivityForResult(i, request_Code);
}
});
buttonShow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
try {
String destPath = "/data/data/" + getPackageName() +
"/databases";
File f = new File(destPath);
if (!f.exists()) {
f.mkdirs();
f.createNewFile();
//---copy the db from the assets folder into
// the databases folder---
CopyDB(getBaseContext().getAssets().open("mydb"),
new FileOutputStream(destPath + "/MyDB"));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
//---get all contacts---
database.open();
Cursor c = database.getAllContacts();
if (c.moveToFirst())
{
do {
DisplayContact(c);
} while (c.moveToNext());
}
database.close();
}
});
}
private ArrayList<ListItemDetails> GetSearchResults() {
ArrayList<ListItemDetails> results = new ArrayList<ListItemDetails>();
item_details = new ListItemDetails();
database.open();
Cursor c = database.getAllContacts();
if (c.moveToFirst())
{
do {
item_details.setFirstName(c.getString(1));
results.add(item_details);
} while (c.moveToNext());
database.close();
}
return results;
}
public void CopyDB(InputStream inputStream,
OutputStream outputStream) throws IOException {
//---copy 1K bytes at a time---
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, length);
}
inputStream.close();
outputStream.close();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.famous_person, menu);
return true;
}
public void DisplayContact(Cursor c)
{
Toast.makeText(this,
"id: " + c.getString(0) + "\n" +
"Name: " + c.getString(1) + "\n" +
"Email: " + c.getString(2),
Toast.LENGTH_LONG).show();
}
}
This is the stack trace, I'm not sure if this is entirely correct
Try this:-
lv.setListAdapter(new ArrayAdapter(MyListActivity.this,
android.R.layout.simple_list_item_1,result));

Why I don't see record in database from my test project?

Hї!
I have wrote test for my application. I need add item to database throught UI interface (using robotium) and then I want to check if item exists in database using SQLiteDatabase.
Item is added succesfully (I see new record in database after test finished), but isExistsInDb in my test class returns false. I do not understand why. Could you please help me.
Thanks!
Activity class:
public abstract class EditActivity {
// Some code .....
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
initButtonCancelOk();
}
protected void validateAndSave() {
try {
formValidator.validateAll();
if (formValidator.isFormValid()) {
DatabaseOpenHelper doh = new DatabaseOpenHelper(this);
Dao d = new Dao(doh);
d.add(fetchObjectFromUi());
finish(); // destroy this activity
} else {
ToastImage.makeImageText(context,
R.drawable.warning,
formValidator.getMessages(),
Toast.LENGTH_SHORT
).show();
}
} catch (Exception e) {
Toast.makeText(context, " Error during validate form ", Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
private void initButtonCancelOk() {
btnOk = (Button) findViewById(R.id.btn_ok);
btnOk.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
validateAndSave();
}
});
}
}
Test class:
public class AddItemSmokeTest extends extends ActivityInstrumentationTestCase2<EditActivity> {
protected Activity activity;
protected Solo solo;
public AddItemSmokeTest() {
super("com.myapp", EditActivity.class);
Intent i = createIntent(2);
setActivityIntent(i);
activity = getActivity();
solo = new Solo(getInstrumentation(), activity);
solo.sleep(1000); // interval between tests
}
protected Intent createIntent(long transType) {
Intent i = new Intent();
i.putExtra(INTENT_VALUE_MODE_NAME, MODE_INSERT_TRANSACTION);
i.putExtra(INTENT_VALUE_TYPE_ID_NAME, transType);
return i;
}
#Override
protected void tearDown() throws Exception {
}
protected void setIncomExpenseData(AbsTransIncomeExpenseTestData testData) {
solo.pressSpinnerItem(CATEGORY_SPN_INDEX, testData.getCategorySpinnerPos());
solo.pressSpinnerItem(ACCOUNT_SPN_INDEX, testData.getAccountSpinnerPos());
solo.typeText((EditText) activity.findViewById(com.rirdev.moneycounter.R.id.et_sum), testData.getSum());
solo.typeText((EditText) activity.findViewById(com.rirdev.moneycounter.R.id.et_comment), testData.getComment());
}
#Smoke
public void testAddIncomeTransaction() throws Exception {
initForType(TransactionType.INCOME);
AbsTransIncomeExpenseTestData testData = new IncomeTestData();
setIncomExpenseData(testData);
solo.clickOnButton(OK);
//solo.getActivityMonitor();
assertTrue(
"Item" + testData.getComment() + " was not added ",
isExistsInDb(activity, Transactions.TABLE_NAME, Transactions.DESCRIPTION, testData.getComment())
);
}
protected static boolean isExistsInDb(Context context, String tableName, String commentFieldName, String comment) {
DatabaseOpenHelper doh = new DatabaseOpenHelper(context);
SQLiteDatabase db = doh.getDatabaseReadable();
Cursor cursor = null;
try {
String query = "SELECT COUNT(*) FROM " + tableName + " WHERE " + commentFieldName + " = \"" + comment + "\"";
cursor = db.rawQuery(query, null);
cursor.moveToFirst();
if (cursor.getInt(0) > 1) {
return true;
}
return false;
} finally {
if (cursor != null) {
cursor.close();
}
db.close();
doh.close();
}
}
}
Update:
If I run test the second time it is passed because in database exists item added by previous test.
I recommend to use use parametrized statement, your approach is danger and not much clear.
Also much better is use getCount() method.
String query = "SELECT COUNT(*) FROM " + tableName + " WHERE columnName = ?";
cursor = db.rawQuery(query, new Sring[] {comment});
int count = 0;
if (cursor.getCount() > 0) {
cursor.moveToFirst();
count = cursor.getInt(0);
}
if (count > 0) {
return true;
}
else {
return false;
}
in where clasue use 'string' instead of "string".....
"SELECT COUNT(*) FROM " + tableName + " WHERE " + commentFieldName + " = '" + comment + "'";

Categories

Resources