Log not working in AsyncTask - android

code for registering using asynctask :
import java.io.IOException;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;
import com.google.android.gms.gcm.GoogleCloudMessaging;
public class RegisterApp extends AsyncTask<Void, Void, String> {
private static final String TAG = "GCMRelated";
Context ctx;
GoogleCloudMessaging gcm;
String SENDER_ID = "10413";
String regid = null;
private int appVersion;
public RegisterApp(Context ctx, GoogleCloudMessaging gcm, int appVersion){
this.ctx = ctx;
this.gcm = gcm;
this.appVersion = appVersion;
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
}
#Override
protected String doInBackground(Void... params) {
String msg = "";
try{
if (gcm == null){
gcm = GoogleCloudMessaging.getInstance(ctx);
}
regid = gcm.register(SENDER_ID);
msg = "Device registered, registration ID=" + regid;
Log.i(TAG,msg);
} catch (IOException e){
msg = "Error: " + e.getMessage();
}
return msg;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Toast.makeText(ctx,
"Registration Completed. Now you can see the notifications",
Toast.LENGTH_SHORT)
.show();
Log.v(TAG, result);
}
}
Here toast is working in onPostExecute() but Log is not working anywhere.what i am trying to show is result and msg in Logcat.
More to know is where can i define log to place in information in Logcat? Do I have to do it in main UI thread or it can be done from anywhere in android system?
Here is Logcat:

Related

Error : method gettext() must be call from UI thread is worker

