App stops whenever I press back button - android

Problem: This only happening on some pages. when I press back app stops. I get this error. I am not able to figure it out the exact problem. I am new to android. and this is happening at many pages.Any help would be highly appreciated.
logcat error:
InputEventSender:Exception dispatching finished signal.E/MessageQueue-JNI:Exception in MessageQueue callback:handleReceiveCallbackE/MessageQueue-JNI:java.lang.NullPointerException: Attempt to invoke virtual method 'void android.database.sqlite.SQLiteDatabase.close()' on a null object reference at twik.in.DBHelper.close(DBHelper.java:102)at twik.in.ActivityMenuDetail.onBackPressed(ActivityMenuDetail.java:285)at android.app.Activity.onKeyUp(Activity.java:2477)at android.view.KeyEvent.dispatch(KeyEvent.java:2664)at android.app.Activity.dispatchKeyEvent(Activity.java:2730)
In error these two classes are mentioned so I am posting its code here
public class ActivityMenuDetail extends Activity {
ImageView imgPreview;
TextView txtText, txtSubText;
WebView txtDescription;
Button btnAdd;
ScrollView sclDetail;
ProgressBar prgLoading;
TextView txtAlert;
// declare dbhelper object
static DBHelper dbhelper;
// declare ImageLoader object
ImageLoader imageLoader;
// declare variables to store menu data
String Menu_image, Menu_name, Menu_serve, Menu_description;
double Menu_price;
int Menu_quantity;
long Menu_ID;
String MenuDetailAPI;
int IOConnect = 0;
// create price format
DecimalFormat formatData = new DecimalFormat("#.##");
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.menu_detail);
ActionBar bar = getActionBar();
bar.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.header)));
bar.setTitle("Service Centre Detail");
bar.setDisplayHomeAsUpEnabled(true);
bar.setHomeButtonEnabled(true);
imgPreview = (ImageView) findViewById(R.id.imgPreview);
txtText = (TextView) findViewById(R.id.txtText);
txtSubText = (TextView) findViewById(R.id.txtSubText);
txtDescription = (WebView) findViewById(R.id.txtDescription);
btnAdd = (Button) findViewById(R.id.btnAdd);
//btnShare = (Button) findViewById(R.id.btnShare);
sclDetail = (ScrollView) findViewById(R.id.sclDetail);
prgLoading = (ProgressBar) findViewById(R.id.prgLoading);
txtAlert = (TextView) findViewById(R.id.txtAlert);
// get screen device width and height
DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
int wPix = dm.widthPixels;
int hPix = wPix / 2 + 50;
// change menu image width and height
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(wPix, hPix);
imgPreview.setLayoutParams(lp);
imageLoader = new ImageLoader(ActivityMenuDetail.this);
dbhelper = new DBHelper(this);
// get menu id that sent from previous page
Intent iGet = getIntent();
Menu_ID = iGet.getLongExtra("menu_id", 0);
// Menu detail API url
MenuDetailAPI = Constant.MenuDetailAPI+"?accesskey="+Constant.AccessKey+"&menu_id="+Menu_ID;
// call asynctask class to request data from server
new getDataTask().execute();
// event listener to handle add button when clicked
btnAdd.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
// TODO Auto-generated method stub
// show input dialog
addtoCart();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_detail, menu);
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.
switch (item.getItemId()) {
case R.id.cart:
// refresh action
Intent iMyOrder = new Intent(ActivityMenuDetail.this, ActivityCart.class);
startActivity(iMyOrder);
overridePendingTransition (R.anim.open_next, R.anim.close_next);
return true;
case android.R.id.home:
// app icon in action bar clicked; go home
this.finish();
overridePendingTransition(R.anim.open_main, R.anim.close_next);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
// method to show number of order form
void addtoCart(){
// open database first
try{
dbhelper.openDataBase();
}catch(SQLException sqle){
throw sqle;
}
if(dbhelper.isDataExist(Menu_ID)){
dbhelper.updateData(Menu_ID, 1, (Menu_price));
}else{
dbhelper.addData(Menu_ID, Menu_name, 1, (Menu_price));
}
startActivity(new Intent(ActivityMenuDetail.this,ActivityCart.class));
};
// asynctask class to handle parsing json in background
public class getDataTask extends AsyncTask<Void, Void, Void>{
// show progressbar first
getDataTask(){
if(!prgLoading.isShown()){
prgLoading.setVisibility(0);
txtAlert.setVisibility(8);
}
}
#Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
// parse json data from server in background
parseJSONData();
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
// when finish parsing, hide progressbar
prgLoading.setVisibility(8);
// if internet connection and data available show data
// otherwise, show alert text
if((Menu_name != null) && IOConnect == 0){
sclDetail.setVisibility(0);
imageLoader.DisplayImage(Constant.AdminPageURL+Menu_image, imgPreview);
txtText.setText(Menu_name);
txtSubText.setText("Price : " +Menu_price+" "+ActivityMenuList.Currency+"\n"+"Status : "+Menu_serve+"\n"+"Empty Slots : "+Menu_quantity);
txtDescription.loadDataWithBaseURL("", Menu_description, "text/html", "UTF-8", "");
txtDescription.setBackgroundColor(Color.parseColor("#e7e7e7"));
}else{
txtAlert.setVisibility(0);
}
}
}
// method to parse json data from server
public void parseJSONData(){
try {
// request data from menu detail API
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 15000);
HttpConnectionParams.setSoTimeout(client.getParams(), 15000);
HttpUriRequest request = new HttpGet(MenuDetailAPI);
HttpResponse response = client.execute(request);
InputStream atomInputStream = response.getEntity().getContent();
BufferedReader in = new BufferedReader(new InputStreamReader(atomInputStream));
String line;
String str = "";
while ((line = in.readLine()) != null){
str += line;
}
// parse json data and store into tax and currency variables
JSONObject json = new JSONObject(str);
JSONArray data = json.getJSONArray("data"); // this is the "items: [ ] part
for (int i = 0; i < data.length(); i++) {
JSONObject object = data.getJSONObject(i);
JSONObject menu = object.getJSONObject("Menu_detail");
Menu_image = menu.getString("Menu_image");
Menu_name = menu.getString("Menu_name");
Menu_price = Double.valueOf(formatData.format(menu.getDouble("Price")));
Menu_serve = menu.getString("Serve_for");
Menu_description = menu.getString("Description");
Menu_quantity = menu.getInt("Quantity");
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
IOConnect = 1;
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// close database before back to previous page
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
super.onBackPressed();
dbhelper.close();
finish();
overridePendingTransition(R.anim.open_main, R.anim.close_next);
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
//imageLoader.clearCache();
super.onDestroy();
}
#Override
public void onConfigurationChanged(final Configuration newConfig)
{
// Ignore orientation change to keep activity from restarting
super.onConfigurationChanged(newConfig);
}
}
and debhelper class here
public class DBHelper extends SQLiteOpenHelper{
String DB_PATH;
private final static String DB_NAME = "db_order";
public final static int DB_VERSION = 1;
public static SQLiteDatabase db;
private final Context context;
private final String TABLE_NAME = "tbl_order";
private final String ID = "id";
private final String MENU_NAME = "Menu_name";
private final String QUANTITY = "Quantity";
private final String TOTAL_PRICE = "Total_price";
public DBHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
this.context = context;
DB_PATH = Constant.DBPath;
}
public void createDataBase() throws IOException{
boolean dbExist = checkDataBase();
SQLiteDatabase db_Read = null;
if(dbExist){
//do nothing - database already exist
}else{
db_Read = this.getReadableDatabase();
db_Read.close();
try {
copyDataBase();
} catch (IOException e) {
throw new Error("Error copying database");
}
}
}
private boolean checkDataBase(){
File dbFile = new File(DB_PATH + DB_NAME);
return dbFile.exists();
}
private void copyDataBase() throws IOException{
InputStream myInput = context.getAssets().open(DB_NAME);
String outFileName = DB_PATH + DB_NAME;
OutputStream myOutput = new FileOutputStream(outFileName);
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer))>0){
myOutput.write(buffer, 0, length);
}
myOutput.flush();
myOutput.close();
myInput.close();
}
public void openDataBase() throws SQLException{
String myPath = DB_PATH + DB_NAME;
db = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);
}
#Override
public void close() {
db.close();
}
#Override
public void onCreate(SQLiteDatabase db) {
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
/** this code is used to get all data from database */
public ArrayList<ArrayList<Object>> getAllData(){
ArrayList<ArrayList<Object>> dataArrays = new ArrayList<ArrayList<Object>>();
Cursor cursor = null;
try{
cursor = db.query(
TABLE_NAME,
new String[]{ID, MENU_NAME, QUANTITY, TOTAL_PRICE},
null,null, null, null, null);
cursor.moveToFirst();
if (!cursor.isAfterLast()){
do{
ArrayList<Object> dataList = new ArrayList<Object>();
dataList.add(cursor.getLong(0));
dataList.add(cursor.getString(1));
dataList.add(cursor.getString(2));
dataList.add(cursor.getString(3));
dataArrays.add(dataList);
}
while (cursor.moveToNext());
}
cursor.close();
}catch (SQLException e){
Log.e("DB Error", e.toString());
e.printStackTrace();
}
return dataArrays;
}
/** this code is used to get all data from database */
public boolean isDataExist(long id){
boolean exist = false;
Cursor cursor = null;
try{
cursor = db.query(
TABLE_NAME,
new String[]{ID},
ID +"="+id,
null, null, null, null);
if(cursor.getCount() > 0){
exist = true;
}
cursor.close();
}catch (SQLException e){
Log.e("DB Error", e.toString());
e.printStackTrace();
}
return exist;
}
/** this code is used to get all data from database */
public boolean isPreviousDataExist(){
boolean exist = false;
Cursor cursor = null;
try{
cursor = db.query(
TABLE_NAME,
new String[]{ID},
null,null, null, null, null);
if(cursor.getCount() > 0){
exist = true;
}
cursor.close();
}catch (SQLException e){
Log.e("DB Error", e.toString());
e.printStackTrace();
}
return exist;
}
public void addData(long id, String menu_name, int quantity, double total_price){
// this is a key value pair holder used by android's SQLite functions
ContentValues values = new ContentValues();
values.put(ID, id);
values.put(MENU_NAME, menu_name);
values.put(QUANTITY, quantity);
values.put(TOTAL_PRICE, total_price);
// ask the database object to insert the new data
try{db.insert(TABLE_NAME, null, values);}
catch(Exception e)
{
Log.e("DB ERROR", e.toString());
e.printStackTrace();
}
}
public void deleteData(long id){
// ask the database manager to delete the row of given id
try {db.delete(TABLE_NAME, ID + "=" + id, null);}
catch (Exception e)
{
Log.e("DB ERROR", e.toString());
e.printStackTrace();
}
}
public void deleteAllData(){
// ask the database manager to delete the row of given id
try {db.delete(TABLE_NAME, null, null);}
catch (Exception e)
{
Log.e("DB ERROR", e.toString());
e.printStackTrace();
}
}
public void updateData(long id, int quantity, double total_price){
// this is a key value pair holder used by android's SQLite functions
ContentValues values = new ContentValues();
values.put(QUANTITY, quantity);
values.put(TOTAL_PRICE, total_price);
// ask the database object to update the database row of given rowID
try {db.update(TABLE_NAME, values, ID + "=" + id, null);}
catch (Exception e)
{
Log.e("DB Error", e.toString());
e.printStackTrace();
}
}}

