I keep getting the error message Close() was never explicitly called on database. From what I've read I'm not closing the database once the activity is destroyed, but I don't know how to implement it:
Database Helper:
public class ResultsDatabase extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "results.db";
private static final int DATABASE_VERSION = 2;
public static final String TABLE_NAME = "results";
public static final String _ID = BaseColumns._ID;
public static final String SAVED_NAME = "name";
public static final String COLUMN_NAME_CREATE_DATE = "date";
public static final String RIGHT_EAR = "right_ear";
public static final String LEFT_EAR = "left_ear";
public ResultsDatabase(Context context) {
// calls the super constructor, requesting the default cursor factory.
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + TABLE_NAME + " ("
+ _ID + " INTEGER PRIMARY KEY,"
+ SAVED_NAME + " TEXT,"
+ COLUMN_NAME_CREATE_DATE + " INTEGER,"
+ RIGHT_EAR + " BLOB,"
+ LEFT_EAR + " BLOB"
+ ");");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion){
}
public void storeResults(String name, List<EarSrt> leftAnswerList, List<EarSrt> rightAnswerList){
SQLiteDatabase db = getWritableDatabase();
ContentValues values = new ContentValues();
values.put(SAVED_NAME, name);
Long now = Long.valueOf(System.currentTimeMillis());
values.put(COLUMN_NAME_CREATE_DATE, now);
values.put(RIGHT_EAR, serializeObject(rightAnswerList ));
values.put(LEFT_EAR, serializeObject(leftAnswerList ));
db.insert(TABLE_NAME, null, values);
}
public static byte[] serializeObject(Object o) {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
ObjectOutput out = new ObjectOutputStream(bos);
out.writeObject(o);
out.close();
// Get the bytes of the serialized object
byte[] buf = bos.toByteArray();
return buf;
} catch(IOException ioe) {
Log.e("serializeObject", "error", ioe);
return null;
}
}
public static Object deserializeObject(byte[] b) {
try {
ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(b));
Object object = in.readObject();
in.close();
return object;
} catch(ClassNotFoundException cnfe) {
Log.e("deserializeObject", "class not found error", cnfe);
return null;
} catch(IOException ioe) {
Log.e("deserializeObject", "io error", ioe);
return null;
}
}
}
I call this helper in my Tabbed Results Activity which displays the data in two different fragments as follows:
public class TabbedResultsActivity extends SherlockFragmentActivity{
TabHost mTabHost;
TabManager mTabManager;
public static final String IS_RIGHT_EAR = "is_right_ear";
private ArrayList<EarSrt> leftAnswerList;
private ArrayList<EarSrt> rightAnswerList;
private final static String TAG = "HearingTest";
private boolean isRightEarTab = true;
private boolean bothEarsBad;
private boolean leftEarBad;
private boolean rightEarBad;
#SuppressWarnings("unchecked")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tab_layout);
ActionBar ab = this.getSupportActionBar();
SherlockHelper.setupActionBar(ab, this);
View infoButton = findViewById(R.id.info_button);
infoButton.setVisibility(View.VISIBLE);
Intent intent = getIntent();
int rowId = intent.getIntExtra(ResultsDatabase._ID, -1);
if ( rowId != -1 ) {
ResultsDatabase db = new ResultsDatabase(this);
String select = "(" + ResultsDatabase._ID + " == " + rowId + ")";
Cursor c = db.getReadableDatabase().query(ResultsDatabase.TABLE_NAME, null, select, null, null, null,null);
if ( c.moveToFirst() ) {
int leftEarColumn = c.getColumnIndex(ResultsDatabase.LEFT_EAR);
byte[] leftEarByteArray = c.getBlob(leftEarColumn);
int rightEarColumn = c.getColumnIndex(ResultsDatabase.RIGHT_EAR);
byte[] rightEarByteArray = c.getBlob(rightEarColumn);
leftAnswerList = (ArrayList<EarSrt>) ResultsDatabase.deserializeObject(leftEarByteArray);
rightAnswerList = (ArrayList<EarSrt>) ResultsDatabase.deserializeObject(rightEarByteArray);
}
} else {
byte[] leftEarByteArray = getIntent().getByteArrayExtra(ResultsDatabase.LEFT_EAR);
byte[] rightEarByteArray = getIntent().getByteArrayExtra(ResultsDatabase.RIGHT_EAR);
leftAnswerList = (ArrayList<EarSrt>) ResultsDatabase.deserializeObject(leftEarByteArray);
rightAnswerList = (ArrayList<EarSrt>) ResultsDatabase.deserializeObject(rightEarByteArray);
}
isRightEarTab = getIntent().getBooleanExtra(IS_RIGHT_EAR, true);
GraphView graphView = new GraphView(this);
graphView.setPoints(rightAnswerList);
float leftAverage = calculateAverage(rightAnswerList);
graphView.setAverage(leftAverage);
graphView.setPoints(leftAnswerList);
float rightAverage = calculateAverage(leftAnswerList);
graphView.setAverage(rightAverage);
setResults(leftAnswerList, rightAnswerList);
String results = setResultCaption(bothEarsBad, leftEarBad, rightEarBad).toString();
Log.d(TAG, "The results were " + results);
Bundle leftbundle = new Bundle();
leftbundle.putString("results", results);
leftbundle.putParcelableArrayList("graph", leftAnswerList);
leftbundle.putFloat("average", leftAverage);
Bundle rightbundle = new Bundle();
rightbundle.putString("results", results);
rightbundle.putParcelableArrayList("graph", rightAnswerList);
rightbundle.putFloat("average", rightAverage);
mTabHost = (TabHost)findViewById(android.R.id.tabhost);
mTabHost.setup();
mTabManager = new TabManager(this, mTabHost, R.id.realtabcontent);
mTabManager.addTab(mTabHost.newTabSpec(getString(R.string.Left_ear)).setIndicator(getString(R.string.Left_ear)),
LeftEarResults.class, leftbundle);
mTabManager.addTab(mTabHost.newTabSpec("contacts").setIndicator(getString(R.string.Right_ear)),
RightEarResults.class, rightbundle);
if (savedInstanceState != null) {
mTabHost.setCurrentTabByTag(savedInstanceState.getString("tab"));
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putString("tab", mTabHost.getCurrentTabTag());
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
return MenuActivity.createMenu(this, menu);
}
private float calculateAverage(List<EarSrt> steps) {
float srt = 0.0f;
int length = steps.size();
for (int i = (int)Math.ceil( (float)length/(float)2); i < length; i++) {
EarSrt es = steps.get(i);
srt += es.getSrt();
}
srt = srt / (length-(float)Math.ceil( (float)length/(float)2));
return srt;
}
private void setResults(List<EarSrt> leftEar, List<EarSrt> rightEar) {
float esLeft = calculateAverage(leftEar);
float esRight = calculateAverage(rightEar);
leftEarBad = (esLeft > 24.0);
rightEarBad = (esRight > 24.0);
bothEarsBad = (leftEarBad && rightEarBad);
}
private StringBuilder setResultCaption(boolean bothEarsBad, boolean leftEarBad, boolean rightEarBad) {
String resultCaption;
StringBuilder resultsText = new StringBuilder();
if (bothEarsBad) {
resultsText.append(getString(R.string.The_test_indicates_a_possible_hearing_loss));
resultsText.append(getString(R.string.We_recommend_that_you_visit_a_Hearing_Care_Professional_for_a_comprehensive_hearing_check));
}else{
if (leftEarBad) {
resultsText.append(getString(R.string.The_test_indicates_a_possible_hearing_loss_for_your_left_ear));
resultsText.append(getString(R.string.We_recommend_that_you_visit_a_Hearing_Care_Professional_for_a_comprehensive_hearing_check));
} else if (rightEarBad) {
resultsText.append(getString(R.string.The_test_indicates_a_possible_hearing_loss_for_your_Right_ear));
resultsText.append(getString(R.string.We_recommend_that_you_visit_a_Hearing_Care_Professional_for_a_comprehensive_hearing_check));
}else {
resultsText.append(getString(R.string.There_is_no_indication_of_hearing_loss));
}
}
resultsText.append(getString(R.string.The_results_of_the_hearing_test_are_not_to_be_utilized_as_an_official_outcome_for_assessing_levels_of_hearing_loss_True_hearing_loss_assessments_can_only_be_determined_by_a_licensed_hearing_healthcare_provider));
Log.d(TAG, "The results were " + resultsText);
return resultsText;
}
public void infoView(View aView) {
Intent intent = new Intent(this, InfoActivity.class);
startActivity(intent);
}
}
My quesiton is how and where should I close the connection?
Thanks
Just alter your storeResults method as follows
public void storeResults(String name, List<EarSrt> leftAnswerList, List<EarSrt> rightAnswerList){
SQLiteDatabase db = getWritableDatabase(); // opens the database connection
try {
ContentValues values = new ContentValues();
values.put(SAVED_NAME, name);
Long now = Long.valueOf(System.currentTimeMillis());
values.put(COLUMN_NAME_CREATE_DATE, now);
values.put(RIGHT_EAR, serializeObject(rightAnswerList ));
values.put(LEFT_EAR, serializeObject(leftAnswerList ));
db.insert(TABLE_NAME, null, values);
}
catch(Exception e) {
e.printStackTrace();
// furher error handling
}
finally {
db.close(); // closes the database every time after access
}
}
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I am new in Java Programming.
Now, I am facing the problem that I want to change the shared preferences and want to use the SQLite database to store these data. I had created the table for store these data and I am trying to save these data in SQLite.
How can I do? Anyone can help me ????
MyDatabase-Table
This is my code that using shared preferences :
public class Login extends AppCompatActivity {
InputStream inputStream;
ACDatabase db;
SharedPreferences prefs;
ActivityLoginBinding binding;
AC_Class.Connection connection;
AC_Class.Register reg;
String versionNo;
String url;
String urlStr;
String id;
String pwd;
private static String uniqueID = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
binding = DataBindingUtil.setContentView(this, R.layout.activity_login);
getSupportActionBar().hide();
// Placeholder
versionNo = "3.1.6";
reg = new AC_Class.Register();
connection = new AC_Class.Connection();
binding.setConSettings(connection);
db = new ACDatabase(this);
// Check preferences/create if nonexistent
prefs = this.getSharedPreferences("com.presoft.androidmobilestock", Context.MODE_PRIVATE);
uniqueID = prefs.getString("UUID", null);
if (uniqueID == null)
{
uniqueID = UUID.randomUUID().toString();
//uniqueID = "3FDE9813F93A47CBA6CD4F5DAAECEE01";
prefs.edit().putString("UUID", uniqueID).commit();
}
binding.lblUUID.setText(uniqueID);
binding.lblVersion.setText(versionNo);
if (prefs.getString("ID", id) != null) {
binding.rmbCheckBox.setChecked(true);
url = prefs.getString("URL", url);
binding.txtURL.setText(prefs.getString("URLstr", urlStr));
binding.txtID.setText(prefs.getString("ID", id));
binding.txtpw.setText(prefs.getString("pwd", pwd));
}
if (prefs.getString("Default_curr", null) == null) {
prefs.edit().putString("Default_curr", "RM").apply();
}
if (prefs.getString("Default_loc", null) == null) {
Cursor tempCursor = db.getLocation();
if (tempCursor.moveToNext()) {
prefs.edit().putString("Default_loc", tempCursor
.getString(tempCursor.getColumnIndex("Location"))).apply();
}
}
// Version number
if (prefs.getString("Version ", null) == null) {
prefs.edit().putString("Version", versionNo).apply();
}
// Tax Inclusive
if (!prefs.getBoolean("taxInclusive", false)) {
prefs.edit().putBoolean("taxInclusive", false).apply();
}
if (Build.MODEL.equals("HC720"))
{
Snackbar.make(findViewById(android.R.id.content), "RFID Detected.", Snackbar.LENGTH_SHORT).show();
}
}
#Override
public void onBackPressed() {
finish();
}
//On return of intent
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == 7) {
url = data.getStringExtra("URLKey");
urlStr = data.getStringExtra("URLStr");
Log.i("custDebug", url + ", " + urlStr);
binding.txtURL.setText(urlStr);
if (!TextUtils.isEmpty(binding.txtURL.getText().toString())) {
new GetModules(Login.this).execute(url);
new GetLoginList(Login.this).execute(url);
new SetDevice(Login.this).execute(url);
}
}
}
//Open connection settings
public void btnSetClicked(View view) {
Intent intent = new Intent(Login.this, ConnectionSettings.class);
startActivityForResult(intent, 7);
}
//Reset Database
public void btnResetDbClicked(final View view) {
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Reset DB");
builder.setMessage("Are you sure you want to reset the Database?");
final EditText input = new EditText(this);
input.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
builder.setView(input);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (input.getText().toString().equals("presoftmobile")) {
db.close();
deleteDatabase("AutoCountDatabase");
} else {
// Toast.makeText(getApplicationContext(), "Incorrect Password", Toast.LENGTH_SHORT);
}
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.show();
}
//Login button
public void btnLoginBtnClicked(View view) {
if (TextUtils.isEmpty(binding.txtURL.getText().toString())) {
binding.txtURL.setError("This field can't be blank.");
//return;
}
if (TextUtils.isEmpty(binding.txtID.getText().toString())) {
binding.txtID.setError("This field can't be blank.");
//return;
}
if (TextUtils.isEmpty(binding.txtpw.getText().toString())) {
binding.txtpw.setError("This field can't be blank.");
//return;
}
//Non-empty fields
else {
Cursor checkData = db.loginValidate(binding.txtID.getText().toString(),
binding.txtpw.getText().toString().toUpperCase());
if (checkData.getCount() > 0) {
checkData.moveToNext();
//Shared Preferences
prefs.edit().putString("URL", url).apply();
prefs.edit().putString("URLstr", binding.txtURL.getText().toString()).apply();
if (binding.rmbCheckBox.isChecked()) {
prefs.edit().putString("ID", binding.txtID.getText().toString()).apply();
prefs.edit().putString("pwd", binding.txtpw.getText().toString()).apply();
}
prefs.edit().putInt("EnableSetting", checkData.getInt(checkData.getColumnIndex("EnableSetting"))).apply();
prefs.edit().putInt("FilterByAgent", checkData.getInt(checkData.getColumnIndex("FilterByAgent"))).apply();
prefs.edit().putInt("Sales", checkData.getInt(checkData.getColumnIndex("Sales"))).apply();
prefs.edit().putInt("Purchase", checkData.getInt(checkData.getColumnIndex("Purchase"))).apply();
prefs.edit().putInt("Transfer", checkData.getInt(checkData.getColumnIndex("Transfer"))).apply();
if (url != null) {
try {
// Check Connection
new SetDevice(Login.this).execute(url);
// Go to main
Intent intent = new Intent(Login.this, Dashboard.class);
intent.putExtra("URLKey", url);
intent.putExtra("URLStr", binding.txtURL.getText().toString());
startActivity(intent);
finish();
} catch (Exception e) {
Log.i("custDebug", e.getMessage());
Toast.makeText(this, "Unable to connect to server", Toast.LENGTH_SHORT).show();
}
}
} else {
Toast.makeText(this, "Invalid login credentials", Toast.LENGTH_SHORT).show();
binding.txtpw.setText(null);
}
checkData.close();
}
}
This is the code that to save the data in SQLite database (but getting error):
public class Login extends AppCompatActivity {
InputStream inputStream;
ACDatabase db;
SharedPreferences prefs;
ActivityLoginBinding binding;
AC_Class.Connection connection;
AC_Class.Register reg;
String versionNo;
String url;
String urlStr;
String id;
String pwd;
private static String uniqueID = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
binding = DataBindingUtil.setContentView(this, R.layout.activity_login);
getSupportActionBar().hide();
// Placeholder
versionNo = "3.1.6";
connection = new AC_Class.Connection();
binding.setConSettings(connection);
db = new ACDatabase(this);
db = new ACDatabase(this);
uniqueID = db.getReg("8");
uniqueID = prefs.getString("UUID", null);
if (uniqueID == null)
{
uniqueID = UUID.randomUUID().toString();
//uniqueID = "3FDE9813F93A47CBA6CD4F5DAAECEE01";
db.updateREG("8", uniqueID);
}
binding.lblUUID.setText(uniqueID);
binding.lblVersion.setText(versionNo);
if (prefs.getString("ID", id) != null) {
binding.rmbCheckBox.setChecked(true);
url = prefs.getString("URL", url);
binding.txtURL.setText(prefs.getString("URLstr", urlStr));
binding.txtID.setText(prefs.getString("ID", id));
binding.txtpw.setText(prefs.getString("pwd", pwd));
}
if (prefs.getString("Default_curr", null) == null) {
prefs.edit().putString("Default_curr", "RM").apply();
}
if (prefs.getString("Default_loc", null) == null) {
Cursor tempCursor = db.getLocation();
if (tempCursor.moveToNext()) {
prefs.edit().putString("Default_loc", tempCursor
.getString(tempCursor.getColumnIndex("Location"))).apply();
}
}
// Version number
if (prefs.getString("Version ", null) == null) {
prefs.edit().putString("Version", versionNo).apply();
}
// Tax Inclusive
if (!prefs.getBoolean("taxInclusive", false)) {
prefs.edit().putBoolean("taxInclusive", false).apply();
}
if (Build.MODEL.equals("HC720"))
{
Snackbar.make(findViewById(android.R.id.content), "RFID Detected.", Snackbar.LENGTH_SHORT).show();
}
}
mydatabasehelper
//GET value by id
public Cursor getReg(String id) {
SQLiteDatabase db = this.getWritableDatabase();
Cursor data = db.rawQuery("SELECT Value FROM " + TABLE_NAME_REG + " WHERE ID ='" + id + "'",null);
return data;
}
//update value
public boolean updateREG(String ID, String Value) {
SQLiteDatabase database = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put("Value", Value);
String[] args = new String[]{ID};
database.update("Reg", cv, "ID = ?", args);
return true;
}
The following is a working example that acts very similar to shared prefs but stores the prefs in an SQLite database.
The table is very simple 2 columns. The key (name of the stored value) and the value itself. Which can be String, boolean, int, long or Float.
It includes methods to; insert (add) a key/value pair, update a key/value pair and to get a value according to the key and also to return a default value as passed (making it easy to detect if the value was retrieved).
The DatabaseHelper (sub class of SQLiteOpenHelper) has most of the code and is :-
class DBHelper extends SQLiteOpenHelper {
private static volatile DBHelper instance = null;
private SQLiteDatabase db = null;
public static final String DBNAME = "sharedpreferences.db";
public static final int DBVERSION = 1;
public static final String TBLNAME_SP = "_shared_preferences";
public static final String COLNAME_SP_KEY = "_key";
public static final String COLNAME_SP_VALUE = "_value";
private DBHelper(#Nullable Context context) {
super(context, DBNAME, null, DBVERSION);
db = this.getWritableDatabase();
}
public static DBHelper getInstance(Context context) {
if (instance == null) {
instance = new DBHelper(context);
}
return instance;
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE IF NOT EXISTS " + TBLNAME_SP +
"(" +
COLNAME_SP_KEY + " PRIMARY KEY," +
COLNAME_SP_VALUE + " TEXT" +
")");
}
#Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
}
private long insertPrefsRow(ContentValues cv, String key) {
cv.put(COLNAME_SP_KEY,key);
return db.insertWithOnConflict(TBLNAME_SP,null,cv, SQLiteDatabase.CONFLICT_IGNORE);
}
public long insertPrefsValue (String key, int value) {
ContentValues cv = new ContentValues();
cv.put(COLNAME_SP_VALUE,value);
return insertPrefsRow(cv,key);
}
public long insertPrefsValue (String key, String value) {
ContentValues cv = new ContentValues();
cv.put(COLNAME_SP_VALUE,value);
return insertPrefsRow(cv,key);
}
public long insertPrefsValue (String key, long value) {
ContentValues cv = new ContentValues();
cv.put(COLNAME_SP_VALUE,value);
return insertPrefsRow(cv,key);
}
public long insertPrefsValue (String key, boolean value) {
ContentValues cv = new ContentValues();
cv.put(COLNAME_SP_VALUE,value);
return insertPrefsRow(cv,key);
}
public long insertPrefsValue (String key, float value) {
ContentValues cv = new ContentValues();
cv.put(COLNAME_SP_VALUE,value);
return insertPrefsRow(cv,key);
}
private long updatePrefs(String key, ContentValues cv) {
return db.update(TBLNAME_SP,cv,COLNAME_SP_KEY + "=?",new String[]{key} );
}
public long updatePrefsStringValue(String key, String newValue) {
ContentValues cv = new ContentValues();
cv.put(COLNAME_SP_VALUE,newValue);
return updatePrefs(key,cv);
}
public long updatePrefsStringValue(String key, boolean newValue) {
ContentValues cv = new ContentValues();
cv.put(COLNAME_SP_VALUE,newValue);
return updatePrefs(key,cv);
}
public long updatePrefsStringValue(String key, int newValue) {
ContentValues cv = new ContentValues();
cv.put(COLNAME_SP_VALUE,newValue);
return updatePrefs(key,cv);
}
public long updatePrefsStringValue(String key, long newValue) {
ContentValues cv = new ContentValues();
cv.put(COLNAME_SP_VALUE,newValue);
return updatePrefs(key,cv);
}
public long updatePrefsStringValue(String key, Float newValue) {
ContentValues cv = new ContentValues();
cv.put(COLNAME_SP_VALUE,newValue);
return updatePrefs(key,cv);
}
private Cursor getPrefsValue(String key) {
return db.query(TBLNAME_SP,new String[]{COLNAME_SP_VALUE},COLNAME_SP_KEY + "=?",new String[]{key},null,null,null);
}
public String getPrefsStringValue(String key, String default_value) {
String rv = default_value;
Cursor csr;
if ((csr = getPrefsValue(key)).moveToFirst()) {
rv = csr.getString(csr.getColumnIndex(COLNAME_SP_VALUE));
csr.close();
}
return rv;
}
public Boolean getPrefsBooleanValue(String key, boolean default_value ) {
Boolean rv = default_value;
Cursor csr;
if ((csr = getPrefsValue(key)).moveToFirst()) {
rv = csr.getInt(csr.getColumnIndex(COLNAME_SP_VALUE)) != 0;
csr.close();
}
return rv;
}
public int getPrefsIntValue(String key, int default_value) {
int rv = default_value;
Cursor csr;
if ((csr = getPrefsValue(key)).moveToFirst()) {
rv = csr.getInt(csr.getColumnIndex(COLNAME_SP_VALUE));
csr.close();
}
return rv;
}
public long getPrefsLongValue(String key, long default_value) {
long rv = default_value;
Cursor csr;
if ((csr = getPrefsValue(key)).moveToFirst()) {
rv = csr.getLong(csr.getColumnIndex(COLNAME_SP_VALUE));
csr.close();
}
return rv;
}
public Float getPrefsFLoatValue(String key, Float default_value) {
Float rv = default_value;
Cursor csr;
if ((csr = getPrefsValue(key)).moveToFirst()) {
rv = csr.getFloat(csr.getColumnIndex(COLNAME_SP_VALUE));
csr.close();
}
return rv;
}
}
The following is an activity that demonstrates usage:-
public class MainActivity extends AppCompatActivity {
DBHelper db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
db = DBHelper.getInstance(this);
db.insertPrefsValue("UUID","3FDE9813F93A47CBA6CD4F5DAAECEE01");
db.insertPrefsValue("taxInclusive",false);
db.insertPrefsValue("myprefs_int",100);
db.insertPrefsValue("myprefs_long",100L);
db.insertPrefsValue("myprefs_float",10.567F);
Log.d("PREFSINFO",
"Stored UUID is " + db.getPrefsStringValue("UUID","000000000000000000000000") +
" Stored taxinclusive is " + db.getPrefsBooleanValue("taxInclusive",true) +
" Stored mpint is " + db.getPrefsIntValue("myprefs_int",-99) +
" Stored mplong is " + db.getPrefsLongValue("myprefs_long",-99999999) +
" Stored mpfloat is " + db.getPrefsFLoatValue("myprefs_float",-999999.999999F) +
" NOT STORED is " + db.getPrefsFLoatValue("NOT A SET KEY",-3333.3333F)
);
db.updatePrefsStringValue("UUID","FFFF9813F93A47CBA6CD4F5DAAECEE01");
Log.d("PREFSINFO",
"Stored UUID is " + db.getPrefsStringValue("UUID","000000000000000000000000") +
" Stored taxinclusive is " + db.getPrefsBooleanValue("taxInclusive",true) +
" Stored mpint is " + db.getPrefsIntValue("myprefs_int",-99) +
" Stored mplong is " + db.getPrefsLongValue("myprefs_long",-99999999) +
" Stored mpfloat is " + db.getPrefsFLoatValue("myprefs_float",-999999.999999F) +
" NOT STORED is " + db.getPrefsFLoatValue("NOT A SET KEY",-3333.3333F)
);
}
}
When run (or rerun BUT when rerun the updated UUID rather than the original is retrieved) the log contains :-
D/PREFSINFO: Stored UUID is 3FDE9813F93A47CBA6CD4F5DAAECEE01 Stored taxinclusive is false Stored mpint is 100 Stored mplong is 100 Stored mpfloat is 10.567 NOT STORED is -3333.3333
D/PREFSINFO: Stored UUID is FFFF9813F93A47CBA6CD4F5DAAECEE01 Stored taxinclusive is false Stored mpint is 100 Stored mplong is 100 Stored mpfloat is 10.567 NOT STORED is -3333.3333
NOT STORED demonstrates the default value being returned when the Key/Name isn't stored.
As you can see UUID has been updated in the second line (if rerun both lines would show the updated value)
I have written an application for Tracker; with a service that runs every 5 minutes. It works fine on Samsung Galaxy J7 Prime (Android 7.0) and Samsung Galaxy Tab A (Android 7.1), But when I run on Lenovo A2010 (Android 5.1), the service does not work. I don't know whether it is my code or my device which is causing the problem.
This is the log from when the service stopped:
10-08 09:01:31.122 721-737/? E/JavaBinder: *** Uncaught remote exception! (Exceptions are not yet supported across processes.)
java.lang.ArrayIndexOutOfBoundsException: length=5; index=5
at com.android.internal.os.BatteryStatsImpl.updateAllPhoneStateLocked(BatteryStatsImpl.java:3321)
at com.android.internal.os.BatteryStatsImpl.notePhoneSignalStrengthLocked(BatteryStatsImpl.java:3351)
at com.android.server.am.BatteryStatsService.notePhoneSignalStrength(BatteryStatsService.java:395)
at com.android.server.TelephonyRegistry.broadcastSignalStrengthChanged(TelephonyRegistry.java:1448)
at com.android.server.TelephonyRegistry.notifySignalStrengthForSubscriber(TelephonyRegistry.java:869)
at com.android.internal.telephony.ITelephonyRegistry$Stub.onTransact(ITelephonyRegistry.java:184)
at android.os.Binder.execTransact(Binder.java:451)
And here is my service, AppService.java:
public class AppService extends Service {
private MyThread thread;
PowerManager.WakeLock wl;
DatabaseHelper myDb;
private static final String tracker = "Tracker";
String result=null,status=null,statusresult=null;
String stusername;
String imeiids;
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (!thread.isAlive()) {
thread.start();
}
return START_STICKY;
}
#Override
public void onDestroy() {
if (thread.isAlive()) {
stopService(new Intent(this, AppService.class));
}
super.onDestroy();
}
#Override
public void onCreate() {
Toast.makeText(AppService.this,"Start...",Toast.LENGTH_SHORT).show();
thread = new MyThread();
myDb = new DatabaseHelper(this);
SharedPreferences shared = getSharedPreferences(tracker, Context.MODE_PRIVATE);
stusername = shared.getString("username", "not found!").toString();
if(ContextCompat.checkSelfPermission(this, android.Manifest.permission.READ_PHONE_STATE)== PackageManager.PERMISSION_GRANTED){
TelephonyManager c=(TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
SharedPreferences.Editor editor = shared.edit();
if(c.getDeviceId()==null){
editor.commit();
}
else{
editor.putString("imeiid", c.getDeviceId());
editor.commit();
}
}
}
private class MyThread extends Thread {
private static final String tag = "Sevice Demo";
private static final int delay = 60000;//60000=30sec/1minute
private int roundNumber = 0;
private boolean finishService = false;
#Override
public void run() {
while (true) {
PowerManager pm = (PowerManager) getApplicationContext().getSystemService(
getApplicationContext().POWER_SERVICE);
wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "My Tag");
wl.acquire();
if(ContextCompat.checkSelfPermission(AppService.this, android.Manifest.permission.READ_PHONE_STATE)== PackageManager.PERMISSION_GRANTED){
TelephonyManager c=(TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
imeiids = c.getDeviceId();
}
if(imeiids== null){
SharedPreferences shared = getSharedPreferences(tracker, Context.MODE_PRIVATE);
imeiids=shared.getString("imeiid", "").toString();
}
Date current = Calendar.getInstance().getTime();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
final String currentDateandTime = sdf.format(current);
if(!stusername.equals("not found!")){
//////////////////////////////////// Open GPS //////////////////////////////////////
int off=0;
try {
off = Settings.Secure.getInt(getContentResolver(), Settings.Secure.LOCATION_MODE);
} catch (Settings.SettingNotFoundException e) {
e.printStackTrace();
}
if(off==0){
Intent onGPS = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(onGPS);
}
////////////////////////////////////////////////////////////////////////////////////
Date currentTime = Calendar.getInstance().getTime();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String formattedDateString = formatter.format(currentTime);
SimpleDateFormat formatstr = new SimpleDateFormat("EEE", Locale.US);
final String formattedDayString = formatstr.format(currentTime);
if (!haveNetworkConnection()) {
/*no network connect*/
}
else{
Cursor res = myDb.getDatasync(stusername);
if(res.getCount()==0){
Log.d("dddd", "no data");
}
else{
String datetimes=null,lats=null,longs=null;
res.moveToFirst();
do{
final String ids=res.getString(0);
datetimes=res.getString(1);
lats=res.getString(3);
longs=res.getString(4);
final String finalDatetimes = datetimes;
final String finalLats = lats;
final String finalLongs = longs;
new AsyncTask<Void,Void,Void>(){
#Override
protected Void doInBackground(Void... params) {
String location_url = "http://_____._________/__________/______________________.php";
try {
URL url = new URL(location_url);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
String post_data = URLEncoder.encode("staffcode", "UTF-8") + "=" + URLEncoder.encode(stusername, "UTF-8")+ "&"
+ URLEncoder.encode("dateTime", "UTF-8") + "=" + URLEncoder.encode(finalDatetimes, "UTF-8") + "&"
+ URLEncoder.encode("lat", "UTF-8") + "=" + URLEncoder.encode(finalLats, "UTF-8") + "&"
+ URLEncoder.encode("lon", "UTF-8") + "=" + URLEncoder.encode(finalLongs, "UTF-8") + "&"
+ URLEncoder.encode("imei", "UTF-8") + "=" + URLEncoder.encode(imeiids, "UTF-8") + "&"
+ URLEncoder.encode("app", "UTF-8") + "=" + URLEncoder.encode("T:1.0", "UTF-8");
bufferedWriter.write(post_data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
String line = "";
while ((line = bufferedReader.readLine()) != null) {
result = line;
}
JSONObject jsonObject = new JSONObject(result.toString());
for (int i = 0; i < jsonObject.length(); i++)
{
status=(jsonObject.getString("status")); //Get Status
statusresult=(jsonObject.getString("statusresult"));
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
if(status.equals("success")&& statusresult.equals("success")){
boolean isUpdate = myDb.updateDatasync(ids);
if(isUpdate) {
Log.d("Get Data ", "Updated");
}
else {
Log.d("Get Data ", "not updated");
}
}
else{
}
}
}.execute();
}while(res.moveToNext());
}
}
Cursor res = myDb.getData(stusername);
if (res.getCount() ==0) {
Log.d("dddd", "no data");
}
else {
res.moveToFirst();
do{
String asubstring = String.valueOf(res.getString(1)).substring(11, 16);
String datesub = res.getString(1).substring(0, 10);
if(currentDateandTime.equals(datesub)){ /* Today */ }
else{
//Not Today
if(!res.getString(5).equals("1")) { }
else{ // If Sync = 1 = Sync Success
boolean isDeleteSync = myDb.deleteDataSync(res.getString(0));
if(isDeleteSync) {
Log.d("Log Delete ", "Deleted");
}
else {
Log.d("Log Delete ", "Can't Deleted");
}
}
}
}while(res.moveToNext());
}
if (formattedDayString.equals("Sun")) {
}
else {
String hour = formattedDateString.substring(11, 13);
String minute = formattedDateString.substring(14, 16);
Integer ins = Integer.parseInt(minute);
if (hour.equals("08") || hour.equals("09") || hour.equals("10") || hour.equals("11") || hour.equals("12")
|| hour.equals("13") || hour.equals("14") || hour.equals("15") || hour.equals("16") || hour.equals("17")
|| hour.equals("18")) {
if((hour.equals("18"))&&(ins<=0)){
SimpleDateFormat formatterss = new SimpleDateFormat("HH:mm:ss");
String DateString = formatterss.format(currentTime);
String subtime= DateString.substring(3,5);
Integer minuteif=Integer.parseInt(subtime);
if(minuteif%5==0){
startService(new Intent(AppService.this, GetLocation.class));
}
}
if((!hour.equals("18"))){
SimpleDateFormat formatterss = new SimpleDateFormat("HH:mm:ss");
String DateString = formatterss.format(currentTime);
String subtime= DateString.substring(3,5);
Integer minuteif=Integer.parseInt(subtime);
if(minuteif%5==0){
startService(new Intent(AppService.this, GetLocation.class));
}
}
}
else{
}
}
try {
stopService(new Intent(AppService.this,GetLocation.class));
sleep(delay);
run();
}
catch (InterruptedException e) {
e.printStackTrace();
}
wl.release();
if (finishService) {
return;
}
}
}
}
}
private boolean haveNetworkConnection() {
boolean haveConnectedWifi = false;
boolean haveConnectedMobile = false;
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo[] netInfo = cm.getAllNetworkInfo();
for (NetworkInfo ni : netInfo) {
if (ni.getTypeName().equalsIgnoreCase("WIFI"))
if (ni.isConnected())
haveConnectedWifi = true;
if (ni.getTypeName().equalsIgnoreCase("MOBILE"))
if (ni.isConnected())
haveConnectedMobile = true;
}
return haveConnectedWifi || haveConnectedMobile;
}
}
It's my DatabaseHelper.java
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "Tracker.db";
public static final String TABLE_NAME = "LocationMessenger";
public static final String COL_1 = "ID";
public static final String COL_2 = "DATE";
public static final String COL_3 = "USERNAME";
public static final String COL_4 = "LATITUDE";
public static final String COL_5 = "LONGITUDE";
public static final String COL_6 = "SYNC";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table " + TABLE_NAME +" (ID INTEGER PRIMARY KEY AUTOINCREMENT," +
"DATE TEXT,USERNAME TEXT,LATITUDE TEXT,LONGITUDE TEXT,SYNC TEXT )");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME);
onCreate(db);
}
public boolean insertData(String dates,String username,String latitude,String longitude) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_2,dates);
contentValues.put(COL_3,username);
contentValues.put(COL_4,latitude);
contentValues.put(COL_5,longitude);
contentValues.put(COL_6,"0");
long result = db.insert(TABLE_NAME,null ,contentValues);
if(result == -1) {
return false;
}
else{
return true;
}
}
public boolean insertDataSuccess(String dates,String username,String latitude,String longitude) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_2,dates);
contentValues.put(COL_3,username);
contentValues.put(COL_4,latitude);
contentValues.put(COL_5,longitude);
contentValues.put(COL_6,"1");
long result = db.insert(TABLE_NAME,null ,contentValues);
if(result == -1) {
return false;
}
else{
return true;
}
}
public Cursor getData(String username) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_3,username);
Cursor res = db.rawQuery("select * from "+TABLE_NAME+" where USERNAME= ? ",new String[] { username });
return res;
}
public Cursor getDataforsync(String id) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_3,id);
contentValues.put(COL_6,"0");
Cursor res = db.rawQuery("select * from "+TABLE_NAME+" where ID= ? and SYNC = ?",new String[] { id,"0" });
return res;
}
public Cursor getDatasync(String username) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_3,username);
contentValues.put(COL_6,"0");
Cursor res = db.rawQuery("select * from "+TABLE_NAME+" where USERNAME= ? and SYNC = ?",new String[] { username,"0" });
return res;
}
public boolean deleteData(String id){
SQLiteDatabase db =this.getWritableDatabase();
long rows = db.delete(TABLE_NAME, "ID = ?", new String[] { String.valueOf(id) });
db.close();
if(rows == -1) {
return false;
}
else{
return true;
}
}
public boolean deleteDataSync(String id){
SQLiteDatabase db =this.getWritableDatabase();
long rows = db.delete(TABLE_NAME, "ID = ?", new String[] { id });
db.close();
if(rows == -1) {
return false;
}
else{
return true;
}
}
public boolean updateDatasync(String id){
SQLiteDatabase db =this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_6,"1");
long result = db.update(TABLE_NAME,contentValues,"ID=" + id,null);
if(result == -1) {
return false;
}
else{
return true;
}
}
}
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
am trying to delete all records from the database and insert records which i get from remote db , every time the activity loads.
I am able to insert the data. but when i try to delete the all the records from the table i get the error.
my code
Main Menu class
public class mainmenu extends Activity {
private ScheduleDAO mscheduleDAo;
private VisitsDAO mvisitsDAO;
private String storedkey;
private String jsonfromapi;
//schedule table variables
private String schedule_id = null;
private String schedule_name = null;
private String schedule_date= null;
//visits table variables
private String visit_id = null;
private String visit_schedule_id = null;
private String visit_name = null;
private String visit_time = null;
private String visit_place = null;
private String visit_address = null;
private String visit_location_lat = null;
private String visit_location_lng = null;
private String visit_status = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mainmenu);
//Delete all records from visits and schedule tables
// mscheduleDAo.deleteAllSchedule();
mvisitsDAO.deleteAllVisits();
//loading schedule list
Button btn_sche = (Button) findViewById(R.id.btn_schedule);
btn_sche.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(mainmenu.this, Schedule_Activity.class));
}
});
//loading reset password
Button reset = (Button) findViewById(R.id.btn_reset_password);
reset.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(mainmenu.this, resetpassword.class));
}
});
//loading google maps
Button location = (Button) findViewById(R.id.btn_location);
location.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(mainmenu.this, My_Location.class));
}
});
try {
String user_name = getdate_from_local();
TextView user = (TextView) findViewById(R.id.lbl_name);
user.setText("Welcome : "+user_name+"\n");
} catch (IOException e) {
e.printStackTrace();
}
// getting the list of schedules from the remote api
get_schedule_list();
try{
JSONObject jsonObject = new JSONObject(jsonfromapi); //Here reponse is the yours server response
JSONObject result = jsonObject.getJSONObject("result");
JSONArray sehedule = result.getJSONArray("sehedule");
//save all schedules
for(int i=0;i<sehedule.length();i++)
{
schedule_id = sehedule.getJSONObject(i).getString("schedule_id");
schedule_date = sehedule.getJSONObject(i).getString("schedule_date");
String[] parts = schedule_date.split(" ");
String string1 = parts[0];
schedule_date = string1;
schedule_name = sehedule.getJSONObject(i).getString("schedule_name");
insert_schedule();
// Toast.makeText(this, schedule_date,Toast.LENGTH_LONG).show();
}
//save all visits
JSONArray visits = result.getJSONArray("visit");
for(int i=0;i<visits.length();i++)
{
visit_id = visits.getJSONObject(i).getString("visit_id");
visit_schedule_id = visits.getJSONObject(i).getString("schedule_id");
visit_name = visits.getJSONObject(i).getString("visit_name");
visit_time = visits.getJSONObject(i).getString("visit_time");
visit_place = visits.getJSONObject(i).getString("visit_place");
visit_address = visits.getJSONObject(i).getString("visit_address");
visit_location_lat = visits.getJSONObject(i).getString("visit_location_lat");
visit_location_lng = visits.getJSONObject(i).getString("visit_location_lng");
visit_status = visits.getJSONObject(i).getString("visit_status");
insert_visits();
}
//Save all items
JSONArray items = result.getJSONArray("item");
for(int i=0;i<items.length();i++)
{
String item_id = items.getJSONObject(i).getString("item_id");
String visit_id = items.getJSONObject(i).getString("visit_id");
String item_name = visits.getJSONObject(i).getString("item_name");
String item_check_status ="1";
String item_comment = "";
String item_latitude = "";
String item_longitude = "";
String item_submit_time = "";
String item_remote_status = "1";
}
}catch(Exception e)
{ }
}
private boolean insert_schedule(){
mscheduleDAo =new ScheduleDAO(getApplicationContext());
Schedule createdschedule = mscheduleDAo.createschedule(Integer.parseInt(String.valueOf(schedule_id)),
schedule_name,
schedule_date);
return true;
}
private boolean insert_visits(){
mvisitsDAO = new VisitsDAO(getApplicationContext());
Visits createvisits =mvisitsDAO.createvisits(Integer.parseInt(String.valueOf(visit_id)),
Integer.parseInt(String.valueOf(visit_schedule_id)),
visit_name, visit_time, visit_place, visit_address, visit_location_lat, visit_location_lng,
Integer.parseInt(String.valueOf(visit_status)));
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private String readkeyfromfille() throws IOException {
FileInputStream fis = openFileInput("myappkey.txt");
BufferedInputStream bis = new BufferedInputStream(fis);
StringBuffer b = new StringBuffer();
while(bis.available() !=0){
char c = (char) bis.read();
b.append(c);
}
String Key =b.toString();
return Key;
}
public String getdate_from_local() throws IOException {
String storedkey = readkeyfromfille();
byte[] data = Base64.decode(storedkey, Base64.DEFAULT);
String key_in_text = new String(data, "UTF-8");
String[] parts = key_in_text.split(Pattern.quote("|"));
String string1 = parts[0]; // 004
String string2 = parts[1];
return string1;
}
private void get_schedule_list(){
try {
jsonfromapi = new MySchedules().execute(storedkey).get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
//async task to get the schedule, visits, items details from remote database
class MySchedules extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... arg0) {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://172.16.110.3/agent_tracking/index.php/api/rest/get-schedules/");
try {
// Add your data
List<BasicNameValuePair> nameValuePairs = new ArrayList<>(1);
nameValuePairs.add(new BasicNameValuePair("key", arg0[0]));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
String schedule_list = EntityUtils.toString(entity, "UTF-8");
return schedule_list;
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
return null;
}
#Override
protected void onPostExecute(String data) {
if(data != null){
jsonfromapi = data; //you would get json data here
//then do parse your json data
}
}
}
// end of async task
}
VisitsDOA class
public class VisitsDAO {
public static final String TAG = "visitsDAO";
// Database fields
private SQLiteDatabase mDatabase;
private DBHelper mDbHelper;
private Context mContext;
private String[] mAllColumns = {
DBHelper.COLUMN_VISITS_ID,
DBHelper.COLUMN_VISITS_SCHEDULE_ID,
DBHelper.COLUMN_VISITS_NAME,
DBHelper.COLUMN_VISITS_TIME,
DBHelper.COLUMN_VISITS_PLACE,
DBHelper.COLUMN_VISITS_ADDRESS,
DBHelper.COLUMN_VISITS_LOCATION_LAT,
DBHelper.COLUMN_VISITS_LOCATION_LNG,
DBHelper.COLUMN_VISITS_STATUS };
public VisitsDAO(Context context) {
this.mContext = context;
mDbHelper = new DBHelper(context);
// open the database
try {
open();
} catch (SQLException e) {
Log.e(TAG, "SQLException on openning database " + e.getMessage());
e.printStackTrace();
}
}
public void open() throws SQLException {
mDatabase = mDbHelper.getWritableDatabase();
}
public void close() {
mDbHelper.close();
}
public Visits createvisits(int vid, int v_sid, String vname, String vtime, String vplace, String address, String vlat, String vlong, int vstatus) {
ContentValues values = new ContentValues();
values.put(DBHelper.COLUMN_VISITS_ID, vid);
values.put(DBHelper.COLUMN_VISITS_SCHEDULE_ID, v_sid);
values.put(DBHelper.COLUMN_VISITS_NAME, vname);
values.put(DBHelper.COLUMN_VISITS_TIME, vtime);
values.put(DBHelper.COLUMN_VISITS_PLACE, vplace);
values.put(DBHelper.COLUMN_VISITS_ADDRESS, address);
values.put(DBHelper.COLUMN_VISITS_LOCATION_LAT, vlat);
values.put(DBHelper.COLUMN_VISITS_LOCATION_LNG, vlong);
values.put(DBHelper.COLUMN_VISITS_STATUS, vstatus);
long insertId = mDatabase
.insert(DBHelper.TABLE_VISITS, null, values);
Cursor cursor = mDatabase.query(DBHelper.TABLE_VISITS, mAllColumns,
DBHelper.COLUMN_VISITS_ID + " = " + insertId, null, null,
null, null);
Visits newvisits = null;
if (cursor != null&& cursor.moveToFirst()) {
cursor.moveToFirst();
newvisits = cursorTovisits(cursor);
}
cursor.close();
return newvisits;
}
public List<Visits> getAllvisits() {
List<Visits> listVisits = new ArrayList<Visits>();
Cursor cursor = mDatabase.query(DBHelper.TABLE_VISITS, mAllColumns,
null, null, null, null, null);
if (cursor != null) {
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
Visits visits = cursorTovisits(cursor);
listVisits.add(visits);
cursor.moveToNext();
}
// make sure to close the cursor
cursor.close();
}
return listVisits;
}
public List<Visits> getAllvisitsforSchedule(int id) {
List<Visits> listVisits = new ArrayList<Visits>();
Cursor cursor = mDatabase.query(DBHelper.TABLE_VISITS, mAllColumns,
DBHelper.COLUMN_VISITS_SCHEDULE_ID + " = ?",
new String[]{String.valueOf(id)}, null, null, null);
if (cursor != null) {
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
Visits visits = cursorTovisits(cursor);
listVisits.add(visits);
cursor.moveToNext();
}
// make sure to close the cursor
cursor.close();
}
return listVisits;
}
public Visits getvisitById(int id) {
Cursor cursor = mDatabase.query(DBHelper.TABLE_VISITS, mAllColumns,
DBHelper.COLUMN_VISITS_ID + " = ?",
new String[]{String.valueOf(id)}, null, null, null);
if (cursor != null) {
cursor.moveToFirst();
}
Visits visits = cursorTovisits(cursor);
return visits;
}
protected Visits cursorTovisits(Cursor cursor) {
Visits schedule = new Visits();
schedule.setvId(cursor.getInt(0));
schedule.setVschID(cursor.getInt(1));
schedule.setVname(cursor.getString(2));
schedule.setVtime(cursor.getString(3));
schedule.setVplace(cursor.getString(4));
schedule.setVaddress(cursor.getString(5));
schedule.setVlat(cursor.getString(6));
schedule.setVlong(cursor.getString(7));
schedule.setVstatus(cursor.getInt(8));
return schedule;
}
public void deleteVisits(Visits visits) {
long id = visits.getvId();
mDatabase.delete(DBHelper.TABLE_VISITS, DBHelper.COLUMN_VISITS_ID + " = " + id, null);
}
public void deleteAllVisits() {
SQLiteDatabase db = mDbHelper.getWritableDatabase();
db.delete(DBHelper.TABLE_VISITS, null, null);
}
}
dbhelper class
public class DBHelper extends SQLiteOpenHelper {
public static final String TAG = "DBHelper";
// columns of the schedule table
public static final String TABLE_SCHEDULE= "schedule";
public static final String COLUMN_SCHEDULE_ID = "schedule_id";
public static final String COLUMN_SCHEDULE_NAME = "schedule_name";
public static final String COLUMN_SCHEDULE_DATE = "schedule_date";
// columns of the items table
public static final String TABLE_ITEM= "items";
public static final String COLUMN_ITEM_ID = "item_id";
public static final String COLUMN_ITEM_VISIT_ID = "visit_id";
public static final String COLUMN_ITEM_NAME = "item_name";
public static final String COLUMN_ITEM_CHECK_STATUS= "item_check_status";
public static final String COLUMN_ITEM_COMMENT = "item_comment";
public static final String COLUMN_ITEM_LAT = "item_latitude";
public static final String COLUMN_ITEM_LNG = "item_longitude";
public static final String COLUMN_ITEM_SUB_TIME = "item_submit_time";
public static final String COLUMN_ITEM_REMOTE_status = "item_remote_status";
// columns of the employees table
public static final String TABLE_VISITS = "visits";
public static final String COLUMN_VISITS_ID = "visit_id";
public static final String COLUMN_VISITS_SCHEDULE_ID = "schedule_id";
public static final String COLUMN_VISITS_NAME = "visit_name";
public static final String COLUMN_VISITS_TIME = "visit_time";
public static final String COLUMN_VISITS_PLACE = "visit_place";
public static final String COLUMN_VISITS_ADDRESS ="visit_address";
public static final String COLUMN_VISITS_LOCATION_LAT = "visit_location_lat";
public static final String COLUMN_VISITS_LOCATION_LNG = "visit_location_lng";
public static final String COLUMN_VISITS_STATUS = "visit_status";
private static final String DATABASE_NAME = "certisagent";
private static final int DATABASE_VERSION = 7;
// SQL statement of the visits table creation
private static final String SQL_CREATE_TABLE_VISITS = "CREATE TABLE " + TABLE_VISITS + "("
+ COLUMN_VISITS_ID + " INTEGER PRIMARY KEY, "
+ COLUMN_VISITS_SCHEDULE_ID + " INTEGER, "
+ COLUMN_VISITS_NAME + " TEXT NOT NULL, "
+ COLUMN_VISITS_TIME + " TEXT NOT NULL, "
+ COLUMN_VISITS_PLACE + " TEXT NOT NULL, "
+ COLUMN_VISITS_ADDRESS + " TEXT NOT NULL, "
+ COLUMN_VISITS_LOCATION_LAT + " TEXT NOT NULL, "
+ COLUMN_VISITS_LOCATION_LNG + " TEXT NOT NULL, "
+ COLUMN_VISITS_STATUS + " INTEGER "
+");";
// SQL statement of the schedule table creation
private static final String SQL_CREATE_TABLE_SCHEDULE = "CREATE TABLE " + TABLE_SCHEDULE + "("
+ COLUMN_SCHEDULE_ID + " INTEGER PRIMARY KEY, "
+ COLUMN_SCHEDULE_NAME + " TEXT NOT NULL, "
+ COLUMN_SCHEDULE_DATE + " TEXT NOT NULL "
+");";
// SQL statement of the item table creation
private static final String SQL_CREATE_TABLE_ITEMS = "CREATE TABLE " + TABLE_ITEM + "("
+ COLUMN_ITEM_ID + " INTEGER PRIMARY KEY, "
+ COLUMN_ITEM_VISIT_ID + " INTEGER, "
+ COLUMN_ITEM_NAME + " TEXT NOT NULL, "
+ COLUMN_ITEM_CHECK_STATUS + " INTEGER, "
+ COLUMN_ITEM_COMMENT + " TEXT, "
+ COLUMN_ITEM_LAT + " TEXT, "
+ COLUMN_ITEM_LNG + " TEXT, "
+ COLUMN_ITEM_SUB_TIME + " TEXT, "
+ COLUMN_ITEM_REMOTE_status + " INTEGER "
+");";
public DBHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase database) {
database.execSQL(SQL_CREATE_TABLE_SCHEDULE);
database.execSQL(SQL_CREATE_TABLE_VISITS);
database.execSQL(SQL_CREATE_TABLE_ITEMS);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(TAG,
"Upgrading the database from version " + oldVersion + " to " + newVersion);
// clear all data
db.execSQL("DROP TABLE IF EXISTS " + TABLE_SCHEDULE);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_VISITS);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_ITEM);
// recreate the tables
onCreate(db);
}
}
Error Stack
Process: lk.agent.certislanka.certisagenttracking, PID: 15681
java.lang.RuntimeException: Unable to start activity ComponentInfo{lk.agent.certislanka.certisagenttracking/lk.agent.certislanka.certisagenttracking.mainmenu}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2429)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2493)
at android.app.ActivityThread.access$800(ActivityThread.java:166)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1283)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5584)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1268)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1084)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at lk.agent.certislanka.certisagenttracking.mainmenu.onCreate(mainmenu.java:79)
at android.app.Activity.performCreate(Activity.java:5442)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1094)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2393)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2493)
at android.app.ActivityThread.access$800(ActivityThread.java:166)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1283)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5584)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1268)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1084)
at dalvik.system.NativeStart.main(Native Method)
You need to add
mvisitsDAO = new VisitsDAO(getApplicationContext());
before you perform the delete in onCreate()
I am new to android, I am trying to retrieve values from a sqlite database based on the listview values. I tried to retrieve values using string variable. I can do this if I directly substitute the value in the place of variable.
Following this I post my codes kindly help me to sort out this.
DBhelper.java
public class DBHelper extends SQLiteOpenHelper{
public SQLiteDatabase DB;
public String DBPath;
public static String DBName = "VERIFY ME1.sqlite3";
public static final int version = '1';
public static Context currentContext;
public static String tableName = "FORM2";
public DBHelper(Context context) {
super(context, DBName, null, version);
currentContext = context;
DBPath = "/data/data/" + context.getPackageName() + "/databases";
createDatabase();
Oninsert(DB);
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
}
private void createDatabase() {
boolean dbExists = checkDbExists();
if (dbExists) {
// do nothing
}
else {
DB = currentContext.openOrCreateDatabase(DBName, 0, null);
DB.execSQL("CREATE TABLE IF NOT EXISTS " +tableName +" (AppNo VARCHAR, AppName VARCHAR," +
" Area VARCHAR, FHcode INT(3));");
}}
private boolean checkDbExists() {
SQLiteDatabase checkDB = null;
try {
String myPath = DBPath + DBName;
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;
}
private void Oninsert(SQLiteDatabase dB2) {
// TODO Auto-generated method stub
DB = currentContext.openOrCreateDatabase(DBName, 0, null);
DB.execSQL("INSERT INTO " +
tableName +
" Values ('M001','shumi','India',250);");
DB.execSQL("INSERT INTO " +
tableName +
" Values ('C002','sarah','India',251);");
DB.execSQL("INSERT INTO " +
tableName +
" Values ('D003','Lavya','USA',252);");
DB.execSQL("INSERT INTO " +
tableName +
" Values ('V004','Avi','EU',253);");
DB.execSQL("INSERT INTO " +
tableName +
" Values ('T005','Shenoi','Bangla',254);");
DB.execSQL("INSERT INTO " +
tableName +
" Values ('L006','Lamha','Australia',255);");
DB.close();
}
}
ListActivity.java
public class login2 extends ListActivity implements OnItemClickListener {
private static final login2 ListActivity = null;
private static final AdapterView<?> parent = null;
private static int mPosition = 0;
private static final long id = 0;
private ArrayList<String> results = new ArrayList<String>();
private String tableName = DBHelper.tableName;
private SQLiteDatabase newDB;
private String AppName1,ApplID,FHcode,Area;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
openAndQueryDatabase();
displayResultList();
}
private void displayResultList() {
setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, results));
getListView().setTextFilterEnabled(true);
getListView().setOnItemClickListener(this);
}
private String openAndQueryDatabase() {
try {
DBHelper dbHelper = new DBHelper(this.getApplicationContext());
newDB = dbHelper.getWritableDatabase();
Cursor c = newDB.rawQuery("SELECT * FROM " +tableName +"", null);
if (c != null ) {
if (c.moveToFirst()) {
do {
AppName1 = c.getString(c.getColumnIndex("AppName"));
results.add(AppName1 );
}while (c.moveToNext());
}
}
c.close();
} catch (SQLiteException se ) {
Log.e(getClass().getSimpleName(), "Could not create or Open the database");
} finally {
//if (newDB == null)
// newDB.execSQL("DELETE FROM " + tableName);
//newDB.close();
}
return AppName1;
}
public void onClick(View arg0) {
login2 det = (login2)ListActivity;
det.onItemClick(parent, arg0, mPosition, id);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
// TODO Auto-generated method stub
String data=(String)parent.getItemAtPosition(position);
//showMessage("Successfully", data);
if (data != null ) {
try {
DBHelper dbHelper = new DBHelper(this.getApplicationContext());
newDB = dbHelper.getWritableDatabase();
Cursor c1 = newDB.rawQuery("SELECT DISTINCT AppNo, AppName, FHcode, Area FROM "
+tableName +" where AppName ="+data+"" ,null);
if (c1 != null ) {
if (c1.moveToFirst()) {
do {
ApplID= c1.getString(c1.getColumnIndex("AppNo"));
String AppName =c1.getString(c1.getColumnIndex("AppName"));
Area = c1.getString(c1.getColumnIndex("Area"));
FHcode =c1.getString(c1.getColumnIndex("FHcode"));
Intent intent = new Intent(getApplicationContext(), form.class);
//Create a bundle object
Bundle b = new Bundle();
//Inserts a String value into the mapping of this Bundle
b.putString("AppName", AppName.toString());
b.putString("Apprefno", ApplID.toString());
b.putString("FHcode", FHcode.toString());
b.putString("Area", Area.toString());
//Add the bundle to the intent.
intent.putExtras(b);
//start the DisplayActivity
startActivity(intent);
}
while (c1.moveToNext());
}
}
}
catch (SQLiteException se ) {
Log.e(getClass().getSimpleName(), "Could not create or Open the database");
} finally {
//if (newDB == null)
//newDB.execSQL("DELETE FROM " + tableName);
newDB.close();
}
}
}
public void showMessage (String title, String message)
{
Builder builder=new Builder(this);
builder.setCancelable(true);
builder.setTitle(title);
builder.setMessage(message);
builder.show();
}
You have taken this column as an integer FHcode INT(3)
and trying to fetch values as an string that is wrong
c1.getString(c1.getColumnIndex("FHcode")
change to c1.getInt**(c1.getColumnIndex("FHcode")
I have a SQLLite DB that stores an ftp site's login information (name,address,username,password,port,passive). When an item (site) is clicked in the list, it's supposed to load the name, address, username, password etc. into the corresponding EditTexts. What's happening is that the password value is getting loaded into the address EditText and the address isn't getting loaded anywhere.
My Activity's addRecord function looks like this:
public void addRecord() {
long newId = myDb.insertRow(_name, _address, _username, _password,
_port, _passive);
Cursor cursor = myDb.getRow(newId);
displayRecordSet(cursor);
}
The order of the parameters in insertRow() correspond to the order in my DBAdapter, however when I change the order of the parameters I can get the address and password values to end up in the correct EditTexts, just never all of them at once. What am I doing wrong?
public class DBAdapter {
// ///////////////////////////////////////////////////////////////////
// Constants & Data
// ///////////////////////////////////////////////////////////////////
// For logging:
private static final String TAG = "DBAdapter";
// DB Fields
public static final String KEY_ROWID = "_id";
public static final int COL_ROWID = 0;
/*
* CHANGE 1:
*/
// TODO: Setup your fields here:
public static final String KEY_NAME = "name";
public static final String KEY_ADDRESS = "address";
public static final String KEY_USERNAME = "username";
public static final String KEY_PASSWORD = "password";
public static final String KEY_PORT = "port";
public static final String KEY_PASSIVE = "passive";
// TODO: Setup your field numbers here (0 = KEY_ROWID, 1=...)
public static final int COL_NAME = 1;
public static final int COL_ADDRESS = 2;
public static final int COL_USERNAME = 3;
public static final int COL_PASSWORD = 4;
public static final int COL_PORT = 5;
public static final int COL_PASSIVE = 6;
public static final String[] ALL_KEYS = new String[] { KEY_ROWID, KEY_NAME,
KEY_ADDRESS, KEY_USERNAME, KEY_PASSWORD, KEY_PORT, KEY_PASSIVE };
// DB info: it's name, and the table we are using (just one).
public static final String DATABASE_NAME = "Sites";
public static final String DATABASE_TABLE = "SiteTable";
// Track DB version if a new version of your app changes the format.
public static final int DATABASE_VERSION = 2;
private static final String DATABASE_CREATE_SQL = "create table "
+ DATABASE_TABLE
+ " ("
+ KEY_ROWID
+ " integer primary key autoincrement, "
/*
* CHANGE 2:
*/
// TODO: Place your fields here!
// + KEY_{...} + " {type} not null"
// - Key is the column name you created above.
// - {type} is one of: text, integer, real, blob
// (http://www.sqlite.org/datatype3.html)
// - "not null" means it is a required field (must be given a
// value).
// NOTE: All must be comma separated (end of line!) Last one must
// have NO comma!!
+ KEY_NAME + " string not null, " + KEY_ADDRESS
+ " string not null, " + KEY_USERNAME + " string not null, "
+ KEY_PASSWORD + " string not null, " + KEY_PORT
+ " integer not null," + KEY_PASSIVE + " integer not null"
// Rest of creation:
+ ");";
// Context of application who uses us.
private final Context context;
private DatabaseHelper myDBHelper;
private SQLiteDatabase db;
// ///////////////////////////////////////////////////////////////////
// Public methods:
// ///////////////////////////////////////////////////////////////////
public DBAdapter(Context ctx) {
this.context = ctx;
myDBHelper = new DatabaseHelper(context);
}
// Open the database connection.
public DBAdapter open() {
db = myDBHelper.getWritableDatabase();
return this;
}
// Close the database connection.
public void close() {
myDBHelper.close();
}
// Add a new set of values to the database.
public long insertRow(String name, String address, String user,
String pass, int port, int passive) {
/*
* CHANGE 3:
*/
// TODO: Update data in the row with new fields.
// TODO: Also change the function's arguments to be what you need!
// Create row's data:
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_NAME, name);
initialValues.put(KEY_ADDRESS, address);
initialValues.put(KEY_USERNAME, user);
initialValues.put(KEY_PASSWORD, pass);
initialValues.put(KEY_PORT, port);
initialValues.put(KEY_PASSIVE, passive);
// Insert it into the database.
return db.insert(DATABASE_TABLE, null, initialValues);
}
// Delete a row from the database, by rowId (primary key)
public boolean deleteRow(long rowId) {
String where = KEY_ROWID + "=" + rowId;
return db.delete(DATABASE_TABLE, where, null) != 0;
}
public void deleteAll() {
Cursor c = getAllRows();
long rowId = c.getColumnIndexOrThrow(KEY_ROWID);
if (c.moveToFirst()) {
do {
deleteRow(c.getLong((int) rowId));
} while (c.moveToNext());
}
c.close();
}
// Return all data in the database.
public Cursor getAllRows() {
String where = null;
Cursor c = db.query(true, DATABASE_TABLE, ALL_KEYS, where, null, null,
null, null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
// Get a specific row (by rowId)
public Cursor getRow(long rowId) {
String where = KEY_ROWID + "=" + rowId;
Cursor c = db.query(true, DATABASE_TABLE, ALL_KEYS, where, null, null,
null, null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
// Change an existing row to be equal to new data.
public boolean updateRow(long rowId, String name, String address,
String username, String password, int port, int passive) {
String where = KEY_ROWID + "=" + rowId;
/*
* CHANGE 4:
*/
// TODO: Update data in the row with new fields.
// TODO: Also change the function's arguments to be what you need!
// Create row's data:
ContentValues newValues = new ContentValues();
newValues.put(KEY_NAME, name);
newValues.put(KEY_ADDRESS, address);
newValues.put(KEY_USERNAME, username);
newValues.put(KEY_PASSWORD, password);
newValues.put(KEY_PORT, port);
newValues.put(KEY_PASSIVE, passive);
// Insert it into the database.
return db.update(DATABASE_TABLE, newValues, where, null) != 0;
}
// ///////////////////////////////////////////////////////////////////
// Private Helper Classes:
// ///////////////////////////////////////////////////////////////////
/**
* Private class which handles database creation and upgrading. Used to
* handle low-level database access.
*/
private static class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase _db) {
_db.execSQL(DATABASE_CREATE_SQL);
}
#Override
public void onUpgrade(SQLiteDatabase _db, int oldVersion, int newVersion) {
Log.w(TAG, "Upgrading application's database from version "
+ oldVersion + " to " + newVersion
+ ", which will destroy all old data!");
// Destroy old database:
_db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
// Recreate new database:
onCreate(_db);
}
}
}
public class SiteManager extends Activity {
DBAdapter myDb;
public FTPClient mFTPClient = null;
public EditText etSitename;
public EditText etAddress;
public EditText etUsername;
public EditText etPassword;
public EditText etPort;
public CheckBox cbPassive;
public ListView site_list;
public Button clr;
public Button test;
public Button savesite;
public Button close;
public Button connect;
String _name;
String _address;
String _username;
String _password;
int _port;
int _passive = 0;
List<FTPSite> model = new ArrayList<FTPSite>();
ArrayAdapter<FTPSite> adapter;
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.site_manager);
site_list = (ListView) findViewById(R.id.siteList);
adapter = new SiteAdapter(this, R.id.ftpsitename, R.layout.siterow,
model);
site_list.setAdapter(adapter);
etSitename = (EditText) findViewById(R.id.dialogsitename);
etAddress = (EditText) findViewById(R.id.dialogaddress);
etUsername = (EditText) findViewById(R.id.dialogusername);
etPassword = (EditText) findViewById(R.id.dialogpassword);
etPort = (EditText) findViewById(R.id.dialogport);
cbPassive = (CheckBox) findViewById(R.id.dialogpassive);
close = (Button) findViewById(R.id.closeBtn);
connect = (Button) findViewById(R.id.connectBtn);
clr = (Button) findViewById(R.id.clrBtn);
test = (Button) findViewById(R.id.testBtn);
savesite = (Button) findViewById(R.id.saveSite);
addListeners();
openDb();
displayRecords();
}
public void addListeners() {
connect.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent returnResult = new Intent();
returnResult.putExtra("ftpname", _name);
returnResult.putExtra("ftpaddress", _address);
returnResult.putExtra("ftpusername", _username);
returnResult.putExtra("ftppassword", _password);
returnResult.putExtra("ftpport", _port);
setResult(RESULT_OK, returnResult);
finish();
}
});
test.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
_name = etSitename.getText().toString();
_address = etAddress.getText().toString();
_username = etUsername.getText().toString();
_password = etPassword.getText().toString();
_port = Integer.parseInt(etPort.getText().toString());
if (cbPassive.isChecked()) {
_passive = 1;
} else {
_passive = 0;
}
boolean status = ftpConnect(_address, _username, _password,
_port);
ftpDisconnect();
if (status == true) {
Toast.makeText(SiteManager.this, "Connection Succesful",
Toast.LENGTH_LONG).show();
savesite.setVisibility(0);
} else {
Toast.makeText(SiteManager.this,
"Connection Failed:" + status, Toast.LENGTH_LONG)
.show();
}
}
});
savesite.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
_name = etSitename.getText().toString();
_address = etAddress.getText().toString();
_username = etUsername.getText().toString();
_password = etPassword.getText().toString();
_port = Integer.parseInt(etPort.getText().toString());
if (cbPassive.isChecked()) {
_passive = 1;
} else {
_passive = 0;
}
addRecord();
adapter.notifyDataSetChanged();
}
});
close.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
clr.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
clearAll();
}
});
site_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, final View view,
int position, long id) {
final FTPSite item = (FTPSite) parent
.getItemAtPosition(position);
String tmpname = item.getName();
String tmpaddress = item.getAddress();
String tmpuser = item.getUsername();
String tmppass = item.getPassword();
int tmpport = item.getPort();
String tmp_port = Integer.toString(tmpport);
int tmppassive = item.isPassive();
etSitename.setText(tmpname);
etAddress.setText(tmpaddress);
etUsername.setText(tmpuser);
etPassword.setText(tmppass);
etPort.setText(tmp_port);
if (tmppassive == 1) {
cbPassive.setChecked(true);
} else {
cbPassive.setChecked(false);
}
}
});
}
public void addRecord() {
long newId = myDb.insertRow(_name, _username, _address,_password,
_port, _passive);
Cursor cursor = myDb.getRow(newId);
displayRecordSet(cursor);
}
private void openDb() {
myDb = new DBAdapter(this);
myDb.open();
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
closeDb();
}
private void closeDb() {
myDb.close();
}
public void displayRecords() {
Cursor cursor = myDb.getAllRows();
displayRecordSet(cursor);
}
protected void displayRecordSet(Cursor c) {
// String msg = "";
if (c.moveToFirst()) {
do {
// int id = c.getInt(0);
_name = c.getString(1);
_address = c.getString(2);
_username = c.getString(3);
_password = c.getString(4);
_port = c.getInt(5);
FTPSite sitesFromDB = new FTPSite();
sitesFromDB.setName(_name);
sitesFromDB.setAddress(_address);
sitesFromDB.setUsername(_username);
sitesFromDB.setAddress(_password);
sitesFromDB.setPort(_port);
sitesFromDB.setPassive(_passive);
model.add(sitesFromDB);
adapter.notifyDataSetChanged();
} while (c.moveToNext());
}
c.close();
}
public void clearAll() {
myDb.deleteAll();
adapter.notifyDataSetChanged();
}
public boolean ftpConnect(String host, String username, String password,
int port) {
try {
mFTPClient = new FTPClient();
// connecting to the host
mFTPClient.connect(host, port);
// now check the reply code, if positive mean connection success
if (FTPReply.isPositiveCompletion(mFTPClient.getReplyCode())) {
// login using username & password
boolean status = mFTPClient.login(username, password);
mFTPClient.enterLocalPassiveMode();
return status;
}
} catch (Exception e) {
// Log.d(TAG, "Error: could not connect to host " + host );
}
return false;
}
public boolean ftpDisconnect() {
try {
mFTPClient.logout();
mFTPClient.disconnect();
return true;
} catch (Exception e) {
// Log.d(TAG,
// "Error occurred while disconnecting from ftp server.");
}
return false;
}
class SiteAdapter extends ArrayAdapter<FTPSite> {
private final List<FTPSite> objects;
private final Context context;
public SiteAdapter(Context context, int resource,
int textViewResourceId, List<FTPSite> objects) {
super(context, R.id.ftpsitename, R.layout.siterow, objects);
this.context = context;
this.objects = objects;
}
/** #return The number of items in the */
public int getCount() {
return objects.size();
}
public boolean areAllItemsSelectable() {
return false;
}
/** Use the array index as a unique id. */
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.siterow, parent, false);
TextView textView = (TextView) rowView
.findViewById(R.id.ftpsitename);
textView.setText(objects.get(position).getName());
return (rowView);
}
}
I think you should try to use :
int keyNameIndex = c.getColumnIndex(DBAdapter.KEY_NAME);
_name = c.getString(keyNameIndex);
Instead of using direct number.I am not sure it cause the bug, but it gonna be better exercise. Hope it's help.
There is mismatch in your arguments see below
public long insertRow(String name, String address, String user,
String pass, int port, int passive) {
public void addRecord() {
long newId = myDb.insertRow(_name, _username, _address,_password,
_port, _passive);
Cursor cursor = myDb.getRow(newId);
displayRecordSet(cursor);
}
you are passing username to address and address to user
This is embarrassing. I had sitesFromDB.setAddress(_password); instead of sitesFromDB.setPassword(_password);