Edittext Suggestion on android Studio - java

help me how to fix this code
from AutocompleteTextview i cant see the error code from this part
final String [] myData = myDB.SelectAllData();
final AutoCompleteTextView autoCom = (AutoCompleteTextView)findViewById(R.id.TVresult);
final ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.select_dialog_singlechoice,myData);
autoCom.setAdapter(adapter);
and This Part
public String[] SelectAllData() {
try {
String ArrayData[] = null;
SQLiteDatabase db;
db = this.getReadableDatabase(); // Read Data
String strSQL = "SELECT * FROM " + DB_TABLE_NAME;
Cursor cursor = db.rawQuery(strSQL, null);
if(cursor != null)
{
if (cursor.moveToFirst()) {
ArrayData = new String[cursor.getCount()];
/***
* [x] = Name
*/
int i= 0;
do {
ArrayData[i] = cursor.getString(0);
i++;
} while (cursor.moveToNext());
}
}
cursor.close();
return ArrayData;
} catch (Exception e) {
return null;
}
}
This is my code of MainActivity
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
resulttext = (TextView) findViewById(R.id.TVresult);
rescebu = (TextView) findViewById(R.id.english);
trans = (Button) findViewById(R.id.translate);
respam = (TextView) findViewById(R.id.tagalog);
resilo = (TextView) findViewById(R.id.vis);
resbik = (TextView) findViewById(R.id.ilonngo);
myDB = new DatabaHelper(this);
tts = new TextToSpeech(this, this);
final String [] myData = myDB.SelectAllData();
final AutoCompleteTextView autoCom = (AutoCompleteTextView)findViewById(R.id.TVresult);
final ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.select_dialog_singlechoice,myData);
autoCom.setAdapter(adapter);
autoCom.setThreshold(1);
autoCom.setTextColor(Color.RED);
This is The Dabasehelper and SelectAllData Method
public class DatabaHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "translator4.sqlite";
private static final String DB_TABLE_NAME = "wews";
public DatabaHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
}
public Cursor getAllData(String English, String Tagalog, String Visaya, String Ilonggo) {
SQLiteDatabase db = this.getWritableDatabase();
Cursor res = db.rawQuery("select * from wews where English like '" + English + "' or Tagalog like '" + Tagalog + "' or Visayan like '" + Visaya + "' or Ilonggo like '" + Ilonggo + "';", null);
return res;
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
}
public String[] SelectAllData() {
try {
String ArrayData[] = null;
SQLiteDatabase db;
db = this.getReadableDatabase(); // Read Data
String strSQL = "SELECT * FROM " + DB_TABLE_NAME;
Cursor cursor = db.rawQuery(strSQL, null);
if(cursor != null)
{
if (cursor.moveToFirst()) {
ArrayData = new String[cursor.getCount()];
/***
* [x] = Name
*/
int i= 0;
do {
ArrayData[i] = cursor.getString(0);
i++;
} while (cursor.moveToNext());
}
}
cursor.close();
return ArrayData;
} catch (Exception e) {
return null;
}
}
This is The logs LogCat
Process: application.example.com.myapplication, PID: 20663
Theme: themes:{default=overlay:system, iconPack:system, fontPkg:system, com.android.systemui=overlay:system, com.android.systemui.navbar=overlay:system}
java.lang.RuntimeException: Unable to start activity ComponentInfo{application.example.com.myapplication/application.example.com.myapplication.MainActivity}: java.lang.NullPointerException: storage == null
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2462)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2522)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1363)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5475)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
at de.robv.android.xposed.XposedBridge.main(XposedBridge.java:102)
Caused by: java.lang.NullPointerException: storage == null
at java.util.Arrays$ArrayList.<init>(Arrays.java:38)
at java.util.Arrays.asList(Arrays.java:155)
at android.widget.ArrayAdapter.<init>(ArrayAdapter.java:137)
at application.example.com.myapplication.MainActivity.onCreate(MainActivity.java:56)
at android.app.Activity.performCreate(Activity.java:7125)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1108)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2415)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2522) 
at android.app.ActivityThread.-wrap11(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1363) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:148) 
at android.app.ActivityThread.main(ActivityThread.java:5475) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 
at de.robv.android.xposed.XposedBridge.main(XposedBridge.java:102)

Possible Modification in this code block as you missed to created string object ArrayData[i] = new String() in do...while loop.
public String[] SelectAllData() {
try {
String ArrayData[] = null;
SQLiteDatabase db;
db = this.getReadableDatabase(); // Read Data
String strSQL = "SELECT * FROM " + DB_TABLE_NAME;
Cursor cursor = db.rawQuery(strSQL, null);
if(cursor != null)
{
if (cursor.moveToFirst()) {
ArrayData = new String[cursor.getCount()];
/***
* [x] = Name
*/
int i= 0;
do {
ArrayData[i] = new String();
ArrayData[i] = cursor.getString(0);
i++;
} while (cursor.moveToNext());
}
}
cursor.close();
return ArrayData;
} catch (Exception e) {
return null;
}
}

I'd suggest changing :-
public String[] SelectAllData() {
try {
String ArrayData[] = null;
SQLiteDatabase db;
db = this.getReadableDatabase(); // Read Data
String strSQL = "SELECT * FROM " + DB_TABLE_NAME;
Cursor cursor = db.rawQuery(strSQL, null);
if(cursor != null)
{
if (cursor.moveToFirst()) {
ArrayData = new String[cursor.getCount()];
/***
* [x] = Name
*/
int i= 0;
do {
ArrayData[i] = cursor.getString(0);
i++;
} while (cursor.moveToNext());
}
}
cursor.close();
return ArrayData;
} catch (Exception e) {
return null;
}
}
to :-
public String[] SelectAllData() {
try {
String ArrayData[];
SQLiteDatabase db;
db = this.getReadableDatabase(); // Read Data
String strSQL = "SELECT * FROM " + DB_TABLE_NAME;
Cursor cursor = db.rawQuery(strSQL, null);
ArrayData = new String[cursor.getCount()];
int i = 0;
while (cursor.moveToNext()) {
ArrayData[i++] = cursor.getString(0);
//ArrayData[cursor.getPosition()] = cursor.getString(0); //Could be an alternative
}
cursor.close();
return ArrayData;
} catch (Exception e) {
return new String[0];
}
}
In short, the check for a null cursor is useless it DOES NOT signify no data, rather an empty cursor with a count of 0 is returned when there is no data.
Thus when there is no data cursor.moveToFirst will be false and none of the code within the if will be executed. As such ArrayData will be null (the likely reason for the null pointer exception).
The modified code will return an empty array (0 elements) if there is no data or if there is another exception captured in the try block.
You could also do away with using a counter/index, by using cursor.getPosition(), which is effectively the same (as per commented out line).