The logcat says your dbhelper object is null when preforming close()
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
super.onBackPressed();
if (dbhelper != null)
dbhelper.close();
finish();
overridePendingTransition(R.anim.open_main, R.anim.close_next);
}
That should fix the problem

From the error trace that you have provided, it seems that "db" instance in DBHelper is null. Therefore in your onBackPressed() when you try to close db by called dbHelper.close(), it's throwing the NullPointerException. Adding a null check will help.
// close database before back to previous page
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
super.onBackPressed();
dbhelper.close();
finish();
overridePendingTransition(R.anim.open_main, R.anim.close_next);
}
The above function will eventually call the function below:
#Override
public void close() {
db.close();
}
Add a null check for "db"
#Override
public void close() {
if (db != null) {
db.close();
}
}
In a quick glance of your code, it seems that you are opening DB only on action like "add to cart".
void addtoCart(){
// open database first
try{
dbhelper.openDataBase();
}catch(SQLException sqle){
throw sqle;
}
if(dbhelper.isDataExist(Menu_ID)){
dbhelper.updateData(Menu_ID, 1, (Menu_price));
}else{
dbhelper.addData(Menu_ID, Menu_name, 1, (Menu_price));
}
startActivity(new Intent(ActivityMenuDetail.this,ActivityCart.class));
};
If you try to close the screen without performing such action DB object would not be available.

