Dropbox Sync API - How to Sync Manually ? - android

I am trying to implement Dropbox Sync API in my Android Application. I want to do the Syncing manually on Click Events. I have written this code:,br/>
private class BackgroundSyncManager extends AsyncTask<String, String, String>
{
private boolean isSynced = false;
private ProgressDialog pd;
public BackgroundSyncManager(Context ctx)
{
pd = new ProgressDialog(ctx);
pd.setTitle("Downlaoding in Progress...");
pd.setCancelable(false);
pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
pd.dismiss();
sync_Button.setVisibility(View.GONE);
}
#Override
protected void onProgressUpdate(String... values) {
// TODO Auto-generated method stub
super.onProgressUpdate(values);
pd.setProgress(Integer.parseInt(values[0]));
}
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
try
{
pd.show();
mDbFileSystem.syncNowAndWait();
isSynced = true;
}
catch(Exception e)
{
isSynced = false;
Log.e(TAG, "Error Occured While Syncing !, Error = "+e.toString());
}
return "";
}
}
But, it is throwing me an Error, Here is what my Logcat Says:
12-10 11:34:23.311: E/Main Activity(15464): Error Occured While Syncing !, Error = java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
Am i doing the Manual Syncing Wrong, or is there some problem in this implementation ?
Any help is highly appreciated, thanks.

Related

my application not read if statement in postexecute method

my code will crash if i not comment statement else if (message.equals("holiday")) on postexecute tell me why is not go further if not euqal this line (message.equals("holiday")) why not print "School is off today. Reason: if i comment else if (message.equals("holiday")) this code app work fine check my if else stateement please
String message;
public class getDataTask extends AsyncTask<Void, Void, Void> {
getDataTask() {
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
yourBoolean=false;
}
#Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
displayData();
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
yourBoolean=true ;
if ((Category_ID.size() > 0) ) {
listCategory.setAdapter(cla);
cla.notifyDataSetChanged() ;
listCategory.invalidateViews();
menu_nametxt.setText(mVal2);
}
else if (message.equals("holiday"))
{
menu_nametxt.setText("No menu available .");
listCategory.setVisibility(View.GONE);
}
else
menu_nametxt.setText("School is off today. Reason: "+mVal3);
listCategory.setVisibility(View.GONE);
}
private void displayData() {
Cursor mCursor3 = db.selectQuery("SELECT * FROM uss_vacation WHERE calendar_id);
if (mCursor3.moveToFirst()) {
do {
Vacation_Date.add(mCursor3.getString(mCursor3.getColumnIndex("date")));
if(mCursor3.getString(mCursor3.getColumnIndex("date")).equals(mydate))
{
message = "holiday";
String mVal ;
mVal = (mCursor3.getString(mCursor3.getColumnIndex("title")));
mVal2 = mVal.toString();
mCursor3.close();
return;
}
} while (mCursor3.moveToNext());
}
mCursor3.close();
}
if i comment this code application print "School is off today. Reason: text
else if (message.equals("holiday"))
// {
// menu_nametxt.setText("No menu available .");
// listCategory.setVisibility(View.GONE);
// }
Since message is null when the app is run for the first time, when the if-else statement reaches else if (message.equals("holiday"), it will throws NullPointerException instead of false and crashing the app.
see SO: Java null String equals result
Consider initialize the message with empty string instead. (i.e. message = "";).
OR
Change the order of checking to else if ("holiday".equals(message)).

Progress Dialog canceled before the task finished on another AsyncTask

I want to download stock from web using Web Service. Created Sync to delete current stock
new ResetStock().execute();
Here is ResetStock Async:
private class ResetStock extends AsyncTask<Void, Void, Void>
{
ProgressDialog pd;
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
pd.cancel();
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
pd=new ProgressDialog(FrmMainMenu.this);
pd.setMessage("Please Wait. We are Downloading the Catalogue...");
pd.show();
pd.setCancelable(false);
pd.setCanceledOnTouchOutside(false);
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
DatabaseHandlerStock dbc=new DatabaseHandlerStock(FrmMainMenu.this);
dbc.deleteallstock();
dbc.close();
new AsyncStock(FrmMainMenu.this).execute();
return null;
}
}
Now I Called Another Async to download and xml and insert into my database
here is Asyncstock
List<Stock> mystocks = null;
Context mcontext;
int x=0;
public AsyncStock(Context context) {
super();
this.mcontext = context;
}
#Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
try{
URLConnection conn = new URL("http://192.168.1.2/mob2server.asmx/GetStock").openConnection();
mystocks = SAXXMLParser.parse(conn.getInputStream());
DatabaseHandlerStock dbc;
dbc=new DatabaseHandlerStock(mcontext);
String category, make, model, productcode, productname, smallimages, largeimages, description, mrp, unit, pkg;
for(Stock in :mystocks)
{
x++;
category=in.getCategory();
make=in.getMake();
model=in.getModel();
productcode=in.getProductcode();
productname=in.getProductname();
smallimages=in.getSmallimages();
largeimages=in.getLargeimages();
description=in.getDescription();
mrp=in.getMrp();
unit=in.getUnit();
pkg=in.getPkg();
dbc.addContact(new Catalogue(category.replace("$","&"), make.replace("$","&"), model.replace("$","&"), productcode, productname.replace("$","&"), smallimages, largeimages, description.replace("$","&"), mrp, unit, pkg));
}
dbc.close();
}
catch (Exception e)
{
System.out.println(e.getMessage());
}
return null;
}
#Override
protected void onPostExecute(Void result) {
Toast.makeText(mcontext, "Total " + x + " Models Imported!", Toast.LENGTH_LONG).show();
super.onPostExecute(result);
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
}
My First dialog is cancel before the stock is inserted into stock.
I want my dialog to be there until stock is inserted into my database.
Create another class and pack your second asynctask stuff in it. You can than call this new class in your first asynctask. Also use the progress update to see what is going on. In this way you will have only one progress bar but will keep you informed.