Related

Passing string from one MainActivity to another DB Class Java

How to pass a string from a TextView populated from spiner onItemSelected event to make query in DBController class. I can't implement intent:
Main14Activity
Nidd.setText(imc_met.substring(imc_met.lastIndexOf("Id") + 3));
String ado = Nidd.getText().toString();
DBController
String selectQuery = "SELECT * FROM proinfo WHERE Name= " + .... ;
Intent is not working, because I don't know how to get this working. The function getintent(). Returns red in DB class.
Main14Activity Code:
public class Main14Activity extends ListActivity {
TextView lbl;
DBController controller = new DBController(this);
ListView lv;
final Context context = this;
ListAdapter adapter;
ArrayList<HashMap<String, String>> myList;
ArrayList<String> myList1;
Spinner spinner12;
TextView Nidd;
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main142);
lbl = (TextView) findViewById(R.id.txtresulttext);
Nidd = (TextView) findViewById(R.id.Nidd);
lv = getListView();
spinner12 = (Spinner) findViewById(R.id.spinner12);
myList1 = controller.getAllProducts1();
Spinner My_spinner = (Spinner) findViewById(R.id.spinner12);
ArrayAdapter adapter1 = new ArrayAdapter(this, R.layout.spinner_row,
myList1);
My_spinner.setAdapter(adapter1);
controller = new DBController(getApplicationContext());
SQLiteDatabase db = controller.getWritableDatabase();
String tableName = "proinfo";
db.execSQL("delete from " + tableName);
try {
try {
String filename = "/Download/jobtex.csv";
String path = Environment.getExternalStorageDirectory() + filename;
FileReader file = new FileReader(path);
BufferedReader buffer = new BufferedReader(file);
ContentValues contentValues = new ContentValues();
String line = "";
db.beginTransaction();
while ((line = buffer.readLine()) != null) {
String[] str = line.split(",", 3); // defining 3 columns with null or blank field //values acceptance
//Job, Nid
// String company = str[0].toString();
String company = str[0].toString();
String Name = str[1].toString();
// String Price = str[2].toString();
contentValues.put("Company", company);
contentValues.put("Name", Name);
// contentValues.put("Price", Price);
db.insert(tableName, null, contentValues);
lbl.setText("Successfully Updated Database.");
}
db.setTransactionSuccessful();
db.endTransaction();
} catch (IOException e) {
if (db.inTransaction())
db.endTransaction();
Dialog d = new Dialog(this);
d.setTitle(e.getMessage().toString() + "first");
d.show();
// db.endTransaction();
}
myList = controller.getAllProducts();
if (myList.size() != 0) {
ListView lv = getListView();
ListAdapter adapter = new SimpleAdapter(Main14Activity.this, myList,
R.layout.v, new String[]{"Company", "Name"}, new int[]{
R.id.txtproductcompany, R.id.txtproductname});
setListAdapter(adapter);
lbl.setText("Data Imported");
myList1 = controller.getAllProducts1();
My_spinner = (Spinner) findViewById(R.id.spinner12);
adapter1 = new ArrayAdapter(this, R.layout.spinner_row,
myList1);
My_spinner.setAdapter(adapter1);
My_spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
String imc_met = spinner12.getSelectedItem().toString();
Nidd.setText(imc_met.substring(imc_met.lastIndexOf("Id") + 3));
String ado = Nidd.getText().toString();
Fragment fragment = new Fragment();
???????????????
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}
} finally {
}
}
}
DBController: DB Class
public class DBController extends SQLiteOpenHelper {
private static final String LOGCAT = null;
public DBController(Context applicationcontext) {
super(applicationcontext, "PrdouctDB.db", null, 1); // creating DATABASE
Log.d(LOGCAT, "Created");
}
#Override
public void onCreate(SQLiteDatabase database) {
String query;
query = "CREATE TABLE IF NOT EXISTS proinfo ( Id INTEGER PRIMARY KEY, Company TEXT,Name TEXT)";
database.execSQL(query);
}
#Override
public void onUpgrade(SQLiteDatabase database, int version_old,
int current_version) {
String query;
query = "DROP TABLE IF EXISTS proinfo" ;
database.execSQL(query);
onCreate(database);
}
public ArrayList<HashMap<String, String>> getAllProducts() {
ArrayList<HashMap<String, String>> proList;
proList = new ArrayList<HashMap<String, String>>();
String selectQuery = "SELECT * FROM proinfo WHERE Name=" + ??????????????????? ;
SQLiteDatabase database = this.getWritableDatabase();
Cursor cursor = database.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
//Id, Company,Name,Price
HashMap<String, String> map = new HashMap<String, String>();
map.put("Id", cursor.getString(0));
map.put("Company", cursor.getString(1));
map.put("Name", cursor.getString(2));
// map.put("Price", cursor.getString(3));
proList.add(map);
} while (cursor.moveToNext());
}
return proList;
}
public ArrayList<String> getAllProducts1() {
ArrayList<String> proList1;
proList1 = new ArrayList<String>();
String selectQuery = "SELECT * FROM proinfo ";
SQLiteDatabase database = this.getWritableDatabase();
Cursor cursor = database.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
String add = "Job Id";
String as = "Site:";
String space = " ";
proList1.add( as + space + cursor.getString(1) + space + add + space + cursor.getString(2));
} while (cursor.moveToNext());
}
cursor.close();
database.close();
return proList1;
}
}

no such table SQLite error could not compile