While working on a project I'm getting this error
Error : method gettext() must be call from UI thread is worker
on the following line :
String url = Util.send_chat_url+"?email_id="+editText_mail_id.getText().toString()+"&message="+editText_chat_message.getText().toString();
Please Help
This is my entire code for the class ChatActivity.java
package com.example.ankit.myapplication;
import android.app.Activity;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.support.annotation.NonNull;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import com.example.ankit.myapplication.XmppService;
import com.squareup.okhttp.OkHttpClient;
import org.jivesoftware.smack.packet.Message;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.Scanner;
//import services.XmppService;
public class ChatActivity extends Activity {
EditText editText_mail_id;
EditText editText_chat_message;
ListView listView_chat_messages;
Button button_send_chat;
List<ChatObject> chat_list;
BroadcastReceiver recieve_chat;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);
Scanner in = new Scanner(System.in);
XmppService xm= new XmppService();
Log.d("pavan","in chat "+getIntent().getStringExtra("user_id"));
Log.d("pavan","in chat server "+Util.SERVER);
XmppService.setupAndConnect(ChatActivity.this, Util.SERVER, "",
getIntent().getStringExtra("user_id"), Util.XMPP_PASSWORD);
editText_mail_id= (EditText) findViewById(R.id.editText_mail_id);
editText_chat_message= (EditText) findViewById(R.id.editText_chat_message);
listView_chat_messages= (ListView) findViewById(R.id.listView_chat_messages);
button_send_chat= (Button) findViewById(R.id.button_send_chat);
button_send_chat.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// send chat message to server
String message=editText_chat_message.getText().toString();
showChat("sent",message);
// new SendMessage().execute();
XmppService.sendMessage(ChatActivity.this, editText_mail_id.getText().toString() + Util.SUFFIX_CHAT, Message.Type.chat, message);
editText_chat_message.setText("");
}
});
recieve_chat=new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String message=intent.getStringExtra("message");
Log.d("pavan","in local braod "+message);
showChat("recieve",message);
}
};
LocalBroadcastManager.getInstance(this).registerReceiver(recieve_chat, new IntentFilter("message_recieved"));
}
private void showChat(String type, String message){
if(chat_list==null || chat_list.size()==0){
chat_list= new ArrayList<ChatObject>();
}
chat_list.add(new ChatObject(message,type));
ChatAdabter chatAdabter=new ChatAdabter(ChatActivity.this,R.layout.chat_view,chat_list);
listView_chat_messages.setAdapter(chatAdabter);
//chatAdabter.notifyDataSetChanged();
}
#Override
protected void onDestroy() {
super.onDestroy();
}
private class SendMessage extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
String url = Util.send_chat_url+"?email_id="+editText_mail_id.getText().toString()+"&message="+editText_chat_message.getText().toString();
Log.i("pavan", "url" + url);
OkHttpClient client_for_getMyFriends = new OkHttpClient();
String response = null;
// String response=Utility.callhttpRequest(url);
try {
url = url.replace(" ", "%20");
response = callOkHttpRequest(new URL(url),
client_for_getMyFriends);
for (String subString : response.split("<script", 2)) {
response = subString;
break;
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return response;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
//Toast.makeText(context,"response "+result,Toast.LENGTH_LONG).show();
}
}
// Http request using OkHttpClient
String callOkHttpRequest(URL url, OkHttpClient tempClient)
throws IOException {
HttpURLConnection connection = tempClient.open(url);
connection.setConnectTimeout(40000);
InputStream in = null;
try {
// Read the response.
in = connection.getInputStream();
byte[] response = readFully(in);
return new String(response, "UTF-8");
} finally {
if (in != null)
in.close();
}
}
byte[] readFully(InputStream in) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
for (int count; (count = in.read(buffer)) != -1;) {
out.write(buffer, 0, count);
}
return out.toByteArray();
}
}
Do not access the Android UI toolkit from outside the UI thread
Pass editText_mail_id.getText() and editText_chat_message.getText() as parameters to your async task or set it in onPreExecute to some variable
Like :
private class SendMessage extends AsyncTask<String, Void, String> {
private String mailId;
private String msgText;
#Override
protected void onPreExecute() {
super.onPreExecute();
mailId = editText_mail_id.getText().toString();
msgText = editText_chat_message.getText().toString();
}
Change url in doInBackground as :
String url = Util.send_chat_url+"?email_id="+mailId+"&message="+msgText;
you can create class for storing your parameter like i do,
Just create one class
example :
public class MyTaskParams
{
String mailId;
String message;
public MyTaskParams(String mailId, String message)
{
this.mailId = mailId;
this.message = message;
}
}
public class SendMessage extends AsyncTask<MyTaskParams, Void, String {
#Override
protected String doInBackground(MyTaskParams... params) {
String mailId = params[0].mailId;
String message = params[0].message;
String url = Util.send_chat_url+"?email_id="+ mailId +"&message="+ message;
}
}
so you can just call like this
MyTaskParams params = new MyTaskParams(editText_mail_id.getText().toString(),editText_chat_message.getText().toString());
SendMessage myTask = new SendMessage();
myTask.execute(params);
with this code you can call SendMessage Class from any activity, dont bind your asynctask with get text because if you do that you just can use SendMessage only in that activity
Hope this can help you.

run a service indefinitely

I am creating an application that sends and receives data from the server all the time. I need it to update the data as soon as possible, because every second is changing online data. I created this class, but it does not work, hangs at one time. Wonder if this "while (true)" is the correct way to do the functions run indefinitely because it does not find anything more like
package nilson.online; /**
* Created by nilso_000 on 23/07/2015.
*/
import android.app.Service;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import java.util.ArrayList;
import nilson.BancoDados;
//this class contains a basic instructions to open a web page and send a POST form
import static nilson.online.ServiceOnline.executaHttpPost;
public class ServiceFilaOnlineB extends Service {
String metodo="";
String url="";
ArrayList<NameValuePair> parametrosPost;
public SQLiteDatabase banco = null;
private BancoDados gerenciaBanco;
public ServiceFilaOnlineB(){}
#Override
public void onCreate() {
Toast.makeText(this, "Service was Created", Toast.LENGTH_LONG).show();
}
#Override
public void onDestroy() {
Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG).show();
}
#Override
public void onStart(Intent intent, int startId) {
try {
banco = openOrCreateDatabase("LNM", MODE_MULTI_PROCESS, null);
gerenciaBanco = new BancoDados();
gerenciaBanco.abrirBD(banco);
}catch (Exception e){
Log.e("LNM erro servico1", "error to init the service " + e);
onDestroy();
}try {
//Here I create the loop that will run indefinitely in android
//even to restart the system. It has two functions:
//1-check for updates offline and send then to the server online
//2-chec for updates online and copy then to the SQLite offline
while(true) {
//This is the records of updates offline
Cursor c = gerenciaBanco.getFilaOnline();
if (c.moveToFirst()) {
url = "http://192.168.10.100/lnm/add.php";
metodo = "POST";
Log.e("LNM Fila", "Size of fila: " + c.getCount());
do {
parametrosPost = new ArrayList<>();
parametrosPost.add(new BasicNameValuePair("SQL", c.getString(0)));
new InsertDataTask().execute(parametrosPost);
new GetDataTask().execute(parametrosPost);
} while (c.moveToNext());
}
Thread.sleep(5 * 1000);
}
}catch (Exception e){
Log.e("LNM erro servico2", "error to init the service " + e);
onDestroy();
}
}
private class InsertDataTask extends AsyncTask<ArrayList<NameValuePair>, String, String> {
protected void onPostExecute(String result){
Log.e("LNM Resultado", "Command executed "+result);
result = result.replaceAll("\\s+"," ").trim();
Log.e("LNM", "" + result.substring(0,6));
if("INSERT".equals(result.substring(0,6))) {
String res[]=result.split("\\|");
Log.e("LNM Comando Online", "The record was inserted int the db ONLINE and returned the ID " + res[1]);
}else
Log.e("LNM Conexao realizada", "Error " + result);
}
private String executa(ArrayList<NameValuePair>... params){
String result;
try {
result = executaHttpPost(url, params[0]);
Log.d("LNM Conectado"," Command executed "+result);
return result;
} catch (Exception e) {
Log.d("LNM Error on POST",""+e);
return executa(params);
}
}
#Override
protected String doInBackground(ArrayList<NameValuePair>... params) {
return executa(params);
}
}
private class GetDataTask extends AsyncTask<ArrayList<NameValuePair>, String, String> {
protected void onPostExecute(String result){
Log.e("LNM Resultado", "Command executed "+result);
result = result.replaceAll("\\s+"," ").trim();
Log.e("LNM", "" + result.substring(0,6));
//Separate results by | and insert in db
if("SUCESS".equals(result.substring(0,6))) {
String res[]=result.split("\\|");
Log.e("LNM Comando Online", "Data updated " + res[1]);
//Updating the record OFFLINE with the ID ONLINE
gerenciaBanco.updateMatch("online", res);
}else
Log.e("LNM Conexao realizada", "Error " + result);
}
private String executa(ArrayList<NameValuePair>... params){
String result;
try {
result = executaHttpPost(url, params[0]);
Log.d("LNM Conectado"," Command executed "+result);
return result;
} catch (Exception e) {
Log.d("LNM Error on POST",""+e);
return executa(params);
}
}
#Override
protected String doInBackground(ArrayList<NameValuePair>... params) {
return executa(params);
}
}
#Override
public IBinder onBind(Intent intent) {
throw new UnsupportedOperationException("Not yet implemented");
}
}

