My device doesnt recognize my DB where my emulator does - android

When I try to query using my db in the femulator it works perfectly, but given the same appliction and same varibales into the device (milestone) it seems like the DB is not recognized.
I think the key to solving it is to understand where on the device we store the db.
On the emulator it's on /data/data/com.countryCityGame/databases/test1.db
But when I am using the device itself it must be in another place, does someone know where?
This is the java code where I build the DB:
public static void main(String[] args) throws Exception {
String CITIES[] = city.split(",");
String ANIMEL[] = animel.split(",");
String CELEB[] = UK_CELEB.split(",");
String Nature[] = vegtablesAndFruiets.split(",");
String V[][] = {COUNTRIES,CITIES,ANIMEL,Nature,occupations,CELEB};
String []TypeNames = {"Country","City","Animels","Nature","Occupation","Celeb"};
Class.forName("org.sqlite.JDBC");
Connection conn = DriverManager.getConnection("jdbc:sqlite:test1.db");
Statement stat = conn.createStatement();
//stat.executeUpdate("drop table if exists "+"android_metadata"+";");
stat.executeUpdate("create table android_metadata (\"locale\" TEXT DEFAULT 'en_US');");
//PreparedStatement prep1 = conn.prepareStatement(
// "insert into "+"android_metadata"+" values (?);");
//prep1.setString(1, "en_US") ;
//prep1.addBatch();
stat.executeUpdate("drop table if exists "+TABLE_NAME+";");
//stat.executeUpdate("create table "+TABLE_NAME+" (name, occupation);");
stat.executeUpdate("create table "+TABLE_NAME+" ("+VALUE+" TEXT NOT NULL,"+TYPE+" TEXT NOT NULL,"+LETTER+" TEXT NOT NULL,"+counter+" INTEGER);");
PreparedStatement prep = conn.prepareStatement(
"insert into "+TABLE_NAME+" values (?,?,?,?);");
//private void insertToTalble();
int j=0,i=0;
try{
for(j = 0 ;j < V.length; j++)
for (i = 0 ;i < V[j].length ; i++)
{
if (V[j][i] != null)
{
V[j][i] = asUpperCaseFirstChar(V[j][i]);
Character c = V[j][i].charAt(0);
prep.setString(3, c.toString());
}
prep.setString(1, V[j][i]);
prep.setString(2, TypeNames[j]);
prep.setInt(4,0);
prep.addBatch();
}
}catch(Exception e) {
System.out.println("***********"+i+"***************");
}
conn.setAutoCommit(false);
prep.executeBatch();
// prep1.executeBatch();
conn.setAutoCommit(true);
ResultSet rs = stat.executeQuery("select * from "+TABLE_NAME+";");
while (rs.next()) {
System.out.println("country name = " + rs.getString(VALUE));
System.out.println("type = " + rs.getString(TYPE));
System.out.println("letter = " + rs.getString(LETTER));
System.out.println("********************************");
}
rs.close();
conn.close();
}
and this is the code from where i first get the bug:
private static final String DB_PATH = "/data/data/com.countryCityGame/databases/test1.db";
private static final String DATABASE_NAME = "test1.db";
private static final int DATABASE_VERSION = 1;
private static final String TABLE_NAME = "GameTable";
private static final String VALUE = "value";
private static final String TYPE = "type";
private static final String LETTER = "letter";
public countryCityGameLogic(EditText[] myEditTextArr , Context context) {
points = 0;//init values
Cursor cursor = null ;
this.context = context;
openHelper = new OpenHelper(context);
gameList = new CharSequence [myEditTextArr.length];
for (int i = 0 ; i < myEditTextArr.length; i++){
gameList[i] = myEditTextArr[i].getText();
}
//this.db = openHelper.getWritableDatabase();
try{
db = SQLiteDatabase.openDatabase(DB_PATH , null, SQLiteDatabase.NO_LOCALIZED_COLLATORS/*SQLiteDatabase.CREATE_IF_NECESSARY*/);
//this question
cursor = db.query(TABLE_NAME, new String[] {LETTER}
,LETTER+ " like " + "'%" + "A" +"%'", null, null, null, null);
if ( !cursor.moveToFirst()){
//*****if data base doesnot exist HERE I GOT PROBLEMES****
this.db = openHelper.getWritableDatabase();//make new data base
}
}catch(SQLiteException e){
this.db = openHelper.getWritableDatabase();//make new data base
// for (int i = 0 ; i < ALLVALUES.length ; i++)
// insertValus(ALLVALUES[i],i);
}
NOTICE: In the device I am using /data/data/com.countryCityGame/databases/test1.db, it might not be the path where the appliction is located onto the device I am using.

Related

how to turn two sqlite tables into a JSON object

Is it possible to turn a two table(relational tabel) from sqlite in to a JSON object? I've googling but still cannot find a way to convert those table. So far, i've only manage to turn one table into JSON object. If it's possible, can you tell me how to do it? if it's not, can you give me an alternatives? thanks.
here's the code that turn one table to JSON object:
private JSONArray getResults()
{
Context context = this;
String myPath = String.valueOf(context.getDatabasePath("ekantin1.db"));// Set path to database
String myTable = DatabaseHelper.ORDER_TABLE_NAME;//Set name of table
SQLiteDatabase myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
String searchQuery = "SELECT * FROM " + myTable;
Cursor cursor = myDataBase.rawQuery(searchQuery, null );
JSONArray resultSet = new JSONArray();
cursor.moveToFirst();
while (cursor.isAfterLast() == false) {
int totalColumn = cursor.getColumnCount();
JSONObject rowObject = new JSONObject();
for( int i=0 ; i< totalColumn ; i++ )
{
if( cursor.getColumnName(i) != null )
{
try
{
if( cursor.getString(i) != null )
{
Log.d("TAG_NAME", cursor.getString(i) );
rowObject.put(cursor.getColumnName(i) , cursor.getString(i) );
}
else
{
rowObject.put( cursor.getColumnName(i) , "" );
}
}
catch( Exception e )
{
Log.d("TAG_NAME", e.getMessage() );
}
}
}
resultSet.put(rowObject);
cursor.moveToNext();
}
cursor.close();
Log.d("TAG_NAME", resultSet.toString() );
Intent pass_data = new Intent(this,BluetoothOut.class);
pass_data.putExtra("pindah",resultSet.toString());
startActivity(pass_data);
return resultSet;
}
}
And this is my table in my DatabaseHelper :
//tabel order
public static final String ORDER_TABLE_NAME="tb_order";
public static final String COL_1="ORDERID";
public static final String COL_2="USERID";
public static final String COL_3="PASSWORD";
public static final String COL_4="MEJA";
public static final String COL_5="TOPUP";
public static final String COL_6="SALDO";
//tabel lineitems
public static final String LINEITEMS_TABLE_NAME="tb_lineitems";
public static final String COL1 = "FOODID";
public static final String COL2 = "PRICE";
public static final String COL3 = "NUM";
public static final String COL4 = "RES";
public static final String COL6 = "ORDERID_FK";
table line items and orderid related to each other where orderid in tb_order as PK and orderid_fk in tb_lineitems as FK.
A good way to export data from your database is to use Gson, which is Google's Json serialization/deserialization library.
Fetch your Objects from your database like normally, and then use Gson to convert it into Json and export it.
Here is an example of how you could do it.
private void exportDatabase() {
// Create an instance of Gson.
Gson gson = new Gson();
// You can easily convert Objects into Json.
MyItem item = new MyItem();
String json = gson.toJson(item);
// Fetch your items from your database.
ArrayList<MyItems> items = database.getAll();
// Arrays are a bit harder to convert, but not very.
json = gson.toJson(items, new TypeToken<ArrayList<MyItems>>(){}.getType());
// Now export it to some easily copy-pasted location.
System.out.println(json);
}