i have three classes where the flow is..
entering the entry to be searched: (from MainActivity)
try {
String input = etSearch.getText().toString();
Intent i = new Intent(this, SearchViewList.class);
i.putExtra("input", input);
Log.i("input", input + "");
startActivity(i);
} catch (Exception e) {
// TODO: handle exception
String error = e.toString();
Dialog d = new Dialog(this);
d.setTitle("Row Empty or ID not found!");
TextView tv = new TextView(this);
tv.setText(error);
d.setContentView(tv);
d.show();
break;
}
then the class SearchViewList would display the list by the searched value from the intent
Intent i = getIntent();
input = i.getStringExtra("input");
String l = input;
datasource = new DatabaseHelper(this);
datasource.openDataBase();
List<Definition> values = datasource.getSearchedDefinition(l);
// use the SimpleCursorAdapter to show the
// elements in a ListView
ArrayAdapter<Definition> adapter = new ArrayAdapter<Definition>(this,
android.R.layout.simple_list_item_1, values);
setListAdapter(adapter);
ListView listView = getListView();
listView.setTextFilterEnabled(true);
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// When clicked, show a toast with the TextView text
Toast.makeText(getApplicationContext(),
((TextView) view).getText(), Toast.LENGTH_SHORT).show();
String str = ((TextView) view).getText().toString();
Log.i(str, str + "");
Intent i = new Intent(getApplicationContext(),
SearchedView.class);
i.putExtra("value", str);
startActivity(i);
}
});
then after clicking the searched entry from the list then the error commence
Intent i = getIntent();
l = i.getStringExtra("value");
TextView entry = (TextView) findViewById(R.id.tvEntry);
datasource = new DatabaseHelper(this);
datasource.openDataBase();
String dataEntry = datasource.getEntry(l);
datasource.close();
entry.setText(dataEntry);
}
here is my getEntry() method from the DatabaseHelper class
public String getEntry(String l) throws SQLException {
Cursor c = myDataBase.rawQuery(
"SELECT entry FROM defintionstbl where entry = '"
+ l + "'", null);
if (c != null) {
c.moveToFirst();
if (c.getCount() <= 0) {
return null;
}
String entry = c.getString(0);
return entry;
}
return null;
}
this next method is also from the DatabaseHelper class
public List<Definition> getSearchedDefinition(String l) throws SQLException {
List<Definition> entries = new ArrayList<Definition>();
Cursor cursor = myDataBase.rawQuery(
"SELECT entry FROM definitionstbl where entry like '" + l + "%'", null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
Definition entry = cursorToDefinition(cursor);
entries.add(entry);
cursor.moveToNext();
}
// make sure to close the cursor
cursor.close();
return entries;
}
private Definition cursorToDefinition(Cursor cursor) {
Definition entry = new Definition();
entry.setId(cursor.getLong(0));
entry.setEntry(cursor.getString(0));
return entry;
}
this method compile just fine but the i am getting a "no such table definitionstbl" error from the method getEntry().
additional note:
database = dictionary.sqlite
table = definitionstbl
column1 = _id
column2 = entry
column3 = definitions
here is the code for the copying of the database from an external source:
public class DatabaseHelper extends SQLiteOpenHelper {
// The Android's default system path of your application database.
private static String DB_PATH = "/data/data/com.gtxradeon.newversioncomputerdictionary/databases/";
private static String DB_NAME = "dictionary.sqlite";
private SQLiteDatabase myDataBase;
private final Context myContext;
/**
* Constructor Takes and keeps a reference of the passed context in order to
* access to the application assets and resources.
*
* #param context
*/
public DatabaseHelper(Context context) {
super(context, DB_NAME, null, 1);
this.myContext = context;
}
/**
* Creates a empty database on the system and rewrites it with your own
* database.
* */
public void createDataBase() throws IOException {
boolean dbExist = checkDataBase();
if (dbExist) {
// do nothing - database already exist
} else {
// By calling this method and empty database will be created into
// the default system path
// of your application so we are gonna be able to overwrite that
// database with our database.
this.getReadableDatabase();
try {
copyDataBase();
} catch (IOException e) {
throw new Error("Error copying database");
}
}
}
/**
* Check if the database already exist to avoid re-copying the file each
* time you open the application.
*
* #return true if it exists, false if it doesn't
*/
private boolean checkDataBase() {
SQLiteDatabase checkDB = null;
try {
String myPath = DB_PATH + DB_NAME;
checkDB = SQLiteDatabase.openDatabase(myPath, null,
SQLiteDatabase.OPEN_READONLY);
} catch (SQLiteException e) {
// database does't exist yet.
}
if (checkDB != null) {
checkDB.close();
}
return checkDB != null ? true : false;
}
/**
* Copies your database from your local assets-folder to the just created
* empty database in the system folder, from where it can be accessed and
* handled. This is done by transfering bytestream.
* */
private void copyDataBase() throws IOException {
// Open your local db as the input stream
InputStream myInput = myContext.getAssets().open(DB_NAME);
// Path to the just created empty db
String outFileName = DB_PATH + DB_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();
}
public void openDataBase() throws SQLException {
// Open the database
String myPath = DB_PATH + DB_NAME;
myDataBase = SQLiteDatabase.openDatabase(myPath, null,
SQLiteDatabase.OPEN_READONLY);
}
#Override
public synchronized void close() {
if (myDataBase != null)
myDataBase.close();
super.close();
}
#Override
public void onCreate(SQLiteDatabase db) {
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
create table from MainActivity
try {
myDbHelper.createDataBase();
myDbHelperTrivia.createDataBase();
Log.i("CREATING", "DATABASE CREATED");
} catch (Exception e) {
Log.i("CREATE", "Exception Caught! ", e);
}
try {
myDbHelper.openDataBase();
Log.i("OPENING", "DATABASE OPENED");
} catch (SQLException e) {
Log.i("OPEN", "Exception Caught! ", e);
}
thanks for helping guys but i just changed the getEntry method to this.. rawQuery gave alot of error but this new method is good to go..
public String getEntry(String l) throws SQLException {
String[] columns = new String[] { "_id",
"entry", "definition" };
Cursor c = myDataBase.query("definitionstbl", columns,
"entry" + "='" + l + "'", null, null, null, null);
if (c != null) {
c.moveToFirst();
if (c.getCount() <= 0) {
return null;
}
String entry = c.getString(1);
return entry;
}
return null;
}

Getting contact name from contact list

I'm trying to get name of Contact List from phone's contacts list, I have error on first line of try: ContentResolver cr = ContactFragment.getActivity().getContentResolver();
Any help?
ContactFragment.java
private String refreshData() {
String namedata = "";
try {
/**************************************************/
ContentResolver cr = ContactFragment.getActivity().getContentResolver();
Cursor cursor = cr.query(ContactsContract.Contacts.CONTENT_URI, null,
"DISPLAY_NAME = '" + namedata + "'", null, null);
if (cursor.moveToFirst()) {
String contactId =
cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
//
// Get all phone numbers.
//
Cursor phones = cr.query(Phone.CONTENT_URI, null,
Phone.CONTACT_ID + " = " + contactId, null, null);
while (phones.moveToNext()) {
String number = phones.getString(phones.getColumnIndex(namedata));
phones.close();
}
}
}
Try Like This :
Set this tag in manifest file:
<uses-permission android:name="android.permission.READ_CONTACTS" />
Try this code :
Cursor cursor = null;
try {
cursor = context.getContentResolver().query(Phone.CONTENT_URI, null, null, null, null);
int contactIdIdx = cursor.getColumnIndex(Phone._ID);
int nameIdx = cursor.getColumnIndex(Phone.DISPLAY_NAME);
int phoneNumberIdx = cursor.getColumnIndex(Phone.NUMBER);
int photoIdIdx = cursor.getColumnIndex(Phone.PHOTO_ID);
cursor.moveToFirst();
do {
String idContact = cursor.getString(contactIdIdx);
String name = cursor.getString(nameIdx);
String phoneNumber = cursor.getString(phoneNumberIdx);
//...
} while (cursor.moveToNext());
} catch (Exception e) {
e.printStackTrace();
} finally {
if (cursor != null) {
cursor.close();
}
}

get others column value on onItemSelected in Android

My Tbl_Driver have 3 columns _id,Driver_Code,Driver_Name
How do i able to get the Driver_Name when the Spinner OnItemSelected, because The Spinner will only show Driver_Code
public void DriverDatabaseConn(){
DataBaseHelper myDbHelper = new DataBaseHelper(this.getApplicationContext());
myDbHelper = new DataBaseHelper(this);
try {
myDbHelper.createDataBase();
} catch (IOException ioe) {
throw new Error("Unable to create database");
}
try {
myDbHelper.openDataBase();
}catch(SQLException sqle){
throw sqle;
}
SQLiteDatabase db = myDbHelper.getReadableDatabase();
//SQLiteDatabase db = SQLiteDatabase.openDatabase("/data/data/com.example.abc2/databases/DB_BusData", null, 0);
Cursor c = db.rawQuery("SELECT * FROM Tbl_Driver", null);
//=====Add Additional=====
MatrixCursor extras = new MatrixCursor(new String[] { "_id", "Driver_Code" , "Driver_Name"});
extras.addRow(new String[] { "-1", "< Select Driver Code >","< Select Driver >" });
//extras.addRow(new String[] { "-2", "Empty Template","BB" });
Cursor[] cursors = { extras, c };
c = new MergeCursor(cursors);
//===========================
startManagingCursor(c);
//create an array to specify which fields we want to display
String[] from = new String[]{"Driver_Code"};
//create an array of the display item we want to bind our data to
int[] to = new int[]{android.R.id.text1};
//create simple cursor adapter
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, android.R.layout.simple_spinner_item, c, from, to );
adapter.setDropDownViewResource( android.R.layout.simple_spinner_dropdown_item );
//get reference to our spinner
Spinner s = (Spinner) findViewById( R.id.DriverSpin);
s.setAdapter(adapter);
s.setOnItemSelectedListener(
new OnItemSelectedListener() {
public void onItemSelected(
AdapterView<?> parent, View view, int position, long id) {
Spinner s = (Spinner) findViewById( R.id.DriverSpin);
TextView textView = (TextView)s.getSelectedView();
String result = textView.getText().toString();
Log.d(null,"Spinner1: position=" + result + " id=" + id);
global.Driver_ID = id;
global.Driver_Code = result;
// at here how i can get the Driver_Name column's value at here?
}
public void onNothingSelected(AdapterView<?> parent) {
Log.d(null,"Spinner1: unselected");
}
});
//db.close();
//myDbHelper.close(); //cannot close, otherwise after logout the spinner will blank
}
DataBaseHelper.java
package com.example.abc2;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
public class DataBaseHelper extends SQLiteOpenHelper{
//The Android's default system path of your application database.
private static String DB_PATH = "/data/data/com.example.abc2/databases/";
private static String DB_NAME = "DB_BusData";
private SQLiteDatabase myDataBase;
private final Context myContext;
/**
* Constructor
* Takes and keeps a reference of the passed context in order to access to the application assets and resources.
* #param context
*/
public DataBaseHelper(Context context) {
super(context, DB_NAME, null, 1);
this.myContext = context;
}
/**
* Creates a empty database on the system and rewrites it with your own database.
* */
public void createDataBase() throws IOException{
boolean dbExist = checkDataBase();
if(dbExist){
//do nothing - database already exist
}else{
//By calling this method and empty database will be created into the default system path
//of your application so we are gonna be able to overwrite that database with our database.
this.getReadableDatabase();
try {
copyDataBase();
} catch (IOException e) {
throw new Error("Error copying database");
}
}
}
/**
* Check if the database already exist to avoid re-copying the file each time you open the application.
* #return true if it exists, false if it doesn't
*/
private boolean checkDataBase(){
SQLiteDatabase checkDB = null;
try{
String myPath = DB_PATH + DB_NAME;
checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
}catch(SQLiteException e){
//database does't exist yet.
}
if(checkDB != null){
checkDB.close();
}
return checkDB != null ? true : false;
}
/**
* Copies your database from your local assets-folder to the just created empty database in the
* system folder, from where it can be accessed and handled.
* This is done by transfering bytestream.
* */
private void copyDataBase() throws IOException{
//Open your local db as the input stream
InputStream myInput = myContext.getAssets().open(DB_NAME);
// Path to the just created empty db
String outFileName = DB_PATH + DB_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();
}
public void openDataBase() throws SQLException{
//Open the database
String myPath = DB_PATH + DB_NAME;
myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
}
#Override
public synchronized void close() {
if(myDataBase != null)
myDataBase.close();
super.close();
}
#Override
public void onCreate(SQLiteDatabase db) {
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
// Add your public helper methods to access and get content from the database.
// You could return cursors by doing "return myDataBase.query(....)" so it'd be easy
// to you to create adapters for your views.
}
I have rewrite your DatabaseHelpe and a Test Activity:
public class DataBaseHelper {
private static final String DB_NAME = "DB_BusData";
public static final String TABLE_NAME = "Tbl_Driver";
private Context context;
private String path;
private SQLiteDatabase database;
private boolean isInitializing = false;
public DataBaseHelper(Context context) {
this.context = context;
this.path = context.getDatabasePath(DB_NAME).getAbsolutePath();
if (TextUtils.isEmpty(this.path)) {
throw new IllegalArgumentException("database can't be null");
}
}
public SQLiteDatabase getReadableDatabase() {
synchronized (this) {
checkAndCopyDatabase();
return getDatabaseLocked(false);
}
}
/**
* Attention:just support readable database until now
*
* #return
*/
public SQLiteDatabase getWriteableDatabase() {
synchronized (this) {
checkAndCopyDatabase();
return getDatabaseLocked(true);
}
}
private void checkAndCopyDatabase() {
File file = new File(this.path);
if (file.exists() && file.length() > 0) {
Log.d("TAG", "db already exist");
} else {
try {
InputStream is = context.getAssets().open(DB_NAME);
copyStreamToFile(is, new File(this.path));
} catch (IOException e) {
e.printStackTrace();
}
}
}
private static final void copyStreamToFile(InputStream inputStream, File file) {
ensureDir(file);
FileOutputStream fos = null;
try {
fos = new FileOutputStream(file);
byte[] buffer = new byte[2048];
int read = 0;
while ((read = inputStream.read(buffer)) > 0) {
fos.write(buffer, 0, read);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
quietClose(inputStream);
quietClose(fos);
}
}
private static final void ensureDir(File file) {
if (file != null && (file = file.getParentFile()) != null && !file.exists()) {
file.mkdirs();
}
}
private static final void quietClose(final Closeable closeable) {
if (closeable != null) {
try {
closeable.close();
} catch (final IOException e) {
}
}
}
private SQLiteDatabase getDatabaseLocked(boolean writeable) {
if (this.database != null) {
if (!this.database.isOpen()) {
database = null;
} else if (!writeable || !database.isReadOnly()) {
return database;
}
}
if (isInitializing) {
throw new IllegalArgumentException("getDatabase called recursively");
}
SQLiteDatabase db = this.database;
try {
isInitializing = true;
if (db != null && writeable && db.isReadOnly()) {
if (db.isOpen()) {
db.close();
}
db = null;
}
try {
db = SQLiteDatabase.openDatabase(this.path, null,
writeable ? SQLiteDatabase.OPEN_READWRITE : SQLiteDatabase.OPEN_READONLY);
} catch (SQLiteException e) {
e.printStackTrace();
}
this.database = db;
return db;
} finally {
isInitializing = false;
if (db != null && db != database) {
db.close();
}
}
}
public static class Driver implements BaseColumns {
long id;
String code;
String name;
static final String CODE_CLOMN_NAME = "Driver_Code";
static final String NAME_CLOMN_Name = "Driver_Name";
#Override
public String toString() {
return name;
}
}
public List<Driver> queryAllDriver() {
List<Driver> drivers = null;
SQLiteDatabase db = getReadableDatabase();
if (db != null) {
Cursor cursor = null;
try {
cursor = db.query(TABLE_NAME, null, null, null, null, null, null);
if(cursor != null && cursor.moveToFirst()) {
do {
final long id = cursor.getLong(cursor.getColumnIndex(Driver._ID));
final String code = cursor.getString(cursor.getColumnIndex(Driver.CODE_CLOMN_NAME));
final String name = cursor.getString(cursor.getColumnIndex(Driver.NAME_CLOMN_Name));
Driver driver = new Driver();
driver.id = id;
driver.code = code;
driver.name = name;
if(drivers == null)
drivers = new ArrayList<DataBaseHelper.Driver>();
drivers.add(driver);
} while(cursor.moveToNext());
}
} catch (SQLiteException e) {
e.printStackTrace();
} finally {
if(cursor != null)
cursor.close();
}
db.close();
}
return drivers;
}
}
The DB open and operation code is above, then I write a Test Activity:
public class MainActivity extends Activity implements OnItemSelectedListener {
private List<Driver> drivers;
private Spinner spinner;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
spinner = (Spinner) findViewById(R.id.spinner);
spinner.setOnItemSelectedListener(this);
new DBTask().execute();
}
class DBTask extends AsyncTask<Void, Void, List<Driver>> {
#Override
protected List<Driver> doInBackground(Void... params) {
DataBaseHelper dbHelper = new DataBaseHelper(MainActivity.this);
return dbHelper.queryAllDriver();
}
#Override
protected void onPostExecute(List<Driver> result) {
bindSpinner(result);
}
}
private void bindSpinner(List<Driver> drivers) {
this.drivers = drivers != null ? drivers : new ArrayList<DataBaseHelper.Driver>(0);
ArrayAdapter<Driver> adapter = new ArrayAdapter<DataBaseHelper.Driver>(this,
android.R.layout.simple_spinner_item, this.drivers);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if (this.spinner != null && position >= 0 && position < this.drivers.size()) {
Driver driver = drivers.get(position);
Toast.makeText(this, "selected: driver=" + driver.name + ", code=" + driver.code,
Toast.LENGTH_SHORT).show();
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
Toast.makeText(this, "nothing selected", Toast.LENGTH_SHORT).show();
}
}
The Test Activity is works fine for me, I use the database that I simulated. I think you can't store spinner item in database, how many item in spinner? 10? 100 ? 1000?
You can move query data outside DataBaseHelper.java like this:
private List<Driver> queryAllDriver() {
List<Driver> drivers = null;
DataBaseHelper helper = new DataBaseHelper(this);
SQLiteDatabase db = helper.getReadableDatabase();
if (db != null) {
Cursor cursor = null;
try {
cursor = db.query(DataBaseHelper.TABLE_NAME, null, null, null, null, null, null);
if(cursor != null && cursor.moveToFirst()) {
do {
final long id = cursor.getLong(cursor.getColumnIndex(Driver._ID));
final String code = cursor.getString(cursor.getColumnIndex(Driver.CODE_CLOMN_NAME));
final String name = cursor.getString(cursor.getColumnIndex(Driver.NAME_CLOMN_Name));
Driver driver = new Driver();
driver.id = id;
driver.code = code;
driver.name = name;
if(drivers == null)
drivers = new ArrayList<DataBaseHelper.Driver>();
drivers.add(driver);
} while(cursor.moveToNext());
}
} catch (SQLiteException e) {
e.printStackTrace();
} finally {
if(cursor != null)
cursor.close();
}
db.close();
}
return drivers;
}

Android App working on Emulator but crashes at launch on device

I have read through thousands of pages and have yet to find a solution. I am relatively new at Android Development and this is the first time I am deploying any kind of app on a mobile device and my problem is that the application runs on my emulator flawlessly, but on my device it crashes at launch. I have kind of pin pointed the error as to being related to accessing data from the database I am packaging with the app.
Basically, my first activity calls a function to retrieve airport codes from the DB. It gets to the function in my DBContext file and returns an error:
0java.lang.RuntimeException: Unable to start activity ComponentInfo{com.maziz.POS/com.maziz.POS.Login}: java.lang.NullPointerException
1at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1647)
2at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
3at android.app.ActivityThread.access$1500(ActivityThread.java:117)
4at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
5at android.os.Handler.dispatchMessage(Handler.java:99)
6at android.os.Looper.loop(Looper.java:130)
7at android.app.ActivityThread.main(ActivityThread.java:3683)
8at java.lang.reflect.Method.invokeNative(Native Method)
9at java.lang.reflect.Method.invoke(Method.java:507)
10at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
11at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
12at dalvik.system.NativeStart.main(Native Method) Caused by: java.lang.NullPointerException
13at com.maziz.POS.POSContext.getAirportCodes(POSContext.java:178)
14at com.maziz.POS.Login.onCreate(Login.java:29)
15at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
16at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
17... 11 more
FirstActivity: Login.java
package com.maziz.POS;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.bugsense.trace.BugSenseHandler;
public class Login extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Creates instance of all Global Vars
// GlobalVars gv = (GlobalVars) getApplicationContext();
BugSenseHandler.setup(this, "00728e23");
GlobalVars gv = (GlobalVars) getApplicationContext();
Cursor cc = gv.db.getAirportCodes();
while(cc.moveToNext())
{
for (int i = 0; i < cc.getColumnCount(); i++) {
gv.Airport_Codes.add(cc.getString(i));
}
}
final EditText txtUserID = (EditText) findViewById(R.id.txtUserID);
final EditText txtPassword = (EditText) findViewById(R.id.txtPassword);
Button btnLogin = (Button) findViewById(R.id.btnLogin);
btnLogin.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String userID = txtUserID.getText().toString();
String password = txtPassword.getText().toString();
if (checkLogin(userID, password)) {
Toast.makeText(getApplicationContext(), "Logging in...",
Toast.LENGTH_SHORT).show();
Intent intent = new Intent(v.getContext(),
FASelection.class);
startActivity(intent);
} else {
AlertDialog.Builder ad = new AlertDialog.Builder(Login.this);
ad.setMessage("Login Not Successful");
ad.setNeutralButton("OK",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(),
"Re-Enter Your Info...",
Toast.LENGTH_SHORT).show();
}
});
ad.show();
}
}
});
}
public boolean checkLogin(String u, String p) {
GlobalVars gv = (GlobalVars) getApplicationContext();
Cursor c = gv.db.getUser(u);
User temp = new User();
temp.setUserID(c.getString(c.getColumnIndex("Employee_ID")));
temp.setPassword(c.getString(c.getColumnIndex("Password")));
boolean exists = false;
if(c == null)
return false;
if (temp.UserID.equalsIgnoreCase(u)) {
if (temp.Password.equals(p)) {
gv.user = temp;
gv.PK_Login_Log = (int) gv.db.insertLoginLogInfo(u, 1000);
return true;
} else
exists = false;
}
return exists;
}
}
Then This is my POSContext(DB Context Class):
package com.maziz.POS;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class POSContext extends SQLiteOpenHelper{
//The Android's default system path of your application database.
private static String DB_PATH = "/data/data/com.maziz.POS/databases/";
private static String DB_NAME = "AndroidPOS.sqlite";
private SQLiteDatabase myDataBase;
private final Context myContext;
/**
* Constructor
* Takes and keeps a reference of the passed context in order to access to the application assets and resources.
* #param context
*/
public POSContext(Context context) {
super(context, DB_NAME, null, 1);
this.myContext = context;
}
/**
* Creates a empty database on the system and rewrites it with your own database.
* */
public void createDataBase() throws IOException{
boolean dbExist = checkDataBase();
if(dbExist){
//do nothing - database already exist
}else{
//By calling this method and empty database will be created into the default system path
//of your application so we are gonna be able to overwrite that database with our database.
this.getReadableDatabase();
try {
copyDataBase();
} catch (IOException e) {
throw new Error("Error copying database");
}
}
}
/**
* Check if the database already exist to avoid re-copying the file each time you open the application.
* #return true if it exists, false if it doesn't
*/
private boolean checkDataBase(){
File dbFile = new File(DB_PATH + DB_NAME);
return dbFile.exists();
/* SQLiteDatabase checkDB = null;
try{
String myPath = DB_PATH + DB_NAME;
checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
}catch(SQLiteException e){
//database does't exist yet.
}
if(checkDB != null){
checkDB.close();
}
return checkDB != null ? true : false;*/
}
/**
* Copies your database from your local assets-folder to the just created empty database in the
* system folder, from where it can be accessed and handled.
* This is done by transfering bytestream.
* */
private void copyDataBase() throws IOException{
//Open your local db as the input stream
InputStream myInput = myContext.getAssets().open(DB_NAME);
// Path to the just created empty db
String outFileName = DB_PATH + DB_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[2048];
int length;
while ((length = myInput.read(buffer))>0){
myOutput.write(buffer, 0, length);
}
//Close the streams
myOutput.flush();
myOutput.close();
myInput.close();
}
public void openDataBase() throws SQLException{
//Open the database
String myPath = DB_PATH + DB_NAME;
myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);
}
#Override
public synchronized void close() {
if(myDataBase != null)
myDataBase.close();
super.close();
}
#Override
public void onCreate(SQLiteDatabase db) {
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
// Add your public helper methods to access and get content from the database.
// You could return cursors by doing "return myDataBase.query(....)" so it'd be easy
// to you to create adapters for your views.
public Cursor getUser(String uID)
{
Cursor mCursor = myDataBase.query(true, "FA_Login", new String[] {
"PK_FA_Login", "Airline_ID", "Employee_ID", "Password"},
"Employee_ID = '" + uID + "'", null, null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
public Cursor getAirportCodes()
{
Cursor mCursor = myDataBase.query("Airport_Codes", new String[] {
"Airport_Code"
}, null, null, null, null, "Airport_Code");
return mCursor;
}
public Cursor getFlightByOriginDestination(String origin, String dest)
{
Cursor mCursor = myDataBase.query("Inventory_Flight_Schedule", new String[] {
"PK_Inventory_Flight_Schedule", "Flight_Number", "AC_Type", "Time", "Origin", "Destination"
}, "Origin = '" + origin + "' AND Destination = '" + dest + "'", null, null, null, null);
return mCursor;
}
public Cursor getFlightByFlightNumber(String fn)
{
if(fn.equals(""))
fn = "0";
Cursor mCursor = myDataBase.query("Inventory_Flight_Schedule", new String[] {
"PK_Inventory_Flight_Schedule", "Flight_Number", "AC_Type", "Time", "Origin", "Destination"
}, "Flight_Number = " + fn, null, null, null, null);
return mCursor;
}
public Cursor getProductsOnFlight(int pk)
{
Cursor mCursor = myDataBase.query("Inventory_Scheduled", new String[] {
"PK_Product_ID", "Quantity"
}, "PK_Inventory_Flight_Schedule = " + pk, null, null, null, null);
return mCursor;
}
public String getProductCategory(int pk)
{
String c = "";
Cursor mCursor = myDataBase.query("Product_Category_Assigned", new String[] {
"PK_Product_ID", "PK_Category_ID"
}, "PK_Product_ID = " + pk, null, null, null, null);
while (mCursor.moveToNext())
{
c = c + " " + mCursor.getString(mCursor.getColumnIndex("Category_Name"));
}
return c;
}
public Cursor getProductDetailsByProductID(int pID)
{
Cursor mCursor = myDataBase.query("Products", new String[] {
"Product_Description", "Product_Name", "Price", "ImageUri"
}, "PK_Product_ID = " + pID, null, null, null, null);
return mCursor;
}
public ArrayList<Product> getProductSalesDetail(int pkss)
{
ArrayList<Product> productSales = new ArrayList<Product>();
Product temp;
Cursor p = myDataBase.query("Sales_Details", new String[] {
"PK_Product_ID", "Quantity"
}, "PK_Sales_Summary = " + pkss, null, null, null, null);
while(p.moveToNext())
{
int pkproduct = Integer.parseInt(p.getString(p.getColumnIndex("PK_Product_ID")));
Cursor product = getProductDetailsByProductID(pkproduct);
product.moveToFirst();
temp = new Product();
temp.PK_Product_ID = pkproduct;
temp.QuantityInCart = Integer.parseInt(p.getString(p.getColumnIndex("Quantity")));
temp.Product_Name = product.getString(product.getColumnIndex("Product_Name"));
temp.Price = product.getDouble(product.getColumnIndex("Price"));
temp.ImageUri = product.getString(product.getColumnIndex("ImageUri"));
productSales.add(temp);
}
return productSales;
}
public ArrayList<Product> getProductSales(ArrayList<Integer> pkss)
{
ArrayList<Product> productSales = new ArrayList<Product>();
for(int pk: pkss)
{
Cursor p = myDataBase.query("Sales_Details", new String[] {
"PK_Product_ID", "Quantity"
}, "PK_Sales_Summary = " + pk, null, null, null, null);
while(p.moveToNext())
{
int pkproduct = Integer.parseInt(p.getString(p.getColumnIndex("PK_Product_ID")));
Cursor product = getProductDetailsByProductID(pkproduct);
product.moveToFirst();
Product temp;
if(productSales.isEmpty())
{
temp = new Product();
temp.PK_Product_ID = pkproduct;
temp.Quantity = Integer.parseInt(p.getString(p.getColumnIndex("Quantity")));
temp.Product_Name = product.getString(product.getColumnIndex("Product_Name"));
temp.Price = product.getDouble(product.getColumnIndex("Price"));
temp.ImageUri = product.getString(product.getColumnIndex("ImageUri"));
productSales.add(temp);
}
else //if product list is not empty
{
temp = new Product();
boolean inList = false;
for(Product pp: productSales)
{
if(pp.PK_Product_ID == pkproduct)
{
inList = true;
temp.Quantity = temp.Quantity + Integer.parseInt(p.getString(p.getColumnIndex("Quantity")));
break;
}
}
if(!inList)
{
temp.PK_Product_ID = pkproduct;
temp.Quantity = Integer.parseInt(p.getString(p.getColumnIndex("Quantity")));
temp.Product_Name = product.getString(product.getColumnIndex("Product_Name"));
temp.Price = product.getDouble(product.getColumnIndex("Price"));
temp.ImageUri = product.getString(product.getColumnIndex("ImageUri"));
productSales.add(temp);
}
else
{
for(int i = 0; i < productSales.size(); i++)
{
Product pp = productSales.get(i);
if(pp.PK_Product_ID == pkproduct)
{
productSales.get(i).Quantity = productSales.get(i).Quantity + Integer.parseInt(p.getString(p.getColumnIndex("Quantity")));
}
}
}
}
}
}
return productSales;
}
public ArrayList<SalesTransaction> getSalesData(int FlightNumber, String currentDate)
{
Cursor salesData;
ArrayList<Integer> pkflights = new ArrayList<Integer>();
ArrayList<SalesTransaction> st = new ArrayList<SalesTransaction>();
currentDate = currentDate.trim();
String select = "Select PK_Flight_Selected From Flight_Selected Where Flight_Number = '" + FlightNumber + "'";
Cursor mCursor = myDataBase.rawQuery(select, null);
/*myDataBase.query("Flight_Selected", new String[] {
"PK_Flight_Selected"
}, "Flight_Number = " + FlightNumber + " AND Flight_Date = '" + currentDate + "'", null, null, null, null);
*/
while (mCursor.moveToNext())
{
pkflights.add(Integer.parseInt(mCursor.getString(mCursor.getColumnIndex("PK_Flight_Selected"))));
}
for(int i: pkflights)
{
salesData = myDataBase.query("Sales_Summary", new String[] {
"PK_Sales_Summary", "PK_Flight_Selected", "Employee_ID", "Total_Items", "Total_Amount"
}, "PK_Flight_Selected = " + i , null, null, null, null);
while(salesData.moveToNext())
{
SalesTransaction temp = new SalesTransaction();
temp.PK_Sales_Summary = Integer.parseInt(salesData.getString(salesData.getColumnIndex("PK_Sales_Summary")));
temp.PK_Flight_Selected = Integer.parseInt(salesData.getString(salesData.getColumnIndex("PK_Flight_Selected")));
temp.EmployeeID = salesData.getString(salesData.getColumnIndex("Employee_ID"));
temp.items = Integer.parseInt(salesData.getString(salesData.getColumnIndex("Total_Items")));
temp.amount = Double.parseDouble(salesData.getString(salesData.getColumnIndex("Total_Amount")));
Cursor salest = myDataBase.query("Sales_Transactions", new String[] {
"PK_Sales_Transaction", "CC_Name"
}, "PK_Sales_Summary = " + temp.PK_Sales_Summary, null, null, null, null);
while(salest.moveToNext())
{
temp.PK_Sales_Transaction = Integer.parseInt(salest.getString(salest.getColumnIndex("PK_Sales_Transaction")));
temp.CC_Name = salest.getString(salest.getColumnIndex("CC_Name"));
}
st.add(temp);
}
}
return st;
}
public long insertFlightSelectedRecord(int airline_ID, int flight_Number, String o, String d, String fd, String ac)
{
ContentValues cv = new ContentValues();
cv.put("Airline_ID", airline_ID);
cv.put("Flight_Number", flight_Number);
cv.put("Origin", o);
cv.put("Dest", d);
cv.put("Flight_Date", fd.toString());
cv.put("AC_Type", ac);
return myDataBase.insert("Flight_Selected", null, cv);
}
public long insertLoginLogInfo(String e, int device)
{
Date date = new Date();
ContentValues cv = new ContentValues();
cv.put("Employee_ID", e);
cv.put("Login_TimeStamp", date.toString());
cv.put("Device_ID", device);
return myDataBase.insert("FA_Login_Log", null, cv);
}
public long insertSalesSummary(int pk_flight, String EmployeeID, double total_items, double Amount)
{
ContentValues cv = new ContentValues();
cv.put("PK_Flight_Selected", pk_flight);
cv.put("Employee_ID", EmployeeID);
cv.put("Total_Items", total_items);
cv.put("Total_Amount", Amount);
return myDataBase.insert("Sales_Summary", null, cv);
}
public long insertSalesDetails(int pk_salessummary, int pID, int q)
{
ContentValues cv = new ContentValues();
cv.put("PK_Sales_Summary", pk_salessummary);
cv.put("PK_Product_ID", pID);
cv.put("Quantity", q);
return myDataBase.insert("Sales_Details", null, cv);
}
public long insertSalesTransaction(int pkss, double amount, String cctype, String ccnumber, int cccode, String ccName)
{
ContentValues cv = new ContentValues();
cv.put("PK_Sales_Summary", pkss);
cv.put("Amount", amount);
cv.put("CC_Type", cctype);
cv.put("CC_Number", ccnumber);
cv.put("CC_Code", cccode);
cv.put("CC_Name", ccName);
return myDataBase.insert("Sales_Transactions", null, cv);
}
public boolean updateLoginLog(int pk, int pkflight)
{
ContentValues cv = new ContentValues();
cv.put("PK_Flight_Selected", pkflight);
return myDataBase.update("FA_Login_Log", cv, "PK_FA_Login_Log = " + pk, null) > 0;
}
}
The error seems to be occurring in the getAirportCode method in POSContext.
Any help would be GREATLY appreciated.
Thanks!
EDIT:
after further debugging I installed Catlog and this is the error in real time:
03-23 12:34:12.468 I/ActivityManager(1296): Start proc com.maziz.POS for activity com.maziz.POS/.Login: pid=6250 uid=10051 gids={3003}
03-23 12:34:12.546 I/Database(6250): sqlite returned: error code = 0, msg = Recovered 3 frames from WAL file /data/data/com.maziz.POS/databases/AndroidPOS.sqlite-wal
03-23 12:34:12.546 E/Database(6250): sqlite_prepare_v2(handle, "pragma journal_mode=WAL;") failed for "/data/data/com.maziz.POS/databases/AndroidPOS.sqlite"
03-23 12:34:12.554 E/Database(6250): at com.maziz.POS.POSContext.openDataBase(POSContext.java:135)
03-23 12:34:12.554 E/Database(6250): at com.maziz.POS.GlobalVars.onCreate(GlobalVars.java:32)
03-23 12:34:12.562 W/System.err(6250): at com.maziz.POS.POSContext.openDataBase(POSContext.java:135)
03-23 12:34:12.562 W/System.err(6250): at com.maziz.POS.GlobalVars.onCreate(GlobalVars.java:32)
03-23 12:34:12.625 D/BugSenseHandler(6250): Looking for exceptions in: /data/data/com.maziz.POS/files
03-23 12:34:12.656 D/BugSenseHandler(6250): Transmitting stack trace: java.lang.RuntimeException: Unable to start activity ComponentInfo{com.maziz.POS/com.maziz.POS.Login}: java.lang.NullPointerException
03-23 12:34:12.656 D/BugSenseHandler(6250): at com.maziz.POS.POSContext.getAirportCodes(POSContext.java:178)
03-23 12:34:12.656 D/BugSenseHandler(6250): at com.maziz.POS.Login.onCreate(Login.java:29)
03-23 12:34:14.648 D/BugSenseHandler(6250): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.maziz.POS/com.maziz.POS.Login}: java.lang.NullPointerException
03-23 12:34:14.648 D/BugSenseHandler(6250): at com.maziz.POS.POSContext.getAirportCodes(POSContext.java:178)
03-23 12:34:14.648 D/BugSenseHandler(6250): at com.maziz.POS.Login.onCreate(Login.java:29)
03-23 12:34:14.648 E/AndroidRuntime(6250): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.maziz.POS/com.maziz.POS.Login}: java.lang.NullPointerException
03-23 12:34:14.648 E/AndroidRuntime(6250): at com.maziz.POS.POSContext.getAirportCodes(POSContext.java:178)
03-23 12:34:14.648 E/AndroidRuntime(6250): at com.maziz.POS.Login.onCreate(Login.java:29)
03-23 12:34:15.492 W/ActivityManager(1296): Force finishing activity com.maziz.POS/.Login
03-23 12:34:16.000 W/ActivityManager(1296): Activity pause timeout for HistoryRecord{407109b8 com.maziz.POS/.Login}
03-23 12:34:17.320 I/ActivityManager(1296): Process com.maziz.POS (pid 6250) has died.
03-23 12:34:17.718 E/AnrParser(1432): Deleted file/data/anr/anrlogs/ANR_com.maziz.POS_20120323-123414.log
03-23 12:34:17.718 E/AnrParser(1432): Deleted file/data/anr/anrlogs/com.maziz.POS-logcat.log
03-23 12:34:26.148 W/ActivityManager(1296): Activity destroy timeout for HistoryRecord{407109b8 com.maziz.POS/.Login}
The only object that can generate a NullPointerException in getAirportCodes is myDataBase. You should check in openDataBase if the file really exists. I also noticed you are having a constant for database path. Maybe that is not correct on your device.
To check for your application's database path use getDatabasePath, see link bellow.
http://developer.android.com/reference/android/content/ContextWrapper.html#getDatabasePath(java.lang.String)

Categories