How to refresh a listview in android using asynctask?

There are two Activities. The first Activity is having the list view to see what is being shared and the second activity has an edit text box (to input inorder to share) and a button. On clicking the button, it returns me the string which is the json response and I need to add this in the previous activity.
Now the problem is, when I refresh the first page fully hitting the server it gets the response but this is not what I want. It should not go back to the server. It should simply add in the list view adapter.
I have commented the code in the PostExecute(). I have tried the everyway but it is not reflecting. I am also posting my code for your reference.
public class ShareAsyncTask extends AsyncTask<String, Void, ArrayList<EventsStreamBean>> {
public ProgressDialog pd = new ProgressDialog(EventStreamActivity.this);
String success_share_val;
#Override
protected ArrayList<EventsStreamBean> doInBackground(
String... result) {
// TODO Auto-generated method stub
JSONObject jsonobj = new JSONObject(result[0].toString());
success_share_val = jsonobj.getString(Constants.SUCCESS);
//checks the success value
if(success_share_val.equalsIgnoreCase("1")) {
JSONArray events_stream_share_array = jsonobj.getJSONArray("streamArray");
if(events_stream_share_array.length() > 0) {
for(int i=0; i<events_stream_share_array.length(); i++) {
EventsStreamBean events_stream_bean = new EventsStreamBean();
JSONObject events_stream_object = events_stream_share_array.getJSONObject(i);
events_stream_bean.setStreamId(events_stream_object.getString(Constants.STREAM_ID));
events_stream_bean.setStreamType(events_stream_object.getString(Constants.STREAM_TYPE));
events_stream_bean.setUserId(events_stream_object.getString(Constants.USER_ID));
events_stream_bean.setUserName(events_stream_object.getString(Constants.USER_NAME));
events_stream_bean.setUserType(events_stream_object.getString(Constants.USER_TYPE));
events_stream_bean.setUserAvatar(events_stream_object.getString(Constants.USER_AVATAR));
arraylist_events_stream.add(events_stream_bean);
}
}else {
Log.i("Test", "No Events Streams Available");
}
}
}catch(Exception e) {}
return arraylist_events_stream;
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
this.pd.setMessage("Loading....");
pd.setCanceledOnTouchOutside(false);
pd.setCancelable(false);
this.pd.show();
}
#Override
protected void onPostExecute(final ArrayList<EventsStreamBean> result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
if(this.pd.isShowing()) {
this.pd.dismiss();
}
Toast.makeText(EventStreamActivity.this, "Post shared successfully", Toast.LENGTH_SHORT).show();
new EventsStreamAsyncTask().execute(temp_val);
/*runOnUiThread(new Runnable() {
public void run() {
//EventStream_Customadapter adapter = (EventStream_Customadapter) list_view.getAdapter();
//adapter.clearData();
adapter.updateData(result);
//adapter = new EventStream_Customadapter(EventStreamActivity.this, arraylist_events_stream);
//list_view.setAdapter(adapter);
//adapter.notifyDataSetChanged();
}
});*/
}
}
Thank you

AsyncTask HttpParams