NOT NULL constraint failed: Facture.Mode

I tried to insert data into table Facture but I received a Crash report on a piece of code :"NOT NULL constraint failed: Facture.Mode (code 1299)".
I didn't find a way ti fix it. Could someone please help me?
There are my logcat.
07-22 13:59:01.565 2471-2471/com.example.pc.myapplication E/SQLiteDatabase: Error inserting U4=100 U1=100 A4=aa Q5=5 Q4=null A3=aaa A5=aa P5=100 P3=100 P4=100 U2=100 Q1=1 P2=100 A1=aa Q2=2 U5=100 Fournisseur=test Q3=3 U3=100 Datefactu=2/07/2018 Numero=123 A2=aaa Mode=null P1=100
android.database.sqlite.SQLiteConstraintException: NOT NULL constraint failed: Facture.Mode (code 1299)
at android.database.sqlite.SQLiteConnection.nativeExecuteForLastInsertedRowId(Native Method)
at android.database.sqlite.SQLiteConnection.executeForLastInsertedRowId(SQLiteConnection.java:782)
at android.database.sqlite.SQLiteSession.executeForLastInsertedRowId(SQLiteSession.java:788)
at android.database.sqlite.SQLiteStatement.executeInsert(SQLiteStatement.java:86)
at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1474)
at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1343)
at com.example.pc.myapplication.DatabaseHelper.insertFacture(DatabaseHelper.java:178)
at com.example.pc.myapplication.facture1.onOKClick(facture1.java:103)
at java.lang.reflect.Method.invoke(Native Method)
at android.view.View$DeclaredOnClickListener.onClick(View.java:4720)
There is my class facture.java :
public void onOKClick ( View v )
{
if (v.getId() == R.id.buttonfacok) {
EditText numero = (EditText)findViewById(R.id.Etnum);
EditText date = (EditText)findViewById(R.id.Etdat);
EditText fournisseur = (EditText)findViewById(R.id.TVfour);
EditText modepaiement = (EditText)findViewById(R.id.TVmode);
EditText article1 = (EditText)findViewById(R.id.A1);
EditText article2 = (EditText)findViewById(R.id.A2);
EditText article3 = (EditText)findViewById(R.id.A3);
EditText article4 = (EditText)findViewById(R.id.A4);
EditText article5 = (EditText)findViewById(R.id.A5);
EditText quantite1 = (EditText)findViewById(R.id.Q1);
EditText quantite2 = (EditText)findViewById(R.id.Q2);
EditText quantite3 = (EditText)findViewById(R.id.Q3);
EditText quantite4 = (EditText)findViewById(R.id.Q4);
EditText quantite5 = (EditText)findViewById(R.id.Q5);
EditText unite1 = (EditText)findViewById(R.id.U1);
EditText unite2 = (EditText)findViewById(R.id.U2);
EditText unite3 = (EditText)findViewById(R.id.U3);
EditText unite4 = (EditText)findViewById(R.id.U4);
EditText unite5 = (EditText)findViewById(R.id.U5);
EditText prix1 = (EditText)findViewById(R.id.P1);
EditText prix2 = (EditText)findViewById(R.id.P2);
EditText prix3 = (EditText)findViewById(R.id.P3);
EditText prix4 = (EditText)findViewById(R.id.P4);
EditText prix5 = (EditText)findViewById(R.id.P5);
String strnumero = numero.getText().toString();
String strdate = date.getText().toString();
String strfournisseur = fournisseur.getText().toString();
String strmodepaiement = modepaiement.getText().toString();
String strarticle1 = article1.getText().toString();
String strarticle2 = article2.getText().toString();
String strarticle3 = article3.getText().toString();
String strarticle4 = article4.getText().toString();
String strarticle5 = article5.getText().toString();
String strquantite1 = quantite1.getText().toString();
String strquantite2 = quantite2.getText().toString();
String strquantite3 = quantite3.getText().toString();
String strquantite4 = quantite4.getText().toString();
String strquantite5 = quantite5.getText().toString();
String strunite1 = unite1.getText().toString();
String strunite2 = unite2.getText().toString();
String strunite3 = unite3.getText().toString();
String strunite4 = unite4.getText().toString();
String strunite5 = unite5.getText().toString();
String strprix1 = prix1.getText().toString();
String strprix2 = prix2.getText().toString();
String strprix3 = prix3.getText().toString();
String strprix4 = prix4.getText().toString();
String strprix5 = prix5.getText().toString();
Facture f = new Facture();
f.setNumero(strnumero);
f.setDatefactu(strdate);
f.setFournisseur(strfournisseur);
f.setMode(strmodepaiement);
f.setA1(strarticle1);
f.setA2(strarticle2);
f.setA3(strarticle3);
f.setA4(strarticle4);
f.setA5(strarticle5);
f.setQ1(strquantite1);
f.setQ2(strquantite2);
f.setQ3(strquantite3);
f.setQ4(strquantite4);
f.setQ5(strquantite5);
f.setU1(strunite1);
f.setU2(strunite2);
f.setU3(strunite3);
f.setU4(strunite4);
f.setU5(strunite5);
f.setP1(strprix1);
f.setP2(strprix2);
f.setP3(strprix3);
f.setP4(strprix4);
f.setP5(strprix5);
helper.insertFacture(f);
}
}
}
There is my databasehelper :
public class DatabaseHelper extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 4 ;
private static final String DATABASE_NAME = "contacts.db" ;
private static final String TABlE_NAME = "contacts" ;
private static final String COLUMN_ID = "id" ;
private static final String COLUMN_NOMETPRENOM = "nometprenom" ;
private static final String COLUMN_CIN = "cin" ;
private static final String COLUMN_MOTDEPASSE = "motdepasse" ;
private static final String TABlE_NAME1 = "Argent" ;
private static final String COLUMN_ENTREE = "Entree" ;
private static final String COLUMN_DATE = "date" ;
private static final String TABlE_NAME2 = "Facture" ;
private static final String COLUMN_NUMERO = "Numero" ;
private static final String COLUMN_DATEFOU = "Datefactu" ;
private static final String COLUMN_FOURNISSEUR = "Fournisseur" ;
private static final String COLUMN_MODE = "Mode" ;
private static final String COLUMN_Article1 = "A1" ;
private static final String COLUMN_Article2 = "A2" ;
private static final String COLUMN_Article3 = "A3" ;
private static final String COLUMN_Article4 = "A4" ;
private static final String COLUMN_Article5 = "A5" ;
private static final String COLUMN_Quantite1 = "Q1" ;
private static final String COLUMN_Quantite2 = "Q2" ;
private static final String COLUMN_Quantite3 = "Q3" ;
private static final String COLUMN_Quantite4 = "Q4" ;
private static final String COLUMN_Quantite5= "Q5" ;
private static final String COLUMN_Unitaire1 = "U1" ;
private static final String COLUMN_Unitaire2 = "U2" ;
private static final String COLUMN_Unitaire3 = "U3" ;
private static final String COLUMN_Unitaire4 = "U4" ;
private static final String COLUMN_Unitaire5 = "U5" ;
private static final String COLUMN_Prix1 = "P1" ;
private static final String COLUMN_Prix2 = "P2" ;
private static final String COLUMN_Prix3 = "P3" ;
private static final String COLUMN_Prix4 = "P4" ;
private static final String COLUMN_Prix5 = "P5" ;
SQLiteDatabase db;
private static final String TABlE_CREATE = "create table contacts ( id integer primary key not null , nometprenom Text not null , cin Text not null , motdepasse Text not null);" ;
private static final String TABlE_CREATE1 = "create table Argent ( id integer primary key not null , date Text not null , Entree Text not null);" ;
private static final String TABlE_CREATE2 = "create table Facture ( id integer primary key not null , Datefactu Text not null , Numero Text not null , Fournisseur Text not null , Mode Text not null , A1 Text not null , A2 Text not null , A3 Text not null , A4 Text not null , A5 Text not null , Q1 Text not null , Q2 Text not null , Q3 Text not null , Q4 Text not null , Q5 Text not null , U1 Text not null , U2 Text not null , U3 Text not null , U4 Text not null , U5 Text not null , P1 Text not null , P2 Text not null , P3 Text not null , P4 Text not null , P5 Text not null);" ;
public DatabaseHelper(Context context)
{
super(context ,DATABASE_NAME , null , DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(TABlE_CREATE2);
this.db=db;
}
public void insertFacture(Facture f)
{
db = this.getWritableDatabase();
ContentValues values = new ContentValues();
String query = "select * from Facture" ;
Cursor cursor = db.rawQuery(query , null) ;
int count = cursor.getCount();
values.put(COLUMN_NUMERO, f.getNumero());
values.put(COLUMN_DATEFOU , f.getDatefactu());
values.put(COLUMN_FOURNISSEUR , f.getFournisseur());
values.put(COLUMN_MODE, f.getMode());
values.put(COLUMN_Article1, f.getA1());
values.put(COLUMN_Article2, f.getA2());
values.put(COLUMN_Article3, f.getA3());
values.put(COLUMN_Article4, f.getA4());
values.put(COLUMN_Article5, f.getA5());
values.put(COLUMN_Quantite1, f.getQ1());
values.put(COLUMN_Quantite2, f.getQ2());
values.put(COLUMN_Quantite3, f.getQ3());
values.put(COLUMN_Quantite4, f.getQ4());
values.put(COLUMN_Quantite5, f.getQ5());
values.put(COLUMN_Unitaire1, f.getU1());
values.put(COLUMN_Unitaire2, f.getU2());
values.put(COLUMN_Unitaire3, f.getU3());
values.put(COLUMN_Unitaire4, f.getU4());
values.put(COLUMN_Unitaire5, f.getU5());
values.put(COLUMN_Prix1, f.getP1());
values.put(COLUMN_Prix2, f.getP2());
values.put(COLUMN_Prix3, f.getP3());
values.put(COLUMN_Prix4, f.getP4());
values.put(COLUMN_Prix5, f.getP5());
db.insert(TABlE_NAME2,null, values);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
String query2 = "DROP TABLE IF EXISTS "+TABlE_NAME2 ;
db.execSQL(query2);
this.onCreate(db);
}
}
Thanks in advance.
Mode's value as per Error inserting U4=100 U1=100 A4=aa Q5=5 Q4=null A3=aaa A5=aa P5=100 P3=100 P4=100 U2=100 Q1=1 P2=100 A1=aa Q2=2 U5=100 Fournisseur=test Q3=3 U3=100 Datefactu=2/07/2018 Numero=123 A2=aaa Mode=null P1=100
is null, you have defined the table so that it cannot be null as per .... , Mode Text not null , .....
You either need to pass a Facture object, to the insertFacture method, that provides, or results in a non-null value being used (which could be to only set the ContentValue for the column if Mode is not null) or you need to remove the not null constraint from the column's definition.
Re comment
#crammeur "Mode" must not be null . I declared as string but no result
When you declare a variable it's value will be null (unless it's a primitive type).
One get around could be to use the following as the insertFacture method :-
public void insertFacture(Facture f) {
db = this.getWritableDatabase();
ContentValues values = new ContentValues();
String query = "select * from Facture" ;
Cursor cursor = db.rawQuery(query , null) ;
int count = cursor.getCount();
values.put(COLUMN_NUMERO, f.getNumero());
values.put(COLUMN_DATEFOU , f.getDatefactu());
values.put(COLUMN_FOURNISSEUR , f.getFournisseur());
if (f.getMode != null ) {
values.put(COLUMN_MODE, f.getMode());
} else {
values.put(COLUMN_MODE,"No mode supplied");
}
values.put(COLUMN_Article1, f.getA1());
values.put(COLUMN_Article2, f.getA2());
values.put(COLUMN_Article3, f.getA3());
values.put(COLUMN_Article4, f.getA4());
values.put(COLUMN_Article5, f.getA5());
values.put(COLUMN_Quantite1, f.getQ1());
values.put(COLUMN_Quantite2, f.getQ2());
values.put(COLUMN_Quantite3, f.getQ3());
values.put(COLUMN_Quantite4, f.getQ4());
values.put(COLUMN_Quantite5, f.getQ5());
values.put(COLUMN_Unitaire1, f.getU1());
values.put(COLUMN_Unitaire2, f.getU2());
values.put(COLUMN_Unitaire3, f.getU3());
values.put(COLUMN_Unitaire4, f.getU4());
values.put(COLUMN_Unitaire5, f.getU5());
values.put(COLUMN_Prix1, f.getP1());
values.put(COLUMN_Prix2, f.getP2());
values.put(COLUMN_Prix3, f.getP3());
values.put(COLUMN_Prix4, f.getP4());
values.put(COLUMN_Prix5, f.getP5());
db.insert(TABlE_NAME2,null, values);
}
This would then use a value of No mode supplied should the value of the getMode method return null. Not necessarily the ideal fix though. The real fix would be ascertain why f.setMode(strmodepaiement); is returning null, which may well be due to the Facture's setMode method setting Mode to null (or not setting Mode at all).