IntentService does not work android

My code receives no crash errors. When I run the App and click the button, a Toast should show, but it doesn't.
Here is my IntentService
package com.example.flas;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.example.flas.JSONParser;
import android.app.IntentService;
import android.content.Intent;
import android.os.Bundle;
import android.os.ResultReceiver;
import android.util.Log;
import android.widget.Toast;
public class SampleIntentService extends IntentService {
public static final int DOWNLOAD_ERROR = 10;
public static final int DOWNLOAD_SUCCESS = 11;
String latbus;
String lonbus;
String latsta;
String Employernumber;
String lonsta;
String numrout;
String nomsta;
JSONParser jsonParser = new JSONParser();
private static final String url_product_detials = "http://********/get_loc_details2.php";
private static final String TAG_IDLOCBUS = "idlocbus";
private static final String TAG_BUSNUMBER = "BusNumber";
private static final String TAG_BUSLATITUDE = "BusLatitude";
private static final String TAG_BUSLONGITUDE = "Buslongitude";
private static final String TAG_SUCCESS = "success";
private static final String TAG_PRODUCT = "product";
public SampleIntentService() {
super(SampleIntentService.class.getName());
// TODO Auto-generated constructor stub
}
#Override
protected void onHandleIntent(Intent intent) {
// TODO Auto-generated method stub
String url = intent.getStringExtra("url");
final ResultReceiver receiver = intent.getParcelableExtra("receiver");
Bundle bundle = new Bundle();
try {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("pid", url));
// getting JSON Object
// Note that create product url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(
url_product_detials, "GET", params);
// check log cat fro response
Log.d("Create Response", json.toString());
// check for success tag
int success = json.getInt(TAG_SUCCESS);
// successfully received product details
JSONArray productObj = json
.getJSONArray(TAG_PRODUCT); // JSON Array
// get first product object from JSON Array
JSONObject product = productObj.getJSONObject(0);
// product with this pid found
// display product data in EditText
String aa = product.getString(TAG_IDLOCBUS);
String bb = product.getString(TAG_BUSNUMBER);
String latb = product.getString(TAG_BUSLATITUDE);
String lonb = product.getString(TAG_BUSLONGITUDE);
bundle.putString("filePath", lonb + latb);
receiver.send(DOWNLOAD_SUCCESS, bundle);
} catch (Exception e) {
// TODO: handle exception
receiver.send(DOWNLOAD_ERROR, Bundle.EMPTY);
e.printStackTrace();
}
}
}
My MainActivity that calls my IntentService
public class MainActivity extends Activity implements OnClickListener {
ProgressBar pd;
SampleResultReceiver resultReceiever;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
resultReceiever = new SampleResultReceiver(new Handler());
pd = (ProgressBar) findViewById(R.id.downloadPD);
}
private class SampleResultReceiver extends ResultReceiver {
public SampleResultReceiver(Handler handler) {
super(handler);
// TODO Auto-generated constructor stub
}
#Override
protected void onReceiveResult(int resultCode, Bundle resultData) {
// TODO Auto-generated method stub
switch (resultCode) {
case SampleIntentService.DOWNLOAD_ERROR: {
Toast.makeText(getApplicationContext(), "error in download", Toast.LENGTH_SHORT).show();
pd.setVisibility(View.INVISIBLE);
}
break;
case SampleIntentService.DOWNLOAD_SUCCESS: {
String filePath = resultData.getString("filePath");
Toast.makeText(getApplicationContext(), "image download via IntentService is done", Toast.LENGTH_SHORT).show();
pd.setIndeterminate(false);
pd.setVisibility(View.INVISIBLE);
}
break;
}
super.onReceiveResult(resultCode, resultData);
}
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent startIntent = new Intent(MainActivity.this, SampleIntentService.class);
startIntent.putExtra("receiver", resultReceiever);
String aaa = "5";
startIntent.putExtra("url", aaa);
startService(startIntent);
pd.setVisibility(View.VISIBLE);
pd.setIndeterminate(true);
}
public void onClick2(View v) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "image download via IntentService is done", Toast.LENGTH_SHORT).show();
}
}
My JSON Class works fine, I tried it in another App and I got not error.
In my AndroidManifest.xml ...
I tried this:
<service android:name="com.example.pfecuspart.SampleIntentService"
android:exported="false">
<intent-filter>
<action android:name="org.example.android.myservicedemo.IService" />
</intent-filter>
</service>
I also tried this:
<service android:name="com.example.pfecuspart.SampleIntentService"
android:enabled="true">
</service>
I dont think onClick2 is doing anything, its not overriding the onClick.
do you need to move;
Toast.makeText(getApplicationContext(),
"image download via IntentService is done",
Toast.LENGTH_SHORT).show();
from onClick2, to onClick.
Maybe try replacing getApplicationContext() with MainActivity.this