Could anyone help me on following questions.
1) onPostExecute - Toast.make while in background i am sending HttpRequest.
0nCraeteBunle - execute() ; startNewActivity
showing error. AsycTask# Runtime Exception .
While commenting Http request in background, no error is showed.
here, how can i know that http Request and reply finished , so that i can start my new Activity.
2) how to get HttpParams. Sending from TIBCO BE (As event with properties)
3) What if i am recieving JSONObject, JAVAObject, Integer other than String in onPostExecute. unable to override .
Try this,
protected class GetTask extends AsyncTask<Void, Void, Integer> {
protected void onPreExecute() {
mProgressDialog = ProgressDialog.show(MainActivity.this,
"Loading", "Please wait");
}
#Override
protected Integer doInBackground(Void... params) {
// TODO Auto-generated method stub
//call ur HttpRequest
httpRequest();
return 0;
}
protected void onPostExecute(Integer result) {
super.onPostExecute(result);
if (mProgressDialog.isShowing()) {
mProgressDialog.dismiss();
}
mHandler.sendEmptyMessage(0);
}
}
Handler mHandler = new Handler() {
public void handleMessage(Message Msg) {
if (Flag) {
//Add ur stuff
}else{
}
And then in ur method set Flag value
public void httpRequest() {
// TODO Auto-generated method stub
String URL ="ADD UR URL";
try {
JSONObject ResponseObject = mAPIService.CallAPI(
YourActivity.this, URL);
String status = ResponseObject.getString("status");
Flag = true;
} catch (Exception err) {
Flag = false;
}
}

How to Handle networkonmainthreadexception in Android?

I have following 2 class
class CallNetworkMethod extends AsyncTask<Void, Void, Void>
{
#Override
protected Void doInBackground(Void... params) {
if (TwitterUtils.isAuthenticated(prefs)) {
sendTweet();
} else {
Intent i = new Intent(getApplicationContext(), TwPrepareRequestTokenActivity.class);
i.putExtra("tweet_msg",getTweetMsg());
startActivity(i);
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
//updateLoginStatus();
loginStatus.setText("Logged into Twitter : " + TwitterUtils.isAuthenticated(prefs));
}
}
====================================================
public class TwitterUtils {
static ArrayList<String> friens=null;
public static boolean isAuthenticated(SharedPreferences prefs) {
String token = prefs.getString(OAuth.OAUTH_TOKEN, "");
String secret = prefs.getString(OAuth.OAUTH_TOKEN_SECRET, "");
AccessToken a = new AccessToken(token,secret);
Twitter twitter = new TwitterFactory().getInstance();
twitter.setOAuthConsumer(TwConstants.CONSUMER_KEY, TwConstants.CONSUMER_SECRET);
twitter.setOAuthAccessToken(a);
try {
**twitter.getAccountSettings();**
return true;
} catch (TwitterException e) {
return false;
}
}
}
I got the exception when running this code(networkonmainthreadexception).I debug this code and found the location where exception come out. It is twitter.getAccountSettings(); .I think this method should run inside a AsynTask but i dont know how to do that.
Currently you are calling TwitterUtils.isAuthenticated(prefs) in onPostExecute because onPostExecute always execute on UI thread then you are getting networkonmainthreadexception exception .
to avoid this issue use a Boolean Flag to get return from doInBackground and show it in TextView in onPostExecute as:
class CallNetworkMethod extends AsyncTask<Void, Void, Void>
{
public static boolean status=false;
#Override
protected Void doInBackground(Void... params) {
status=TwitterUtils.isAuthenticated(prefs);
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
//updateLoginStatus();
loginStatus.setText("Logged into Twitter : " + status);
}
}
the problem is that you're using the AsyncTask wrong.
The idea for the onBackground returning a value and the onPostExecute receiving a result is to pass to the UI thread something that was done on the background thread.
Something like that:
change the class CallNetworkMethod extends AsyncTask<Void, Void, Void> to
class CallNetworkMethod extends AsyncTask<Void, Void, Boolean>
change the protected Void doInBackground(Void... params) { to
protected Boolean doInBackground(Void... params) {
Boolean result = TwitterUtils.isAuthenticated(prefs);
if (result) {
sendTweet();
} else {
Intent i = new Intent(getApplicationContext(), TwPrepareRequestTokenActivity.class);
i.putExtra("tweet_msg",getTweetMsg());
startActivity(i);
}
return result;
}
and change the protected void onPostExecute(Void result) { to
protected void onPostExecute(Boolean result) {
loginStatus.setText("Logged into Twitter : " + result.toString());
}
Note that this method blocks waiting for a network response, so do not call it in a UI thread.
This is what is suggested when using:
facebook.request("me");
Same might be the case with:
twitter.getAccountSettings();
So, just like other Network connections, which you call using AsyncTasks, call this in some AsyncTask.
Okay, the Error might be here:
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
//updateLoginStatus();
loginStatus.setText("Logged into Twitter : " + TwitterUtils.isAuthenticated(prefs));
}
You are calling TwitterUtils.isAuthenticated(prefs) in onPostExecute();
Your first call to isAuthenticated() is correctly placed in the AsyncTask. However, when you use:
loginStatus.setText("Logged into Twitter : " + TwitterUtils.isAuthenticated(prefs));
in your onPostExecute(), you're calling a networking method on the UI thread again, as onPostExecute() is run on the UI thread.
Remove this line, or store the result locally from doInBackground() and use it here.

Categories

Resources