SQLite DB Query

I am building an SQLite DB. One of the tables consists of 2 columns - term and definition.
My question is : How can I query the DB, in order the pair term-definition to be returned in order to be able to insert the data in the activity after that (the term and data are in ExpandableListView, the term is the Key, the data - the value).
Here is the code of the data source so far:
public class TermDataSource extends DAO {
//constants
public static final String TABLE_NAME = "terms";
public static final String TERM = "term";
public static final String DEFINITION = "definition";
//columns in the table
public static final int FIELD_ID_ID = 0;
public static final int FIELD_ID_TERM = 1;
public static final int FIELD_ID_DEFINITION = 2;
public TermDataSource (Context context){
super(context);
}
private String [] selectFields = {_ID, TERM, DEFINITION};
public Cursor getTermsData(){
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_NAME, selectFields, null, null, null, null, null);
return cursor;
}
public List<Term> getTerms(){
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_NAME, selectFields, null, null, null, null, null);
List<Term> terms = new ArrayList<Term>();
if(cursor!=null){
Term term = null;
while(cursor.moveToNext()){
term = getTermFromCursor(cursor);
terms.add(term);
}
cursor.close();
}
db.close();
return terms;
}
private Term getTermFromCursor (Cursor cursor){
Term term = new Term();
term.setTermId(cursor.getInt(FIELD_ID_ID));
term.setTerm(cursor.getString(FIELD_ID_TERM));
term.setDefinition(cursor.getString(FIELD_ID_DEFINITION));
return term;
}
}
Create a folder res>raw and put youfile.csv in that folder.
Use this method to insert data in Your Database from CSV file.
public void insertCSVData(Activity activity, InputStream is, String tableName) {
String colunmNames = null, str1 = null;
open();
try {
BufferedReader buffer = new BufferedReader(new InputStreamReader(is));
String line = "";
String str2 = ");";
db.beginTransaction();
int i = 0;
while ((line = buffer.readLine()) != null) {
i++;
if (i == 1) {
colunmNames = line;
str1 = "INSERT INTO " + tableName + " (" + colunmNames + ") values (";
} else {
StringBuilder sb = new StringBuilder(str1);
String[] str = line.split(",");
for (int h = 0; h < str.length; h++) {
if (h == str.length - 1) {
sb.append("'" + str[h] + "'");
} else {
sb.append("'" + str[h] + "',");
}
}
sb.append(str2);
db.execSQL(sb.toString());
}
}
db.setTransactionSuccessful();
db.endTransaction();
} catch (Exception e) {
close();
e.printStackTrace();
}
close();
}
Call this method by the below code :
insertCSVData(Activity.this, getResources().openRawResource(R.raw.yourfile),"Your Table Name");