This is because it may getting null object reference of dbhelper and also it doesn't need to use finish(); as when onBackPressed() called activity finished automatically.
if (dbhelper != null)
dbhelper.close();
finish();
overridePendingTransition(R.anim.open_main, R.anim.close_next);
super.onBackPressed();

According to logcat you dbhelper is null, so its giving a NULL POINTER EXCEPTION.
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
super.onBackPressed();
dbhelper.close();
finish();
overridePendingTransition(R.anim.open_main, R.anim.close_next);
}
In the above method, super.onBackPressed(); is called first before closing the database, which is not a good practice.
Change it to,
#Override
public void onBackPressed() {
if (dbhelper != null)
dbhelper.close();
finish();
overridePendingTransition(R.anim.open_main, R.anim.close_next);
super.onBackPressed();
}
Also change,
public void close() {
db.close();
}
to
public void close() {
if(db!=null)
db.close();
}
in Dbhelper.class

Related

Updating a ListFragment from another class

I have a Class that helps download data and store them in a Content Provider, and I've a ListFragment that loads the data from the provider, when the user login, the data is downloaded and everything works fine, but when there's an update in the data, the class meant to download downloads the data and saves it, but when I call the ListFragment to update, it crashes. Any help would be appreciated, my code is below:
This is the class that downloads the data
public class OrderDataRetrieval {
final Context context;
ProgressDialog pDiag;
public OrderDataRetrieval(final Context myContext){
context = myContext;
}
public void getData(String getToken, final Uri uri1, final Uri uri2, final Uri uri3){
pDiag = new ProgressDialog(context.getApplicationContext());
pDiag.setMessage("Loading...");
pDiag.setCancelable(false);
String order_URL = "http://xxxxxxxxxxxxxxxxx.json?token=" + getToken + "&contain=nnnnn,mmmm&uuuuu=0";
//pDiag.show();
Cache cache = AppController.getInstance().getRequestQueue().getCache();
final Entry entry = cache.get(order_URL);
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.GET,
order_URL, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
//pDiag.dismiss();
if (response != null) {
context.getContentResolver().delete(uri2, null, null);
context.getContentResolver().delete(uri3, null, null);
context.getContentResolver().delete(uri1, null, null);
Log.d("REPLY", response.toString());
handleResponse(response, uri1, uri2, uri3);
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// TODO Auto-generated method stub
//pDiag.dismiss();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(jsonObjReq);
}
public void handleResponse(JSONObject response, Uri uri1, Uri uri2, Uri uri3){
try {
JSONObject respOrd = response.getJSONObject("response");
JSONObject dataOrd = respOrd.getJSONObject("data");
JSONArray ordersArr = dataOrd.getJSONArray("orders");
Log.d("TEST", uri1.toString());
Log.d("TAGURL", uri2.toString());
for (int i = 0; i < ordersArr.length(); i++) {
ContentValues value = new ContentValues();
JSONObject ordItmObj = (JSONObject) ordersArr.get(i);
final String id = ordItmObj.getString("id");
value.put("order_id", ordItmObj.getString("id"));
value.put("source_number", ordItmObj.getString("number"));
value.put("order_type", ordItmObj.getString("order_type"));
value.put("order_picked", ordItmObj.getString("picked"));
value.put("order_delivered", ordItmObj.getString("delivered"));
value.put("source_code", ordItmObj.getString("source_customer_code"));
value.put("source_email", ordItmObj.getString("source_customer_email"));
value.put("source_name", ordItmObj.getString("source_customer_name"));
value.put("source_phone", ordItmObj.getString("source_customer_phone_number"));
value.put("source_address", ordItmObj.getString("source_customer_address_line_1") + " " + ordItmObj.getString("source_customer_city"));
value.put("destination_code", ordItmObj.getString("destination_customer_code"));
value.put("destination_email", ordItmObj.getString("destination_customer_email"));
value.put("destination_name", ordItmObj.getString("destination_customer_name"));
value.put("destination_phone", ordItmObj.getString("destination_customer_phone_number"));
value.put("destination_address", ordItmObj.getString("destination_customer_address_line_1") + " " + ordItmObj.getString("destination_customer_city"));
context.getContentResolver().insert(uri1, value);
JSONArray ordItem = ordItmObj.getJSONArray("OrderItem");
for (int j = 0; j < ordItem.length(); j++) {
JSONObject itm = (JSONObject) ordItem.get(j);
ContentValues valueItem = new ContentValues();
valueItem.put("order_id", id);
valueItem.put("item_name", itm.getString("name"));
valueItem.put("item_quantity", itm.getString("quantity"));
valueItem.put("item_details", itm.getString("details"));
context.getContentResolver().insert(uri2, valueItem);
}
JSONArray ordIssues = ordItmObj.getJSONArray("Issue");
for (int h = 0; h < ordIssues.length(); h++) {
JSONObject issues = (JSONObject) ordIssues.get(h);
ContentValues valueIssues = new ContentValues();
valueIssues.put("order_id", id);
valueIssues.put("issue_type", issues.getString("issue_type_id"));
valueIssues.put("issue_description", issues.getString("description"));
context.getContentResolver().insert(uri3, valueIssues);
}
}
Intent intent = new Intent();
intent.setAction("RELOAD");
context.sendBroadcast(intent);
//pends.getActivity().
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
And below is the ListFragment that needs to be updated, PendingFragment pends = PendingFragment.getInstance();
pends.getResults(); when that line is called, it crashes the app
public class PendingFragment extends ListFragment{
Context activityContext;
private ProgressDialog pDialog;
private PendingOrderListAdapter listAdapter;
private List<PendingTrackItem> trackItems;
SharedPreferences pref;
private BroadcastReceiver myReciever = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
getResults();
}
};
public void onDestroyView() {
super.onDestroyView();
getActivity().getApplicationContext().unregisterReceiver(myReciever);
};
private static PendingFragment pending;
public PendingFragment(){
}
public static PendingFragment getInstance(){
if (null == pending) {
pending = new PendingFragment();
}
return pending;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
View pending = inflater.inflate(R.layout.pending_frag, container, false);
setHasOptionsMenu(true);
return pending;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onViewCreated(view, savedInstanceState);
ListView list = getListView();
trackItems = new ArrayList<PendingTrackItem>();
listAdapter = new PendingOrderListAdapter(getActivity(), trackItems);
list.setAdapter(listAdapter);
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
TextView add_id = (TextView) view.findViewById(R.id.orderId);
TextView orderNumber = (TextView) view.findViewById(R.id.orderNumber);
pref = getActivity().getSharedPreferences("myId", Context.MODE_PRIVATE);
Editor edit = pref.edit();
edit.putString("int1", add_id.getText().toString());
edit.commit();
Intent i = new Intent(getActivity(), OrderFragmentActivity.class);
i.putExtra("key1", orderNumber.getText().toString());
startActivity(i);
}
});
}
public void getResults(){
Uri uri = Uri.parse("content://" + getString(R.string.AUTORITY_ORDER) + "/order");
Log.d("URL PRINT", uri.toString());
final Cursor cursor = getActivity().getContentResolver().query(uri, null, null, null, "_id");
Log.d("CURSOR DATA:", cursor.toString());
JSONArray array = new JSONArray();
if (cursor != null && cursor.getCount() > 0) {
while(cursor.moveToNext()){
JSONObject object = new JSONObject();
try {
object.put("destination_address", cursor.getString(0));
object.put("destination_code", cursor.getString(1));
object.put("destination_email", cursor.getString(2));
object.put("destination_name", cursor.getString(3));
object.put("destination_phone", cursor.getString(4));
object.put("_id", cursor.getString(5));
object.put("order_delivered", cursor.getString(6));
object.put("order_id", cursor.getString(7));
object.put("order_picked", cursor.getString(8));
object.put("order_type", cursor.getString(9));
object.put("source_address", cursor.getString(10));
object.put("source_code", cursor.getString(11));
object.put("source_email", cursor.getString(12));
object.put("source_name", cursor.getString(13));
object.put("source_number", cursor.getString(14));
object.put("source_phone", cursor.getString(15));
array.put(object);
Log.d("ARRAY", String.valueOf(array.length()));
} catch (JSONException e) {
e.printStackTrace();
}
}
parseJsonFeed(array);
cursor.close();
/*FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ClosedFragment cF = new ClosedFragment();
ft.replace(android.R.id.list, cF);
ft.commit();
cF.getResults();*/
}
}
public void parseJsonFeed(JSONArray jArr){
Log.d("jsonArr", jArr.toString());
try {
trackItems.clear();
for (int i = 0; i < jArr.length(); i++) {
JSONObject rest = (JSONObject) jArr.get(i);
String check = rest.getString("order_delivered");
PendingTrackItem item = new PendingTrackItem();
String sourceAdrress, destinationAddress;
sourceAdrress = rest.getString("source_address");
destinationAddress = rest.getString("destination_address");
Log.d("ORDER_CHECK", rest.toString());
if (check.equals("false")) {
item.setId(rest.getString("order_id"));
item.setNumber(rest.getString("source_number"));
if (sourceAdrress.matches(" ")) {
item.setSourceAddress(rest.getString("destination_address"));
item.setSourceName(rest.getString("destination_name"));
} else if (destinationAddress.matches(" ")) {
item.setSourceAddress(rest.getString("source_address"));
item.setSourceName(rest.getString("source_name"));
} else {
item.setSourceAddress(rest.getString("source_address"));
item.setSourceName(rest.getString("source_name"));
}
trackItems.add(item);
}
}
//Log.d("ITEm", String.valueOf(trackItems.size()));
TextView txt = (TextView) getActivity().findViewById(R.id.txtCount);
txt.setText(String.valueOf(trackItems.size()));
listAdapter.notifyDataSetChanged();
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
#Override
public void onResume() {
// TODO Auto-generated method stub
activityContext = getActivity().getApplicationContext();
SharedPreferences pref = this.getActivity().getSharedPreferences("myData", Context.MODE_PRIVATE);
String getToken = pref.getString("key1", "no data");
IntentFilter filter = new IntentFilter("RELOAD");
getActivity().getApplicationContext().registerReceiver(myReciever, filter);
getResults();
//getData(getToken, uri, itemUri, issuesUri);
super.onResume();
}
}
The crash report is
10-08 13:29:34.370: E/AndroidRuntime(9723): Process: com.deliveryscience.pod, PID: 9723
10-08 13:29:34.370: E/AndroidRuntime(9723): java.lang.IllegalStateException: Fragment PendingFragment{41f49628} not attached to Activity
10-08 13:29:34.370: E/AndroidRuntime(9723): at android.support.v4.app.Fragment.getResources(Fragment.java:603)
10-08 13:29:34.370: E/AndroidRuntime(9723): at android.support.v4.app.Fragment.getString(Fragment.java:625)
10-08 13:29:34.370: E/AndroidRuntime(9723): at com.deliveryscience.pod.fragments.PendingFragment.getResults(PendingFragment.java:109)
10-08 13:29:34.370: E/AndroidRuntime(9723): at com.deliveryscience.pod.handlers.OrderDataRetrieval.handleResponse(OrderDataRetrieval.java:122)
10-08 13:29:34.370: E/AndroidRuntime(9723): at com.deliveryscience.pod.handlers.OrderDataRetrieval$1.onResponse(OrderDataRetrieval.java:53)
10-08 13:29:34.370: E/AndroidRuntime(9723): at com.deliveryscience.pod.handlers.OrderDataRetrieval$1.onResponse(OrderDataRetrieval.java:1)
10-08 13:29:34.370: E/AndroidRuntime(9723): at com.android.volley.toolbox.JsonRequest.deliverResponse(JsonRequest.java:65)
10-08 13:29:34.370: E/AndroidRuntime(9723): at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:99)
I am stuck at finding a way to refresh the ListFragment
Follow below steps
1) register a broadcast receiver in ListFragment.
2) from Downloading data class, send a broadcast message with same intent you registered your receiver with.
instead of below code, use sendBroadcast
PendingFragment pends = PendingFragment.getInstance();
pends.getResults();
3) do the needful update from onReceive of Receiver class.
Alternatively you can use Handler to communicate between Download class and Fragment.
instead of