Trouble with using OAuth LinkedIN for Android SDK

I am trying to run an OAuth in my android app to get user data from LinkedIn and as i just started on the project i have run into a major bug/issue. After requesting the token from the following code, the token doesn't get received and the app continues to open in the on-phone browser used for the authentication.
Any help would be appreciated as I am really new to android development.
package com.tushar.linkedinauth;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import com.google.code.linkedinapi.client.LinkedInApiClient;
import com.google.code.linkedinapi.client.LinkedInApiClientFactory;
import com.google.code.linkedinapi.client.oauth.LinkedInAccessToken;
import com.google.code.linkedinapi.client.oauth.LinkedInOAuthService;
import com.google.code.linkedinapi.client.oauth.LinkedInOAuthServiceFactory;
import com.google.code.linkedinapi.client.oauth.LinkedInRequestToken;
public class MainActivity extends Activity {
public static final String CONSUMER_KEY = "MyConsumerKey";
public static final String CONSUMER_SECRET = "MyConsumerSecret";
public static final String OAUTH_CALLBACK_SCHEME = "x-oauthflow-linkedin";
public static final String OAUTH_CALLBACK_HOST = "callback";
public static final String OAUTH_CALLBACK_URL = OAUTH_CALLBACK_SCHEME + "://" + OAUTH_CALLBACK_HOST;
final LinkedInOAuthService oAuthService = LinkedInOAuthServiceFactory.getInstance().createLinkedInOAuthService(CONSUMER_KEY, CONSUMER_SECRET);
final LinkedInApiClientFactory factory = LinkedInApiClientFactory.newInstance(CONSUMER_KEY, CONSUMER_SECRET);
LinkedInRequestToken liToken;
LinkedInApiClient client;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button b=(Button)findViewById(R.id.button1);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
new AutheticateLinkedIn().execute();
}
});
Log.d("Token", " Starting Task");
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
if(liToken!=null)
{
Log.d("Token", "New Intent Recieved");
String verifier = getIntent().getData().getQueryParameter("oauth_verifier");
LinkedInAccessToken accessToken = oAuthService.getOAuthAccessToken(liToken, verifier);
client = factory.createLinkedInApiClient(accessToken);
Log.d("Token", "Posting update");
client.postNetworkUpdate("LinkedIn Android app test");
Log.d("Token", "Update Posted");
}
}
// #Override
// protected void onNewIntent(Intent intent) {
// // TODO Auto-generated method stub
// super.onNewIntent(intent);
//
// }
public class AutheticateLinkedIn extends AsyncTask<Void, Long, Boolean>
{
#Override
protected Boolean doInBackground(Void... params) {
// TODO Auto-generated method stub
Log.d("Token", " Requested");
liToken = oAuthService.getOAuthRequestToken(OAUTH_CALLBACK_URL);
Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(liToken.getAuthorizationUrl()));
startActivity(i);
return true;
}
#Override
protected void onPostExecute(Boolean result){
Log.d("Token", " Recieved");
// mDialog.cancel();
}
}
}

