I'm trying to execute AsyncTask but when AsyncTask start and doInBackground finish (value returned), it is skipping the OnPostExecute and running the code requestTask2.execute() below, before i change the value in OnPostExecute, it is trying to run if condition so i'm getting null.
Let me explain with the code :
public void onClick(DialogInterface dialog,int id) {
Intent gt = new Intent(MainActivity.this, favorite.class);
String password = userInput.getText().toString();
String kadi = userInput2.getText().toString();
RequestTask2 requestTask2 = new RequestTask2();
requestTask2.execute("http://www.example.com/androfav/?fav2="+kadi+":"+password).get();
if (asd2[0][0]!=null && asd2[1][0]!=null ) {
// This if condition works before on Post Excecute and it is causing the problem.
if (asd2[0][0].equals(password) && asd2[1][0].endsWith(kadi) ) {
// Codes
}}
class RequestTask2 extends AsyncTask<String, String, String> {
private ProgressDialog dialog = new ProgressDialog(MainActivity.this);
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
dialog.setMessage("Diziler Yükleniyor \n Lütfen Bekleyin...");
dialog.show();
dialog.setCancelable(false);
}
#Override
protected String doInBackground(String... uri2) {
HttpClient httpclient2 = new DefaultHttpClient();
HttpResponse response2;
String responseString2 = null;
try {
response2 = httpclient2.execute(new HttpGet(uri2[0]));
StatusLine statusLine2 = response2.getStatusLine();
if (statusLine2.getStatusCode() == HttpStatus.SC_OK) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
response2.getEntity().writeTo(out);
out.close();
responseString2 = out.toString();
} else {
// Closes the connection.
response2.getEntity().getContent().close();
throw new IOException(statusLine2.getReasonPhrase());
}
} catch (ClientProtocolException e) {
// TODO Handle problems..
} catch (IOException e) {
// TODO Handle problems..
}
return responseString2;
}
#Override
protected void onPostExecute(String result2) {
super.onPostExecute(result2);
try {
JSONArray jsonResponse2 = new JSONArray(result2);
asd2 = new String[3][jsonResponse2.length()];
//............................... Codes
dialog.dismiss();
}
}
How can i wait for OnPostExecute before the if condition works.
Hope i could understand myself.
Thanks in advance.
AsyncTask as the name suggests is Asynchronous. You need to move the if condition to onPostExecute.
Move the below to onPostExecute
JSONArray jsonResponse2 = new JSONArray(result2);
asd2 = new String[3][jsonResponse2.length()];
if (asd2[0][0]!=null && asd2[1][0]!=null ) {
if (asd2[0][0].equals(password) && asd2[1][0].endsWith(kadi) ) {
// Codes
}
}
Edit:
I din't notice you called get(). Calling get() makes Asynctask no more asynchronous. You should never call get() just execute() is enough.
Why do you need to call get() which blocks the ui thread waiting for the task to be finished.
You should always avoid calling get() when using AsyncTask. Instead, do all of your post-processing in onPostExecute
#Override
protected void onPostExecute(String result2) {
super.onPostExecute(result2);
try {
JSONArray jsonResponse2 = new JSONArray(result2);
asd2 = new String[3][jsonResponse2.length()];
if (asd2[0][0]!=null && asd2[1][0]!=null ) {
if (asd2[0][0].equals(password) && asd2[1][0].endsWith(kadi) ) {
// Codes
}
}
}
dialog.dismiss();
}
Related
i'm developing an android App.
The user registration process calls a service that sends an email so it takes several seconds, like 5 or 6 seconds,that's why I execute that task within a thread. The problem is, the Dialog is never dismissing. It stays rolling and the user can do nothing. Here's my code:
try
{
final ProgressDialog progDailog = new ProgressDialog(ActividadAltaUsuario.this);
new Thread(new Runnable()
{
#Override
public void run()
{
try
{
URL url = new URL("slowWS");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
InputStream in = new BufferedInputStream(conn.getInputStream());
String response = IOUtils.toString(in, "UTF-8");
final JSONObject jsonPrincipal = new JSONObject(response);
Boolean success = jsonPrincipal.get("status").toString() == "true";
if (success)
{
ActividadAltaUsuario.this.runOnUiThread(new Runnable() {
#Override
public void run() {
progDailog.show(ActividadAltaUsuario.this, "Sendind email");
}
});
final String idUsuario = jsonPrincipal.get("idUsuario").toString();
URL url2 = new URL("anotherSlowWS");
HttpURLConnection conn2 = (HttpURLConnection) url2.openConnection();
conn2.setRequestMethod("POST");
InputStream in2 = new BufferedInputStream(conn2.getInputStream());
String response2 = IOUtils.toString(in2, "UTF-8");
JSONObject jsonRtaMail = new JSONObject(response2);
//finish();
}
else
{
//finish();
showToast(jsonPrincipal.get("message").toString());
}
ActividadAltaUsuario.this.runOnUiThread(new Runnable() {
#Override
public void run() {
progDailog.dismiss();
}
});
}
catch (Exception e)
{
e.printStackTrace();
}
}
}).start();
}
catch(Exception e)
{
Log.e("log_tag", "Error in http connection" + e.toString());
}
Can anybody help me?
Thanks!
AsyncTask would be a better approach instead of thread, Replace your network call from thread to use AsyncTask. You can use something like this
private class LongOperation extends AsyncTask<Void, Void, Void> {
#Override
protected String doInBackground(Void... params) {
//Main stuff that needs to be done in background
}
#Override
protected void onPostExecute(Void result) {
//Post Execution this method will be called, handle result accordingly
//You can dismiss your dialog here
}
#Override
protected void onPreExecute() {
//Do initialization relative stuff here
// Initialize your dialog here.
}
}
As both onPostExecute() and onPreExecute() work on main thread you can show and dismiss your dialog in this methods.
The UI controls have to be accessed only from the UI thread.
Usually I do this in class that extends AsyncTask
Something like:
public class MyTask extends AsyncTask {
protected void onPreExecute() {
//create and display your alert here
progDialog = ProgressDialog.show(MyActivity.this,"Please wait...", "Logging ...", true);
}
protected Void doInBackground(Void... unused) {
// here is the thread's work ( what is on your method run()
...
// if we want to show some progress in UI, then call
publishProgress(item)
}
protected void onProgressUpdate(Item... item) {
// theoretically you can show the progress here
}
protected void onPostExecute(Void unused) {
//dismiss dialog here where the thread has finished his work
progDialog.dismiss();
}
}
LE:
More detalis about AsyncTask https://developer.android.com/reference/android/os/AsyncTask
check especially the Protected Methods
I am new to Android Development. I am setting a debugger points in a code and trying to check how JSON results are present inside doInbackground and postexecute() method by using AsyncTask().
I am unable to do debugging since it is coming out of the window after preExecute() completes.
Even in real time, the app is not getting crashed, after progress dialog bar got dismissed, it is taking me to Home page.
I need to debug even doInbackground and postExecute() method. What mistake could I have done here?
new MakeRequestAndResponse().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, edtPhone,
edtPass, "android", gcmToken, version, mAndroidId);
class MakeRequestAndResponse extends AsyncTask<String, Integer, String> {
private ProgressDialog pr;
#Override
protected void onPreExecute() {
super.onPreExecute();
pr = new ProgressDialog(Activity_Login.this);
s = new SpannableString("Verifying credentials..");
s.setSpan(new TypefaceSpan(Activity_Login.this, "Lato-Regular.ttf"), 0, s.length(),
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
pr.setMessage(s);
pr.setIndeterminate(false);
pr.setCancelable(false);
pr.show();
}
#Override
protected String doInBackground(String... param) {
JSONObject jsonObj = null;
try {
try {
jsonObj = makeRequest(param[0], param[1], param[2], param[3], param[4], param[5]);
} catch (Exception e) {
}
if (jsonObj == null) {
return "null response";
} else {
return jsonObj.toString();
}
} catch (Exception e) {
return "null response";
}
}
#Override
protected void onPostExecute(String json) {
if (pr.isShowing() && pr != null) {
pr.dismiss();
}
Log.d(TAG, json);
System.out.println("Login Json Response:"+json);
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;
}
}
I am trying to use ProgressDialog. when i run my app the Progress Dialog box show and disappear after 1 second. I want to show it on completion of my process.. Here is my code:
public class MainActivity extends Activity {
android.view.View.OnClickListener mSearchListenerListener;
private ProgressDialog dialog;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new YourCustomAsyncTask().execute(new String[] {null, null});
}
private class YourCustomAsyncTask extends AsyncTask <String, Void, Void> {
protected void onPreExecute() {
dialog = new ProgressDialog(MainActivity.this);
dialog.setMessage("Loading....");
dialog.setIndeterminate(true);
dialog.setCancelable(true);
dialog.show(); //Maybe you should call it in ruinOnUIThread in doInBackGround as suggested from a previous answer
}
protected void doInBackground(String strings) {
try {
// search(strings[0], string[1]);
runOnUiThread(new Runnable() {
public void run() {
// updateMapWithResult(); //Or call it onPostExecute before progressDialog's dismiss. I believe this method updates the UI so it should run on UI thread
}
});
} catch(Exception e) {
}
}
#Override
protected void onPostExecute(Void params) {
dialog.dismiss();
//result
}
#Override
protected Void doInBackground(String... params) {
// TODO Auto-generated method stub
return null;
}
}
}
Updated Question:
#Override
public void onCreate(SQLiteDatabase db) {
mDatabase = db;
Log.i("PATH",""+mDatabase.getPath());
mDatabase.execSQL(FTS_TABLE_CREATE);
loadDictionary();
}
/**
* Starts a thread to load the database table with words
*/
private void loadDictionary() {
new Thread(new Runnable() {
public void run() {
try {
loadWords();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}).start();
}
private void loadWords() throws IOException {
Log.d(TAG, "Loading words...");
for(int i=0;i<=25;i++)
{ //***//
final Resources resources = mHelperContext.getResources();
InputStream inputStream = resources.openRawResource(raw_textFiles[i]);
//InputStream inputStream = resources.openRawResource(R.raw.definitions);
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
try {
StringBuilder sb = new StringBuilder();
while ((word = reader.readLine()) != null)
{
sb.append(word);
// Log.i("WORD in Parser", ""+word);
}
String contents = sb.toString();
StringTokenizer st = new StringTokenizer(contents, "||");
while (st.hasMoreElements()) {
String row = st.nextElement().toString();
String title = row.substring(0, row.indexOf("$$$"));
String desc = row.substring(row.indexOf("$$$") + 3);
// Log.i("Strings in Database",""+title+""+desc);
long id = addWord(title,desc);
if (id < 0) {
Log.e(TAG, "unable to add word: " + title);
}
}
} finally {
reader.close();
}
}
Log.d(TAG, "DONE loading words.");
}
I want to show ProgressDialogue box untill all words are not entered in the database. This code is in inner calss which extends SQLITEHELPER. so how to can i use ProgressDialogue in that inner class and run my addWords() method in background.
You cannot have this
runOnUiThread(new Runnable() {
public void run() {
// updateMapWithResult(); //Or call it onPostExecute before progressDialog's dismiss. I believe this method updates the UI so it should run on UI thread
}
});
in your doInBackground().
Progress dialog doesn't take priority when there is some other action being performed on the main UI thread. They are intended only when the actions are done in the background. runonUIthread inside doInBackground will not help you. And this is normal behavior for the progressdialog to be visible only for few seconds.
You have two doInBackground() methods inside your AsyncTask Class. Remove the runOnUiThread() from First doInBackground() and move it to second doInBackground() which has #Override annotation.
I don't know whether you wantedly written two doInBackground() methods or by mistake but it is not good to have such confusion between the Method. Your AsyncTask is not calling the first doInBackground() and it will call doInBackground() which has #Override annotation. So your ProgressDialog is dismissed in 1 second of time as it returns null immediately.
Hello
I'm loading Tweets from a user account to show in a listview. Now I want to let the users know what's going on while they're waiting. I've implementend Async Task, but for some reason, onPostExcecute is never called. That's why the dialog is never removed.
Can someone give me a hint.. What am I doing wrong?
I can post my TweetAdapterClass if that's needed
This is my AsyncClass
public class ProgressTask extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
dialog.setTitle("Even geduld...");
dialog.setMessage("De tweets worden ingeladen...");
dialog.show();
}
protected void onPostExecute() {
try {
if (dialog.isShowing()) {
adaptor = new TweetListAdaptor(MainActivity.this, R.layout.tweetitem, loadTweets());
setListAdapter(adaptor);
dialog.dismiss();
}
} catch (Exception e) {
}
}
#Override
protected Void doInBackground(Void... arg0) {
return null;
}
}
LoadTweets looks like this:
private ArrayList<Tweets> loadTweets() {
ArrayList<Tweets> tweets = new ArrayList<Tweets>();
try {
HttpClient hc = new DefaultHttpClient();
HttpGet get = new HttpGet(
"http://search.twitter.com/search.json?q=JobXXL_be&rpp=10");
// HttpGet get = new
// HttpGet("http://search.twitter.com/search.json?q=Stijn_messiaen&rp=10");
HttpResponse rp = hc.execute(get);
if (rp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
String result = EntityUtils.toString(rp.getEntity());
JSONObject root = new JSONObject(result);
JSONArray sessions = root.getJSONArray("results");
for (int i = 0; i < sessions.length(); i++) {
JSONObject session = sessions.getJSONObject(i);
Tweets tweet = new Tweets();
tweet.setTweet(session.getString("text"));
tweet.setUser(session.getString("from_user"));
// datum vertalen
String date = session.getString("created_at").substring(5,
16);
String[] arrDate = date.split(" ");
int id = this.getResources().getIdentifier(
arrDate[1].toString(), "string",
this.getPackageName());
String maand = getResources().getString(id);
date = arrDate[0].toString() + " " + maand + " "
+ arrDate[2].toString();
tweet.setDate(date);
tweets.add(tweet);
}
}
} catch (Exception e) {
Log.e("TwitterFeedActivity", "Error loading JSON", e);
}
return tweets;
}
EDIT: I added my LoadTweets() in my doInBackgroundMethod and that solved my problems!
Try declaring the ProgressDialog dialog in the main class in which your AsyncTask class exists and only call the dialog.show and dialog.dismiss method in the AsyncTask class.
Use onCreateDialog(int id) in activity to create ProgressDialog. In AsyncTask call:
MainActivity.this.showDialog(PROGRESS_DIALOG_ID);
To dismiss:
MainActivity.this.dismissDialog(PROGRESS_DIALOG_ID);
Dialogs are connected with activity's context. When activity is recreated dialog should be recreated too but then instance of the dialog is not the same.
I had the same problems and yeah this happened to me when onPostExecute didn't match the declaration... try something like protected Void onPostExecute(Void... arg0)
Next thing to do is to put Log.d("Your app", "Location of this code"); and check which part doesn't execute on Log file ...
Hope u will find the solution...
onPostExecute() does not match the declaration Void. I am on the road so off the top of my head consider:
protected void onPostExecute(Void result)
More here.
Hmm, two things come to mind here..
1) Why is your onPostExecute not overridden like the onPreExecute and doInBackground?
2) Why is the doInBackground after the onPost Execute? Generally the order is
onPreExecute
doInBackground
onPostExecute