Error Invalid DriveId while retrieving files from google Drive

Brief Description:
In the following code what i am trying to do is when the new file is created in the drive folder i want to store the file Id in local database and this id i will be using to get that file.
upload() in this it will actually create files and upload to drive
fileIds.add(dfres.getDriveFile().getDriveId().encodeToString() Is it correct?
sync()
This is Where i am getting error:-
DriveId did = DriveId.decodeFromString(dbfileid.get(i));
Please Help
Code : *EDITED *
public class MainActivity extends Activity implements ConnectionCallbacks,
OnConnectionFailedListener {
SQLiteOpenHelper dbhelper;
SQLiteDatabase database;
int j=0;
private static final String LOGTAG="EXPLORECA";
private static final String DATABASE_NAME="file.db";
private static final int DATABASE_VERSION=1;
private static final String TABLE="fileids";
private static final String filename="fname";
private static final String fileid="fid";
Date driveFileDate=new Date();
Date localFileDate=new Date();
ArrayList<String> fileNames = new ArrayList<String>();
ArrayList<String> fileIds = new ArrayList<String>();
ArrayList<String> dbfilename = new ArrayList<String>();
ArrayList<String> dbfileid = new ArrayList<String>();
long lastSyncTime=0;
private static final int REQUEST_CODE_RESOLUTION = 3;
//String[] fileNames = new String[]{""};
Button b1;
private ContentsResult result;
private GoogleApiClient mGoogleApiClient;
byte[] buffer;
int i=111;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lastSyncTime= System.currentTimeMillis()-200000;
//b1=(Button)findViewById(R.id.button1);
getfiles();
if(fileNames.size()>0)
{
if (mGoogleApiClient == null) {
// Create the API client and bind it to an instance variable.
// We use this instance as the callback for connection and connection
// failures.
// Since no account name is passed, the user is prompted to choose.
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(Drive.API)
.addScope(Drive.SCOPE_FILE)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
}
// Connect the client. Once connected, the camera is launched.
try
{
mGoogleApiClient.connect();
}catch(Exception e)
{
showToast(""+e.toString());
}
}
else
{
showToast("Else Part ");
}
#Override
public void onConnected(Bundle arg0) {
// TODO Auto-generated method stub
showToast("connected");
MetadataChangeSet changeSet = new MetadataChangeSet.Builder()
.setTitle("Sky folder").build();
DriveFolderResult sky = Drive.DriveApi.getRootFolder(getGoogleApiClient()).createFolder(
getGoogleApiClient(), changeSet).await();
showToast("folder created");
upload();
}
}
private void upload() {
// TODO Auto-generated method stub
showToast("Inside Connected");
for(int i=0;i<fileNames.size();i++)
{
result = Drive.DriveApi.newContents(mGoogleApiClient).await();
OutputStream outputStream = result.getContents().getOutputStream();
String s=Environment.getExternalStorageDirectory().toString()+"/AudioRecorder";
File file = new File(s+"/"+fileNames.get(i));
showToast(file.getName()+" id uploading");
// showToast("Path="+Environment.DIRECTORY_DOWNLOADS+"/k.mp3 "+file.length());
buffer = new byte[(int)file.length()];
try {
showToast("started reading n writing");
FileInputStream is = new FileInputStream(file);
//ByteArrayInputStream iss = new ByteArrayInputStream(buffer, 0, 0);
int l =is.read(buffer);
//is.read
outputStream.write(buffer);
showToast("Buffer is written");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
showToast(""+e.toString());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
showToast(""+e.toString());
}
showToast(""+result.getContents().toString());
MetadataChangeSet changeSet = new MetadataChangeSet.Builder()
.setTitle(fileNames.get(i)+i)
.setMimeType("audio/MP3")
.setStarred(true).build();
showToast("meta data created");
DriveFileResult dfres= Drive.DriveApi.getRootFolder(getGoogleApiClient())
.createFile(getGoogleApiClient(), changeSet, result.getContents())
.await();
showToast("await() complete");
if (!result.getStatus().isSuccess()) {
showToast("Error while trying to create the file");
return;
}
fileIds.add(dfres.getDriveFile().getDriveId().encodeToString());
// showToast("Created a file: " + dfres.getDriveFile().getDriveId());
}
showToast("fileIds = "+fileIds.size()+" first file"+fileIds.get(0));
add_to_db();
getvalues();
synch();
}
private void synch() {
// TODO Auto-generated method stub
for(int i=0;i<fileIds.size();i++)
{
String path = Environment.getExternalStorageDirectory().toString()+"/AudioRecorder/"+dbfilename.get(i);
showToast("Files Path: " + path);
File f = new File(path);
//long fileModifiedTime = f.lastModified();
localFileDate= new Date(f.lastModified());
showToast(""+localFileDate);
//fetchDriveId(getGoogleApiClient(), dbfileid.get(i).toString()).await();
DriveId did = DriveId.decodeFromString(dbfileid.get(i));
DriveFile file2= Drive.DriveApi.getFile(getGoogleApiClient(),did);
//DriveFile file2 = Drive.DriveApi.getFile(getGoogleApiClient(),result2.getDriveId());
MetadataResult metadata=file2.getMetadata(getGoogleApiClient()).await();
Metadata md =metadata.getMetadata();
driveFileDate=md.getModifiedByMeDate();
if(f.getName().equals(md.getTitle()))
{
showToast("File Not Changed"+f.getName()+" Drive Name"+md.getTitle());
}
else
{
if(localFileDate.getTime() < driveFileDate.getTime())
{
File f2 = new File(md.getTitle());
f.renameTo(f2);
showToast("After Renaming ="+f.getName());
}
else
{
MetadataChangeSet changeSet2 = new MetadataChangeSet.Builder()
.setStarred(true)
.setTitle(f.getName().toString()).build();
file2.updateMetadata(getGoogleApiClient(), changeSet2).await();
showToast("file renamed in drive");
}
}
}
}
private void getfiles() {
// TODO Auto-generated method stub
String path = Environment.getExternalStorageDirectory().toString()+"/AudioRecorder";
showToast("Files Path: " + path);
File f = new File(path);
File file[] = f.listFiles();
//showToast("Files Size: "+ file.length);
for (int i=0; i < file.length; i++)
{
// showToast("Files FileName:" + file[i].getName());
if(file[i].getName().contains(".mp3")||file[i].getName().contains(".wav"))
{
if(lastSyncTime < file[i].lastModified())
{
fileNames.add(file[i].getName().toString());
}
}
}
showToast("fileNames contains:"+fileNames.size());
}
private void getDriveFiles() {
// TODO Auto-generated method stub
showToast("Getting Drive files");
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public void onConnectionFailed(ConnectionResult result) {
// TODO Auto-generated method stub
// Called whenever the API client fails to connect.
//Log.i("GoogleApiClient connection failed: " + result.toString());
if (!result.hasResolution()) {
// show the localized error dialog.
showToast("Error in on connection failed");
GooglePlayServicesUtil.getErrorDialog(result.getErrorCode(), this, 0).show();
return;
}
// The failure has a resolution. Resolve it.
// Called typically when the app is not yet authorized, and an
// authorization
// dialog is displayed to the user.
try {
result.startResolutionForResult(this, REQUEST_CODE_RESOLUTION);
} catch (SendIntentException e) {
showToast("error"+e.toString());
// Log.e(TAG, "Exception while starting resolution activity", e);
}
}
#Override
protected void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
if (requestCode == REQUEST_CODE_RESOLUTION && resultCode == RESULT_OK) {
mGoogleApiClient.connect();
showToast("Connected");
}
}
#Override
public void onConnectionSuspended(int arg0) {
// TODO Auto-generated method stub
}
public GoogleApiClient getGoogleApiClient() {
return mGoogleApiClient;
}
public void showToast(final String toast) {
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), toast, Toast.LENGTH_SHORT).show();
}
});
}
public void add_to_db()
{
dbhelper=new fileiddb(this);
database=dbhelper.getWritableDatabase();
ContentValues values = new ContentValues();
for(int i=0;i< fileNames.size();i++)
{
String name = fileNames.get(i);
String id = fileIds.get(i).substring(8);
showToast("database id ="+id);
values.put(filename,name);
values.put(fileid,id);
}
database.insert(TABLE, null, values);
database.close();
Toast.makeText(this,"Added Successfully" ,Toast.LENGTH_LONG).show();
}
public void getvalues()
{
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE;
dbhelper=new fileiddb(this);
database=dbhelper.getWritableDatabase();
Cursor cursor = database.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
dbfilename.add(cursor.getString(0));
dbfileid.add(cursor.getString(1));
showToast(dbfilename.get(j).toString()+" = "+dbfileid.get(j).toString());
j++;
} while (cursor.moveToNext());
}
}
}
fileiddb.java
public class fileiddb extends SQLiteOpenHelper {
private static final String LOGTAG="EXPLORECA";
private static final String DATABASE_NAME="file.db";
private static final int DATABASE_VERSION=1;
private static final String TABLE="fileids";
private static final String filename="fname";
private static final String fileid="fid";
private static final String TABLE_CREATE=
"CREATE TABLE "+TABLE +
" ("
+filename+" TEXT,"
+fileid +" TEXT primary key not null "
+")";
public fileiddb(Context context) {
super(context, DATABASE_NAME, null,DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
sqLiteDatabase.execSQL(TABLE_CREATE);
Log.i(LOGTAG,"Table is Created");
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i2) {
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS "+TABLE);
onCreate(sqLiteDatabase);
}
}
How can the code above even work / compile if you initialize and connect 'mGoogleApiClient' and you use 'getGoogleApiClient()' coming from godknowswhere. I recommend you start with primitive example like this one and build from there. The example is as simple as you can get the GAC class is a complete wrapper for most of the GDAA scenarios, and if you start building from there, most of your questions will be answered by your own debugger.

my app working fine on online but not working on offline help me

I want to make my application offline .When I am inserting data from url to database it works fine when internet available but my app not show any thing in gridview when no internet available what is wrong in my app please help me why gridview not loading data from database help me
public class MainActivity extends Activity {
CategoryListAdapter3 cla;
static ArrayList<String> Category_ID = new ArrayList<String>();
static ArrayList<String> Category_name = new ArrayList<String>();
static ArrayList<String> Category_image = new ArrayList<String>();
String URL, URL2;
String SelectMenuAPI;
String _response;
String status;
GridView gridview;
private DbHelper mHelper;
private SQLiteDatabase dataBase;
private boolean isUpdate;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mHelper=new DbHelper(this);
dataBase=mHelper.getWritableDatabase();
gridview = (GridView) findViewById(R.id.gridview);
cla = new CategoryListAdapter3(MainActivity.this);
new TheTask().execute();
gridview.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1,
int position, long arg3) {
// TODO Auto-generated method stub
Intent iMenuList = new Intent(MainActivity.this,
Subcategory.class);
iMenuList.putExtra("Category_ID", Category_ID.get(position));
iMenuList.putExtra("Category_name", Category_name.get(position));
startActivity(iMenuList);
}
});
}
void clearData() {
Category_ID.clear();
Category_name.clear();
Category_image.clear();
}
public class TheTask extends AsyncTask<Void, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(Void... arg0) {
SelectMenuAPI = "http://www.fff/mobile_api.php?response=getmaincategories";
clearData();
URL = SelectMenuAPI;
URL2 = URL.replace(" ", "%20");
try {
Log.i("url", "" + URL2);
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(URL2);
HttpResponse response = client.execute(request);
HttpEntity resEntity = response.getEntity();
_response = EntityUtils.toString(resEntity);
} catch (Exception e) {
e.printStackTrace();
}
return _response;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
try {
JSONObject json2 = new JSONObject(result);
status = json2.getString("Status");
if (status.equals("1")) {
JSONArray school2 = json2.getJSONArray("data");
//
for (int i = 0; i < school2.length(); i++) {
JSONObject object = school2.getJSONObject(i);
String id = object.getString("category_id");
String name =object.getString("name");
String image_path = object.getString("image_path");
dataBase=mHelper.getWritableDatabase();
ContentValues values=new ContentValues();
values.put(DbHelper.KEY_MYID,id);
values.put(DbHelper.KEY_FNAME,name);
values.put(DbHelper.KEY_LNAME,image_path );
System.out.println("");
if(isUpdate)
{
//update database with new data
dataBase.update(DbHelper.TABLE_NAME, values, DbHelper.KEY_ID+"="+id, null);
}
else
{
//insert data into database
dataBase.insert(DbHelper.TABLE_NAME, null, values);
}
//close database
dataBase.close();
}
}
else {
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
displayData();
}
}
private void displayData() {
dataBase = mHelper.getWritableDatabase();
Cursor mCursor = dataBase.rawQuery("SELECT * FROM "
+ DbHelper.TABLE_NAME, null);
//
// Category_ID.clear();
// Category_name.clear();
// Category_image.clear();
if (mCursor.moveToFirst()) {
do {
Category_ID.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_ID)));
Category_name.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_FNAME)));
Category_image.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_LNAME)));
} while (mCursor.moveToNext());
}
gridview.setAdapter(cla);
mCursor.close();
}
public class DbHelper extends SQLiteOpenHelper {
static String DATABASE_NAME="userdata";
public static final String TABLE_NAME="user";
public static final String KEY_FNAME="fname";
public static final String KEY_LNAME="lname";
public static final String KEY_ID="id";
public static final String KEY_MYID="myid";
public DbHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_TABLE="CREATE TABLE "+TABLE_NAME+" ("+KEY_ID+" INTEGER PRIMARY
KEY,"+KEY_MYID+" TEXT, "+KEY_FNAME+" TEXT, "+KEY_LNAME+" BLOB)";
db.execSQL(CREATE_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME);
onCreate(db);
}
}
public class CategoryListAdapter3 extends BaseAdapter {
private Activity activity;
private AQuery androidAQuery;
public CategoryListAdapter3(Activity act) {
this.activity = act;
// imageLoader = new ImageLoader(act);
}
public int getCount() {
// TODO Auto-generated method stub
return MainActivity.Category_ID.size();
}
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ViewHolder holder;
androidAQuery = new AQuery(getcontext());
if(convertView == null){
LayoutInflater inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.viewitem2, null);
holder = new ViewHolder();
convertView.setTag(holder);
}else{
holder = (ViewHolder) convertView.getTag();
}
holder.txtText = (TextView) convertView.findViewById(R.id.title2);
holder.imgThumb = (ImageView) convertView.findViewById(R.id.image2);
holder.txtText.setText(MainActivity.Category_name.get(position));
a
ndroidAQuery.id(holder.imgThumb).image(MainActivity.Category_image.get(position), true,
true);
return convertView;
}
private Activity getcontext() {
// TODO Auto-generated method stub
return null;
}
static class ViewHolder {
TextView txtText;
ImageView imgThumb;
}
}
check internet Availability before web service call:
public static boolean isInternetAvailable(Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
return true;
}
return false;
}
You have called displayData() only in onPostExecute, so the data is displayed in grid only when you receive data from that URL.
Solution: Call the displayData() once in onCreate function before new TheTask().execute(). So now data will be displayed from the DB if available and then fetch from that URL using HTTPClient. If no internet then the data will still be displayed.
Note: Make sure the cursor size greater than 0 inside displayData(), else display no data text instead of grid view.
happy coding :)
This is quite obvious, You are actually calling you displayData() in postExecute, but in case of no internet, exception will occur you doInBackgroud and null will be passed to postExecute...Exception again in postExecute and your displayData() will not be called.
So first, implement checks for null values to avoid exceptions, and then close try closing you db in catch block.