Android SQLite: attempt to re-open an already-closed object

I'm trying to get certain book data from my Inventory table based on the ISBN.
However, I'm getting an error: "attempt to re-open an already-closed object". The error only occurs when I click a listView object, go to a different screen, go back to this page via "finish()", and then try to click on another listView object. I moved the String searchEntries[] = InventoryAdapter.getInventoryEntriesByISBN(searchQuery, isbn[position]); from the onClickListener to the previous for loop before the onClickListener and now it works.
Why does it not work if I try to getInventoryEntriesByISBN after returning to this activity from another activity via "finish()"?
The error occurs at SearchResultsScreen:
String searchEntries[] = InventoryAdapter.getInventoryEntriesByISBN(searchQuery, isbn[position]);
and by extension, occurs at InventoryAdapter:
Cursor cursor = db.rawQuery(query, new String[] {ISBN});
SearchResultsScreen.java
// Set up search array
for(int i = 0; i < isbn.length; i++)
{
searchArray.add(new InventoryItem(isbn[i], InventoryAdapter.getTitleAndAuthorByISBN(isbn[i])));
}
Toast.makeText(getApplicationContext(), "searchArray.size()="+searchArray.size(), Toast.LENGTH_LONG).show();
// add data in custom adapter
adapter = new CustomAdapter(this, R.layout.list, searchArray);
ListView dataList = (ListView) findViewById(R.id.list);
dataList.setAdapter(adapter);
// On Click ========================================================
dataList.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
String searchEntries[] = InventoryAdapter.getInventoryEntriesByISBN(searchQuery, isbn[position]);
InventoryAdapter.java (Most relevant parts)
public String[] getInventoryEntriesByISBN(String search, String ISBN)
{
String[] searchEntry = new String [9];
//Query
String query = "select * from INVENTORY where ISBN = ?";
Cursor cursor = db.rawQuery(query, new String[] {ISBN});
if(cursor.getCount()<1) // title Not Exist
{
cursor.close();
for(int i = 0; i < 9; i++)
searchEntry[i] = "Not Found";
return searchEntry;
}
cursor.moveToFirst();
//put data into respective variable
int publish = cursor.getInt(cursor.getColumnIndex("PUBLISH_DATE"));
String publishdate = ((Integer)publish).toString();
String title = cursor.getString(cursor.getColumnIndex("TITLE"));
String author = cursor.getString(cursor.getColumnIndex("AUTHOR"));
String callNumber = cursor.getString(cursor.getColumnIndex("CALL_NUMBER"));
int available = cursor.getInt(cursor.getColumnIndex("AVAILABLE_COUNT"));
String availablecount = ((Integer)available).toString();
int inventory = cursor.getInt(cursor.getColumnIndex("INVENTORY_COUNT"));
String inventorycount = ((Integer)inventory).toString();
int due = cursor.getInt(cursor.getColumnIndex("DUE_PERIOD"));
String dueperiod = ((Integer)due).toString();
int checkoutcount = cursor.getInt(cursor.getColumnIndex("COUNT"));
String count = ((Integer)checkoutcount).toString();
//combine variables into one array
searchEntry[0] = ISBN;
searchEntry[1] = title;
searchEntry[2] = author;
searchEntry[3] = publishdate;
searchEntry[4] = callNumber;
searchEntry[5] = availablecount;
searchEntry[6] = inventorycount;
searchEntry[7] = dueperiod;
searchEntry[8] = count;
cursor.close();
return searchEntry;
}
public String getTitleAndAuthorByISBN(String ISBN)
{
int entriesFound = getNumSearchEntries(ISBN);
if(entriesFound==0)
entriesFound = 1;
String searchEntry;
//Query
String query = "select * from INVENTORY where ISBN = ?";
Cursor cursor = db.rawQuery(query, new String[] {ISBN});
if(cursor.getCount()<1) // title Not Exist
{
cursor.close();
searchEntry = "Not Found";
return searchEntry;
}
cursor.moveToFirst();
//put data into respective variable
String title = cursor.getString(cursor.getColumnIndex("TITLE"));
String author = cursor.getString(cursor.getColumnIndex("AUTHOR"));
//combine variables into one String
searchEntry = title + " / " + author;
//close cursor and return
cursor.close();
return searchEntry;
}
DataBaseHelper.java
public class DataBaseHelper extends SQLiteOpenHelper
{
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "database.db";
// ============================ End Variables ===========================
public DataBaseHelper(Context context, String name, CursorFactory factory, int version)
{
super(context, name, factory, version);
}
public DataBaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// Called when no database exists in disk and the helper class needs
// to create a new one.
#Override
public void onCreate(SQLiteDatabase _db)
{
_db.execSQL(LoginDataBaseAdapter.USER_TABLE_CREATE);
_db.execSQL(CheckOutDataBaseAdapter.CHECKOUT_TABLE_CREATE);
_db.execSQL(InventoryAdapter.INVENTORY_TABLE_CREATE);
_db.execSQL(StatisticsAdapter.STATISTICS_TABLE_CREATE);
}
// Called when there is a database version mismatch meaning that the version
// of the database on disk needs to be upgraded to the current version.
#Override
public void onUpgrade(SQLiteDatabase _db, int _oldVersion, int _newVersion)
{
// Log the version upgrade.
Log.w("TaskDBAdapter", "Upgrading from version " +_oldVersion + " to " +_newVersion + ", which will destroy all old data");
// Upgrade the existing database to conform to the new version. Multiple
// previous versions can be handled by comparing _oldVersion and _newVersion
// values.
// on upgrade drop older tables
_db.execSQL("DROP TABLE IF EXISTS " + LoginDataBaseAdapter.USER_TABLE_CREATE);
_db.execSQL("DROP TABLE IF EXISTS " + CheckOutDataBaseAdapter.CHECKOUT_TABLE_CREATE);
_db.execSQL("DROP TABLE IF EXISTS " + InventoryAdapter.INVENTORY_TABLE_CREATE);
_db.execSQL("DROP TABLE IF EXISTS " + StatisticsAdapter.STATISTICS_TABLE_CREATE);
// Create a new one.
onCreate(_db);
}
}
Check Database Connection before executing query:
if (!dbHelper.db.isOpen())
dbHelper.open();
you can also use cursor.requery(); for again same query.
and in last you have to close the cursor and database also.
cursor.close();
db.close();
Edited:
I have created DBHelper class which extends SQLiteOpenHelper, this class is inner class of DatabaseHelper class and that class have following methods.
/** For OPEN database **/
public synchronized DatabaseHelper open() throws SQLiteException {
dbHelper = new DBHelper(context);
db = dbHelper.getWritableDatabase();
return this;
}
/** For CLOSE database **/
public void close() {
dbHelper.close();
}
If you have still doubt then feel free to ping me. Thank you.
The error only occurs when I click an item, go to a different screen, go back to this page via "finish()", and then try to click on another listView object.
I moved the String searchEntries[] = InventoryAdapter.getInventoryEntriesByISBN(searchQuery, isbn[position]); from the onClickListener to the previous for loop before the onClickListener and now it works.
The correct SearchResultsScreen is below:
SearchResultsScreen.java
// Set up search array
final String Entries[][] = new String[isbn.length][9];
for(int i = 0; i < isbn.length; i++)
{
searchArray.add(new InventoryItem(isbn[i], InventoryAdapter.getTitleAndAuthorByISBN(isbn[i])));
Entries[i] = InventoryAdapter.getInventoryEntriesByISBN(searchQuery, isbn[i]);
}
Toast.makeText(getApplicationContext(), "searchArray.size()="+searchArray.size(), Toast.LENGTH_LONG).show();
// add data in custom adapter
adapter = new CustomAdapter(this, R.layout.list, searchArray);
ListView dataList = (ListView) findViewById(R.id.list);
dataList.setAdapter(adapter);
// On Click ========================================================
dataList.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
String searchEntries[] = Entries[position];
This is your problem
if(cursor.getCount()<1) // title Not Exist
{
cursor.close();
for(int i = 0; i < 9; i++)
searchEntry[i] = "Not Found";
return searchEntry;
}
cursor.moveToFirst();
cursor.close();
Change to
for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
{
String title = cursor.getString(cursor.getColumnIndex("TITLE"));
String author = cursor.getString(cursor.getColumnIndex("AUTHOR"));
//combine variables into one String
searchEntry = title + " / " + author;
}
public String[] getInventoryEntriesByISBN(String search, String ISBN)
{
String[] searchEntry = new String [9];
//Query
String query = "select * from INVENTORY where ISBN = ?";
Cursor cursor = db.rawQuery(query, new String[] {ISBN});
Add SQLiteDatabase db = this.getWritableDatabase(); in this code before executing the raw Query

"Null" appended to database input values from a delimited string

I wonder if someone could show me the error of my ways--I've been struggling with this issue for two days, and realize it must be a fundamental error of initializing variables, but...that reflects the level of my java knowledge.
I'm getting a database result on a delimited string wherein each of the segments has "null" appended to it. It seems that no matter how I change the initialization...well, two days!
I'm declaring the following in the class heading area:
private String strListContent;
private SQLiteDatabase database;
private DatabaseHelper helper2 = new DatabaseHelper(this);
private static final String fields[] = { "_id", "listTitle", "listType",
"listContent", "dateCreated", "dateModified" };
private ArrayList<String> textArray = new ArrayList<String>();
private ArrayList<Integer> imageArray = new ArrayList<Integer>();
Then concatenating my items in
final ImageButton addItem = (ImageButton) findViewById(R.id.btnToAddItem);
addItem.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
itemEdit = (EditText) findViewById(R.id.editTextItem);
if (itemEdit.getText().toString().equals("")) {
showToastMessage("Please enter an item to add...");
} else {
String newListItem = itemEdit.getText().toString();
strListContent += newListItem + "|~|";
...
}}}
I'm using the following bare-bones SQLiteOpenHelper:
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String KEY_ID = "_id";
public DatabaseHelper(Context context) {
super(context, "Cursor", null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE IF NOT EXISTS list_data ("
+ KEY_ID
+ " INTEGER PRIMARY KEY AUTOINCREMENT, listTitle TEXT, listType TEXT, listContent TEXT, dateCreated TEXT, dateModified TEXT)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Steps to upgrade the database for the new version ...
}
}
To insert the values as so:
ImageButton saveAndBack = (ImageButton) findViewById(R.id.btnSaveBack);
saveAndBack.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
String title = null;
String listContent = null;
Calendar javaCalendar = null;
title = titleEdit.getText().toString();
title = (title=="" || title==null)?"Untitled List":title;
strListContent = (strListContent=="" || strListContent==null)?"No Items|~|":strListContent;
listContent = strListContent;
String type = "R"; //"Regular List"
javaCalendar = Calendar.getInstance();
String currentDate = javaCalendar.get(Calendar.MONTH) + "/" + (javaCalendar.get(Calendar.DATE) + 1) + "/" + javaCalendar.get(Calendar.YEAR);
database = helper2.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("listTitle", title);
values.put("listType", type);
values.put("listContent", listContent);
values.put("dateCreated", currentDate);
values.put("dateModified", currentDate);
database.insert("list_data", null, values);
Intent i = new Intent(RegularList.this, ActivityMain.class);
startActivity(i);
}
});
}
//
//End of OnCreate(){}
//
Then, when I retrieve from another activity:
DatabaseHelper helper = new DatabaseHelper(this);
database = helper.getWritableDatabase();
Cursor data = database.query("list_data", fields, null, null, null,
null, null);
Integer tindex = data.getColumnIndex("listTitle");
Integer iindex = data.getColumnIndex("listType");
Integer cindex = data.getColumnIndex("listContent");
itemCount = 0;
for (data.moveToFirst(); !data.isAfterLast(); data.moveToNext()) {
showToastMessage(data.getString(cindex));
titleArrayList.add(data.getString(tindex));
if (data.getString(iindex) == "R") {
imageArrayList.add(R.drawable.listview_regular);
} else if (data.getString(iindex) == "L") {
imageArrayList.add(R.drawable.listview_location);
} else {
imageArrayList.add(R.drawable.listview_regular);
}
itemCount++;
}
data.close();
...
I can see in the toast message that each item from the delimited string has "null" appended to the front of it...the other values are fine. I hope this hasn't been too verbose, but...any recommendations? Thanks!
To me it looks like you may have simply not initialised the String strListContent before you first append to it with:
strListContent += newListItem + "|~|";
When you do that, you'll get a "null" prefixed in front of the value you are trying to append, just as you observe.
Perhaps you can just initialise in the declaration:
private String strListContent = "";

Categories

Resources