AsyncTask is not working properly in android 4.0

I have this async Task on android 2.3.5
class InternetConnexionErrorAsync extends AsyncTask<String, String, String>
{
#Override
protected void onPreExecute() {
super.onPreExecute();
mdpiImageView.setClickable(false);
journalsImageView.setClickable(false);
accountImageView.setClickable(false);
Toast.makeText(getBaseContext(),errorMessage , Toast.LENGTH_LONG).show();
}
#Override
protected String doInBackground(String... aurl) {
try {
Thread.sleep(3450);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String unused)
{
finish();
}
}
Everything is working well.
When I try this in Android 4.0, I am newer accessint the onPostExecute.
Could you please help me. No error message, only that the onPostExecute is newer reached.
Whatever you need to update on the UI you need to do in onPostExecute.
The code below, take a look at onPostExecute - specifically the activity.xx() methods send updates to the main activity that do things on the UI.
For example:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import library.DatabaseHandler;
import library.JSONParser;
import library.UserFunctions;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import com.actionbarsherlock.R;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class LoginTask extends AsyncTask<String, Void, Integer> {
private ProgressDialog progressDialog;
private Polling activity;
private int id = -1;
private JSONParser jsonParser;
private static String loginURL = "http://davidjkelley.net/android_api/";
private static String registerURL = "http://davidjkelley.net/android_api/";
private static String KEY_SUCCESS = "success";
private static String KEY_ERROR = "error";
private static String KEY_ERROR_MSG = "error_msg";
private static String KEY_UID = "uid";
private static String KEY_NAME = "name";
private static String KEY_EMAIL = "email";
private static String KEY_CREATED_AT = "created_at";
private int responseCode = 0;
public LoginTask(Polling activity, ProgressDialog progressDialog)
{
this.activity = activity;
this.progressDialog = progressDialog;
}
#Override
protected void onPreExecute()
{
progressDialog.show();
}
protected Integer doInBackground(String... arg0) {
EditText userName = (EditText)activity.findViewById(R.id.emailEditText);
EditText passwordEdit = (EditText)activity.findViewById(R.id.passEditText);
String email = userName.getText().toString();
String password = passwordEdit.getText().toString();
UserFunctions userFunction = new UserFunctions();
JSONObject json = userFunction.loginUser(email, password);
// check for login response
try {
if (json.getString(KEY_SUCCESS) != null) {
String res = json.getString(KEY_SUCCESS);
if(Integer.parseInt(res) == 1){
//user successfully logged in
// Store user details in SQLite Database
DatabaseHandler db = new DatabaseHandler(activity.getApplicationContext());
JSONObject json_user = json.getJSONObject("user");
//Log.v("name", json_user.getString(KEY_NAME));
// Clear all previous data in database
userFunction.logoutUser(activity.getApplicationContext());
db.addUser(json_user.getString(KEY_NAME), json_user.getString(KEY_EMAIL),
json.getString(KEY_UID), json_user.getString(KEY_CREATED_AT));
responseCode = 1;
// Close Login Screen
//finish();
}else{
responseCode = 0;
// Error in login
}
}
} catch (NullPointerException e) {
e.printStackTrace();
}
catch (JSONException e) {
e.printStackTrace();
}
return responseCode;
}
#Override
protected void onPostExecute(Integer responseCode)
{
EditText userName = (EditText)activity.findViewById(R.id.emailEditText);
EditText passwordEdit = (EditText)activity.findViewById(R.id.passEditText);
if (responseCode == 1) {
progressDialog.dismiss();
activity.loginReport(responseCode);
userName.setText("");
passwordEdit.setText("");
//shared prefences, store name
}
if (responseCode == 0) {
progressDialog.dismiss();
activity.loginReport(responseCode);
}
//if(responseCode == 202)
//activity.login(id);
//else
//activity.showLoginError("");
}
}
Here's the main activity, you can see what loginReport does:
public class Polling extends SherlockFragmentActivity {
private ViewPager mViewPager;
private TabsAdapter mTabsAdapter;
private final static String TAG = "21st Polling:";
private Button loginButton;
private Button registerButton;
private CheckBox remember;
SharedPreferences sharedPreferences;
Toast toast;
ActionBar bar;
//DatabaseHandler ;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.v(TAG, "onCreate");
mViewPager = new ViewPager(this);
mViewPager.setId(R.id.pager);
setContentView(mViewPager);
bar = getSupportActionBar();
bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
bar.setDisplayShowTitleEnabled(false);
bar.setDisplayShowHomeEnabled(false);
mTabsAdapter = new TabsAdapter(this, mViewPager);
mTabsAdapter.addTab(bar.newTab().setText(R.string.login),
LoginFragment.class, null);
mTabsAdapter.addTab(bar.newTab().setText(R.string.economics),
EconFragment.class, null);
mTabsAdapter.addTab(bar.newTab().setText(R.string.elections),
ElectionsFragment.class, null);
mTabsAdapter.addTab(bar.newTab().setText(R.string.politics),
PoliticsFragment.class, null);
mTabsAdapter.addTab(bar.newTab().setText(R.string.science),
ScienceFragment.class, null);
mTabsAdapter.addTab(bar.newTab().setText(R.string.finance),
FinanceFragment.class, null);
mTabsAdapter.addTab(bar.newTab().setText(R.string.religion),
ReligionFragment.class, null);
mTabsAdapter.addTab(bar.newTab().setText(R.string.military),
MilitaryFragment.class, null);
mTabsAdapter.addTab(bar.newTab().setText(R.string.international),
InternationalFragment.class, null);
}
public void loginReport(int responseCode) {
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
UserFunctions userFunctions = new UserFunctions();
Context context = getApplicationContext();
//login succeeded, sent when LoginTask doInBg sends a 1 to onPostExecute
if (responseCode == 1) {
loginButton = (Button)findViewById(R.id.loginButton);
loginButton.setText("Log Out");
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, "Logged in.", duration);
toast.show();
bar.getTabAt(0).setText(db.getUserDetails().get(db.KEY_EMAIL));
//Log.v(TAG, db.getUserDetails().toString());
}
//login failed, sent when LoginTask doInBg sends a 0 to onPostExecute
if (responseCode == 0) {
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, "Incorrect username/password", duration);
toast.show();
}
if (responseCode == 2) {
//logout button clicked, listened from within LoginFragment
//remove user from active sql db here rather than LoginFragment?!
bar.getTabAt(0).setText(R.string.login);
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, "Logged out", duration);
toast.show();
userFunctions.logoutUser(context);
}
}
The solution I adopted, after the suggestion of #Davek804 is that I replace the AsyncTask with a delayed runable like this:
private Runnable mMyRunnable = new Runnable()
{
public void run()
{
finish();
}
};
Toast.makeText(getBaseContext(),errorMessage , Toast.LENGTH_LONG).show();
Handler myHandler = new Handler();
myHandler.postDelayed(mMyRunnable, 3450);
So the effect will be the same.
I found the solution here
Instead of using :
task.execute();
use :
task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, null);

Categories

Resources