How to get mysql data into listview in android

I Want to get data from mysql table in listview. i want to show that data in listview below my calander. can any one help me in simple manner. i have search lot for this but i didn't found proper solution. here is my code. help will be appreciated.
public class ActionList extends ListActivity {
public static String date;
public static String custname;
public static String starttime;
public static String endtime;
public static String task;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.actionlist);
Button plusBtn = (Button) findViewById(R.id.plusBtn);
Button buttonLogout = (Button) findViewById(R.id.btnLogout);
LoginActivity dao = new LoginActivity();
try {
Statement stmt = dao.dbConnection().createStatement();
String sql = "select * from task_tab";
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
System.out.println("This Is rs DAta "
+ rs.getString(1).toString());
date = rs.getString(2).toString();
task = rs.getString(3).toString();
custname = rs.getString(5).toString();
starttime = rs.getString(8).toString();
endtime = rs.getString(9).toString();
}
String[] list2 = { date, task, custname, starttime, endtime };
setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, list2));
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
plusBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent listActivityIntent = new Intent(ActionList.this,
CalendarView.class);
ActionList.this.startActivity(listActivityIntent);
}
});
buttonLogout.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(),
LoginActivity.class);
intent.putExtra("LoginMessage", "Logged Out");
startActivity(intent);
removeDialog(0);
}
});
}

create / open database after closing

In my app, after user logs in, database is created. When user logs out, I have to delete the database from the internal storage to save space. The problem is, after deleting the database and a user logs back in, database cannot be created anymore. I tried using .close() but it only makes the problem worse.
Here is my code.
DatabaseHelper
public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
private static final String DATABASE_PATH = "/mnt/sdcard/Philpost/databases/";
private static final String DATABASE_NAME = "DeliveriesDB.sqlite";
private static final int DATABASE_VERSION = 1;
// the DAO object we use to access the SimpleData table
private Dao<DeliveriesDB, Integer> DeliveriesDbDao = null;
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase database,
ConnectionSource connectionSource) {
try {
TableUtils.createTable(connectionSource, DeliveriesDB.class);
} catch (SQLException e) {
Log.e(DatabaseHelper.class.getName(), "Can't create database", e);
throw new RuntimeException(e);
} catch (java.sql.SQLException e) {
e.printStackTrace();
}
}
#Override
public void onUpgrade(SQLiteDatabase db, ConnectionSource connectionSource,
int oldVersion, int newVersion) {
try {
Log.i(DatabaseHelper.class.getName(), "onUpgrade");
TableUtils.dropTable(connectionSource, DatabaseHelper.class, true);
onCreate(db, connectionSource);
} catch (java.sql.SQLException e) {
// TODO Auto-generated catch block
Log.e(DatabaseHelper.class.getName(), "Cant drop database", e);
e.printStackTrace();
}
}
public Dao<DeliveriesDB, Integer> getDeliveriesDbDao() {
if (null == DeliveriesDbDao) {
try {
DeliveriesDbDao = getDao(DeliveriesDB.class);
} catch (java.sql.SQLException e) {
e.printStackTrace();
}
}
return DeliveriesDbDao;
}
}
DatabaseManager
public class DatabaseManager {
static private DatabaseManager instance;
static public void init(Context ctx) {
if (null == instance) {
instance = new DatabaseManager(ctx);
}
}
static public DatabaseManager getInstance() {
return instance;
}
private DatabaseHelper helper;
public DatabaseManager(Context ctx) {
helper = new DatabaseHelper(ctx);
}
public DatabaseHelper getHelper(Context ctx) {
if(helper == null){
helper = OpenHelperManager.getHelper(ctx, DatabaseHelper.class);
}
return helper;
}
public void releaseDb(Context ctx) {
DatabaseConnection connect;
try {
connect = getHelper(ctx).getConnectionSource()
.getReadWriteConnection();
getHelper(ctx).getConnectionSource().releaseConnection(connect);
helper = null;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void closeDb(){
helper.close();
}
public List<DeliveriesDB> getAllDeliveriesDB(Context ctx) {
List<DeliveriesDB> deliveriesdb = null;
try {
deliveriesdb = getHelper(ctx).getDeliveriesDbDao().queryForAll();
} catch (SQLException e) {
e.printStackTrace();
}
return deliveriesdb;
}
public void addDeliveriesDb(DeliveriesDB l, Context ctx) {
try {
getHelper(ctx).getDeliveriesDbDao().create(l);
} catch (SQLException e) {
e.printStackTrace();
}
}
public DeliveriesDB getDeliveriesDbWithId(int deliveriesDbId, Context ctx) {
DeliveriesDB deliveriesDb = null;
try {
deliveriesDb = getHelper(ctx).getDeliveriesDbDao().queryForId(
deliveriesDbId);
} catch (SQLException e) {
e.printStackTrace();
}
return deliveriesDb;
}
public void deleteDeliveriesDb(DeliveriesDB deliveriesDb, Context ctx) {
try {
getHelper(ctx).getDeliveriesDbDao().delete(deliveriesDb);
} catch (SQLException e) {
e.printStackTrace();
}
}
public void refreshDeliveriesDb(DeliveriesDB deliveriesDb, Context ctx) {
try {
getHelper(ctx).getDeliveriesDbDao().refresh(deliveriesDb);
} catch (SQLException e) {
e.printStackTrace();
}
}
public void updateDeliveriesDb(DeliveriesDB deliveriesDb, Context ctx) {
try {
getHelper(ctx).getDeliveriesDbDao().update(deliveriesDb);
} catch (SQLException e) {
e.printStackTrace();
}
}
}
The class where creation and deletion of database happens
public class DeliveryListActivity extends ListActivity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
DatabaseManager.init(this);
setContentView(R.layout.deliverylist_layout);
if (getLastNonConfigurationInstance() != null) {
deliveryIndex = (Integer) getLastNonConfigurationInstance();
}
if (PhilpostApplication.DELIVERIES == null) {
new RetrieveDeliveriesTask().execute();
} else {
updateCachedList(PhilpostApplication.DELIVERIES);
}
}
private void updateCachedList(List<Delivery> deliveries) {
File expath = context.getFilesDir();
String apppath = "/databases/DeliveriesDB.sqlite";
File path = new File(expath, apppath);
adapter = new DeliveryListAdapter(this,
R.layout.deliverylist_row_layout, deliveries);
setListAdapter(adapter);
PhilpostApplication.DELIVERIES = deliveries;
Log.d(TAG, "Updating UI list");
if (PhilpostApplication.firstDb) {
if (!path.exists()) {
createBackupDb();
Log.d(TAG, "DB first Creation");
}
}
}
public void createBackupDb() {
for (int i = 0; i < PhilpostApplication.DELIVERIES.size(); i++) {
// create db first
dId = PhilpostApplication.DELIVERIES.get(i).getId();
rId = PhilpostApplication.DELIVERIES.get(i).getRecipientId();
lastn = PhilpostApplication.DELIVERIES.get(i).getLastName();
firstn = PhilpostApplication.DELIVERIES.get(i).getFirstName();
addr = PhilpostApplication.DELIVERIES.get(i).getAddress();
dtype = PhilpostApplication.DELIVERIES.get(i).getType();
amount = PhilpostApplication.DELIVERIES.get(i).getCash();
pMan = PhilpostApplication.DELIVERIES.get(i).getPostman();
stats = PhilpostApplication.DELIVERIES.get(i).getStatus();
createNewDeliveriesDb(dId, rId, lastn, firstn, addr, dtype, amount,
pMan, stats);
keyNum[i] = PhilpostApplication.DELIVERIES.get(i).getId();
}
Log.d(TAG, "database created");
PhilpostApplication.firstDb = false;
}
public void logout() {
if (PhilpostApplication.listSynced == false) {
// if( checkIfSyncedList() ){
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Sync data first before logging out.")
.setCancelable(false).setPositiveButton("OK", null);
final AlertDialog alert = builder.create();
alert.show();
} else {
dialog = ProgressDialog.show(this, "Logging out", "please wait");
try {
WebService.logout();
PhilpostApplication.SESSION_KEY = null; // clear Application
// Session
// Key
AccountStore.clear(this);
// clear cached list
PhilpostApplication.DELIVERIES = null;
MemoryUtils.deleteCache(this);
PhilpostApplication.incompleteSync = false;
PhilpostApplication.loggedIn = false;
PhilpostApplication.firstDb = true;
DatabaseManager.getInstance().closeDb();
deleteInternalDb();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (PhilpostApplication.canToggleGPS) {
turnGpsOff();
}
dialog.dismiss();
exitActivity();
}
}
}
Deleting Database
public void deleteInternalDb() {
File internalDb = new File(
Environment.getDataDirectory()
+ "/data/packagename/databases/DeliveriesDB.sqlite");
if (internalDb.exists()) {
internalDb.delete();
Log.d(TAG, "Internal Db deleted");
}
}
Check the example here this will give you an idea how to use existing database.
when your getting response from db follow following formate. it work fine bcz i had face this problem.we must have close db in finally block try this it may help you.
try
{
//Query
}
catch
{
}
finally
{
c.close();
db.close();
}

Categories

Resources