AsyncTask doInBackGround is not called - android

I've created an AsyncTask for my app but doinbackground method is not called upon onpreexecute. Here is my code:
public class NewProductActivity extends AsyncTask<String,Void,Boolean>{
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = ProgressDialog.show(context, "Please wait", "Sending data...", true);
}
#Override
protected Boolean doInBackground(String... params) {
try {
boolean added = dbo.addDataToDB(name, pass);
Log.d("1234rrr", name +" "+pass);
return added;
}
catch(Exception e){
e.printStackTrace();
return false;
}
}
#Override
protected void onPostExecute(Boolean result) {
if(result){
Toast.makeText(context, "successfully added.", Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(context, "failed to add data.", Toast.LENGTH_SHORT).show();
}
progressDialog.dismiss();
}
}
And here is how I call it:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
new NewProductActivity(UserName.getText().toString(), Password.getText().toString(), this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
else
new NewProductActivity(UserName.getText().toString(),Password.getText().toString(),this).execute();
But the app is stuck on onpreexecute. By the way I have only one asynctask. Can anyone help me with this situation? Thanks!
Edit:
I've realized that when I put the log message in the first line of doinbackground I get the message. I'm guessing the problem is with addDataToDB function. Here is the code for addDataToDB:
public boolean addDataToDB(String name, String pass){
try{
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://www.sample.com/phpfilelocation/insertData.php");
List<NameValuePair> nameValuePairs = new ArrayList<>();
nameValuePairs.add(new BasicNameValuePair("name", name));
nameValuePairs.add(new BasicNameValuePair("pass", pass));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
httpclient.execute(httpPost);
return true;
}
catch (Exception ex) {
ex.printStackTrace();
return false;
}
}
catch(Exception e){
e.printStackTrace();
return false;
}
}

Related

Toast from onProgressUpdate not showing up

Everything is working fine but the Toast from the onProgressUpdate is not showing up. I am surely doing something wrong. Please help me out.
The Code is:
private class MyTask extends AsyncTask<String, String, String> {
protected String doInBackground(String... params) {
publishProgress("Sending...");
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.projectyourself.96.lt/android.php");
//HttpPost httppost = new HttpPost("http://www.yembed.in/loans4you/form.php");
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("message", params[0]));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
httpclient.execute(httppost);
}catch (Exception e){
return "fail";
}
return "sent";
}
protected void onProgressUpdate(String i) {
super.onProgressUpdate(i);
Toast.makeText(getBaseContext(),i,Toast.LENGTH_SHORT).show();
}
protected void onPostExecute(String r) {
if(r=="sent") {
t.setText("");
Toast.makeText(getBaseContext(), "Sent", Toast.LENGTH_SHORT).show();
}
else
Toast.makeText(getBaseContext(),"Not Sent!",Toast.LENGTH_SHORT).show();
}
}
The parameter in the method onProgressUpdate(String... values) has to be an array. You created a whole new method that is never actually called.
To fix your problem, change this:
protected void onProgressUpdate(String i) {
super.onProgressUpdate(i);
Toast.makeText(getBaseContext(),i,Toast.LENGTH_SHORT).show();
}
to this:
protected void onProgressUpdate(String... i) {
super.onProgressUpdate(i);
Toast.makeText(getBaseContext(),i[0],Toast.LENGTH_SHORT).show();
}

asynctask sqlite doesnt update

I am making a register screen for my project. After register data is sent to web database I want the app also update local sqlite database so that the next time user opens the app, he/she doesn't need to do the same operations if the register is successfull. My app is updating the web database with no problem but when I try to do sqlite update with a second asynctask it doesn't update sqlite, what am I missing? :(
Here is my code
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.register);
final EditText vmail=(EditText) findViewById(R.id.editText1);
final EditText vpassword=(EditText) findViewById(R.id.editText2);
final EditText vnickname=(EditText) findViewById(R.id.editText3);
Button button2=(Button) findViewById(R.id.button1);
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mail=vmail.getText().toString();
password=vpassword.getText().toString();
mynickname=vnickname.getText().toString();
new AsyncTaskClass().execute();
}
});
}
class AsyncTaskClass extends AsyncTask<Void, Void, String> {
#Override
protected void onPreExecute() {
}
#Override
protected String doInBackground(Void... params) {
String reverseString =null;
try
{
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("mail",mail));
nameValuePairs.add(new BasicNameValuePair("password",password));
nameValuePairs.add(new BasicNameValuePair("mynickname",mynickname));
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("wwwmysite.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String response = httpclient.execute(httppost, responseHandler);
reverseString = response;
} catch (ClientProtocolException e) {
Log.e("log_tag", "Error converting result " + e.toString());
} catch (IOException e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
return reverseString;
}
protected void onPostExecute(String reverseString) {
if (reverseString.contains("success")){
new AsyncTaskClass2().execute();
}else{
Toast.makeText(getApplicationContext(), reverseString, Toast.LENGTH_LONG).show();
}
}
}
class AsyncTaskClass2 extends AsyncTask<Void, Void, String> {
#Override
protected void onPreExecute() {
}
#Override
protected String doInBackground(Void... params) {
String reverseString =null;
try
{
KayitEkle(Array.get(nameValuePairs, 0).toString(),Array.get(nameValuePairs, 1).toString(),Array.get(nameValuePairs, 2).toString());
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
return reverseString;
}
protected void onPostExecute(String reverseString) {
startActivity(new Intent(registergame.this, (mygamescreen.class)));
}
}
private void KayitEkle(String nick, String mail, String password){
SQLiteDatabase db = users.getWritableDatabase();
ContentValues veriler = new ContentValues();
veriler.put("nick", nick);
veriler.put("mail",mail);
veriler.put("password",password);
db.insertOrThrow("ogrenciisim", null, veriler);
}
}
Put a debugger to see if it is actually calling AsyncTaskClass2 doInBackground() method. If it does, then check the value returned by method insertOrThrow(). If return value is -1 then you need to check for that. This link will give you some insight
You declared your nameValuePairs-variable only in your doInBackground-Method of your 1st AsyncTask:
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
You could simply solve it, if you use your class-attribute nameValuePairs:
nameValuePairs = new ArrayList<NameValuePair>();
But as a general aspect, I do not see any cause why you should use a 2nd AsyncTask. Why don't you call the method
KayitEkle(Array.get(nameValuePairs, 0).toString(),Array.get(nameValuePairs, 1).toString(),Array.get(nameValuePairs, 2).toString());
in the doInBackground-Method of your 1st AsyncTask?

Progress Dialog not showing in Android

Progress Dialog is not showing in AsyncTask Class In Android.
My AsyncTask Class Code:
class SyncData1 {
Context context;
DatabaseHelper myDbHelper;
ArrayList<String> ItemNo= new ArrayList<String>();
ArrayList<String> RepReceivedQty= new ArrayList<String>();
ArrayList<String> HotelReceivedQty= new ArrayList<String>();
ArrayList<String> IStatus= new ArrayList<String>();
String jsodata;
String ChallanNo="",HotelRepReceivedOn="",HotelReceivedOn="",Status="";
String url=null;
Commans com;
public SyncData1(Context context)
{
this.context=context;
}
public void fetchData()
{
ItemNo.clear();
IStatus.clear();
RepReceivedQty.clear();
HotelReceivedQty.clear();
com= new Commans(context);
myDbHelper =new DatabaseHelper(context);
com.connectdb(myDbHelper);
Cursor curval= myDbHelper.dbQery("Select * from Challan_R where Flag=1 limit 1");
if(curval != null && curval.moveToFirst()) {
ChallanNo= curval.getString(0);
Status=curval.getString(5);
HotelRepReceivedOn=curval.getString(6);
HotelReceivedOn= curval.getString(7);
}
curval.close();
Cursor curItem= myDbHelper.dbQery("Select * from ChallanItems where ChallanNo= "+"'"+ChallanNo+"'");
if(curItem != null && curItem.moveToFirst()) {
while( !curItem.isAfterLast())
{
ItemNo.add(curItem.getString(0));
IStatus.add(curItem.getString(2));
RepReceivedQty.add(curItem.getString(9));
HotelReceivedQty.add(curItem.getString(1));
curItem.moveToNext();
}
}
curItem.close();
if(ChallanNo.length()>1)
{
jsodata=com.reciveJson(ChallanNo, HotelRepReceivedOn, HotelReceivedOn, Status, ItemNo, RepReceivedQty, HotelReceivedQty, IStatus);
Log.d("Json", jsodata);
ReciveChallanAsyn task = new ReciveChallanAsyn();
task.execute("");
}
}
private class ReciveChallanAsyn extends AsyncTask<String, Void, String> {
public static final int HTTP_TIMEOUT = 30 * 1000;
#Override
protected String doInBackground(String... urls) {
String response = "";
HttpEntity resEntity;
try {
//url=urls[0].getUrl();
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(Constants.SERVICE_SYNC_DATA);
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("data",jsodata));
nameValuePairs.add(new BasicNameValuePair("token",CreateChallan.token));
nameValuePairs.add(new BasicNameValuePair("customer_code",CreateChallan.strcustomer_code));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse responsePOST = httpclient.execute(httppost);
resEntity = responsePOST.getEntity();
response=EntityUtils.toString(resEntity);
} catch (Exception e) {
e.printStackTrace();
}
return response;
}
#SuppressLint("DefaultLocale")
#Override
protected void onPostExecute(String result) {
Log.d("Result", result);
pd.dismiss();
if(result!=null)
{
if(result.contentEquals("1") && result!=null)
{ com.connectdb(myDbHelper);
Toast.makeText(context, " Challan Sent ", Toast.LENGTH_LONG).show();
myDbHelper.ChallN_Updateb("", "2", ChallanNo,"");
Cursor curval1= myDbHelper.dbQery("Select * from Challan_R where Flag=1 limit 1");
if(curval1 != null && curval1.moveToFirst()) {
fetchData();
}
curval1.close();
com.disconnectdb();
}
else
Toast.makeText(context, "Error In Sending Challan", Toast.LENGTH_LONG).show();
}
else {
Toast.makeText(context, "Data Not Fount", Toast.LENGTH_LONG).show();
}
}
#Override
protected void onPreExecute()
{
// pd = ProgressDialog.show(HomeChallan.this, ""," Please wait...");
pd = new ProgressDialog(HomeChallan.this);
pd.setMessage(" Please wait... ");
pd.setIndeterminate(true);
pd.setCancelable(false);
pd.show();
}
}
It's a subclass of my main class where I am using the Async Task class
I am using the class SyncData1 class on onclickListerner Method
Cursor curval1= myDbHelper.dbQery("Select * from Challan_R where Flag=1 limit 1");
if(curval1 != null && curval1.moveToFirst()) {
SyncData1 data= new SyncData1(context);
data.fetchData();
Hope this can solve your issue, do some editing as per your requirment..
private final Handler handler = new Handler();
private Thread thread;
private QueueRunner runner = new QueueRunner();
private CustomProgressDialog mProgressBar;
private class QueueRunner implements Runnable
{
public void run()
{
try
{
synchronized(this)
{
handler.post(new Runnable()
{
public void run()
{
if (((Activity) AsyncWebPostClient.this.context).isFinishing() == false)
mProgressBar = CustomProgressDialog.show(AsyncWebPostClient.this.context,
null,null,true,true );
}
});
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
in your preExecute call this..
thread = new Thread(runner);
thread.start();
in your onpost call this..
mProgressBar.dismiss();
Edit: I have use customeProgress Dialog you can use Progress Dialog
this is your asynctask method,copy and paste it hope it's worked:
private class ReciveChallanAsyn extends AsyncTask<String, Void, String> {
public static final int HTTP_TIMEOUT = 30 * 1000;
#Override
protected void onPreExecute()
{
// pd = ProgressDialog.show(HomeChallan.this, ""," Please wait...");
pd = new ProgressDialog(HomeChallan.this);
pd.setMessage(" Please wait... ");
pd.setIndeterminate(false);
pd.setCancelable(false);
pd.show();
}
#Override
protected String doInBackground(String... urls) {
String response = "";
HttpEntity resEntity;
try {
//url=urls[0].getUrl();
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(Constants.SERVICE_SYNC_DATA);
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("data",jsodata));
nameValuePairs.add(new BasicNameValuePair("token",CreateChallan.token));
nameValuePairs.add(new BasicNameValuePair("customer_code",CreateChallan.strcustomer_code));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse responsePOST = httpclient.execute(httppost);
resEntity = responsePOST.getEntity();
response=EntityUtils.toString(resEntity);
} catch (Exception e) {
e.printStackTrace();
}
return response;
}
#SuppressLint("DefaultLocale")
#Override
protected void onPostExecute(String result) {
Log.d("Result", result);
pd.dismiss();
if(result!=null)
{
if(result.contentEquals("1") && result!=null)
{ com.connectdb(myDbHelper);
Toast.makeText(context, " Challan Sent ", Toast.LENGTH_LONG).show();
myDbHelper.ChallN_Updateb("", "2", ChallanNo,"");
Cursor curval1= myDbHelper.dbQery("Select * from Challan_R where Flag=1 limit 1");
if(curval1 != null && curval1.moveToFirst()) {
fetchData();
}
curval1.close();
com.disconnectdb();
}
else
Toast.makeText(context, "Error In Sending Challan", Toast.LENGTH_LONG).show();
}
else {
Toast.makeText(context, "Data Not Fount", Toast.LENGTH_LONG).show();
}
}
}

Can't create handler inside thread that has not called Looper.prepare() in android

I am getting can't create handler inside thread in asynchronous background task. Below is my code. I made the necessary modifications to progress bar after searching in google but still the error is rising. Please help me with this. Will be thankful.
My code:
private class LongOperation1 extends AsyncTask<String, Void, String> {
private final WeakReference<MainActivity> mainActivityWeakRef;
ProgressDialog dialog;
public LongOperation1(MainActivity mainActivity) {
super();
this.mainActivityWeakRef = new WeakReference<MainActivity>(
mainActivity);
// this.activity = mainActivity;
}
#Override
protected String doInBackground(String... params) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(
"http://.............php");
// This is the data to send
// String MyName = 'adil'; //any data to send
// publishProgress(5);
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(
1);
nameValuePairs.add(new BasicNameValuePair("param1", "1"));
nameValuePairs.add(new BasicNameValuePair("param2",
"Cities"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String response = httpclient.execute(httppost, responseHandler);
// This is the response from a php application
String reverseString = response;
Toast.makeText(MainActivity.this, "response" + reverseString,
Toast.LENGTH_LONG).show();
} catch (ClientProtocolException e) {
Toast.makeText(MainActivity.this,
"CPE response " + e.toString(), Toast.LENGTH_LONG)
.show();
// TODO Auto-generated catch block
} catch (IOException e) {
Toast.makeText(MainActivity.this,
"IOE response " + e.toString(), Toast.LENGTH_LONG)
.show();
// TODO Auto-generated catch block
}
return "All Done!";
}
#Override
protected void onPostExecute(String result) {
Log.d("onpostexecute", (mainActivityWeakRef.get() != null) + "");
if (mainActivityWeakRef.get() != null
&& !mainActivityWeakRef.get().isFinishing()) {
AlertDialog alertDialog = new AlertDialog.Builder(
mainActivityWeakRef.get()).create();
alertDialog.setTitle(result);
alertDialog.setMessage("On post execute");
alertDialog.setCancelable(false);
alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
dialog.dismiss();
}
});
alertDialog.show();
}
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
dialog.incrementProgressBy(5);
}
}
You can not update the UI thread(Main Thread) from another thread.. If you want to do it
1) Return your response String from doInbackground, and update the UI in PostExecute()
2)Otherwise you can wrap the Toast Message in runonUiThread(){}
3) Use Handler to update the UI from another thread.
You cannot use Toast in the do in background operation because you need the UIThread to show them. Instean of doing that as you did. Use a variable an save it for different states.
In onPostExecute check the variable and show the corresponding Toast.
Hope it helps.

ProcessDialog is not appearing properly?

This is my function that is in LoginActivity.java.So onclick of button i am calling this function.
public void postHttpRequest(String userId,String pass,TextView error){
RequestClient reqClient = new RequestClient(LoginActivity.this);
String AppResponse = null;
try {
url = "myurl";
Log.d("URL", url);
AppResponse = reqClient.execute().get();
String status = ValidateLoginStatus.checkLoginStatus(AppResponse);
Log.d("Status recived", status);
if(status.equals("200")){
saveInformation(userId,pass);
startingActivity(HOST_URL);
}else{
error.setText("Incorrect UserName or Password");
}
} catch (Exception e) {
Log.e("Exception Occured", "Exception is "+e.getMessage());
}
}
From this function i am calling a AsynkTask for Http Communication.So onclick of button when i am geeting the response then my processDialog in opening just for one sec.I want as i click the buttoon my processDialog should get open utill i got the response
public class RequestClient extends AsyncTask<String, Void, String>{
ProgressDialog pDialog;
Context context;
public RequestClient(Context c) {
context = c;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(context);
pDialog.setMessage("Authenticating user...");
pDialog.show();
}
#Override
protected String doInBackground(String... aurl){
String responseString="";
DefaultHttpClient httpClient=new DefaultHttpClient();
try {
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(LoginActivity.url);
HttpResponse responseGet = client.execute(get);
HttpEntity resEntityGet = responseGet.getEntity();
if (resEntityGet != null) {
responseString = EntityUtils.toString(resEntityGet);
Log.i("GET RESPONSE", responseString);
}
} catch (Exception e) {
Log.d("ANDRO_ASYNC_ERROR", "Error is "+e.toString());
}
Log.d("ANDRO_ASYNC_ERROR", responseString);
httpClient.getConnectionManager().shutdown();
return responseString;
}
#Override
protected void onPostExecute(String response) {
super.onPostExecute(response);
if(pDialog!=null)
pDialog.dismiss();
}
}
So please suggest me what changes i have to make so that processDialog should display properly in the center of the device
//add style in your progressbialog
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(context);
pDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
pDialog.setMessage("Authenticating user...");
if (pDialog != null && !pDialog.isShowing()) {
pDialog.show();
}
}
AsyncTask return value only after using get() method
Drawing from the above link
Calling the get() method of AsyncTask will block the main thread and wait for the result to be returned. This effectively makes using an AsyncTask become a synchronous operation in which case there's no point in using an AsyncTask.
The only reason I can think of to use the get() method would be from a thread other than the main (UI) thread although I can't think of many reasons to do that.
On Button click
RequestClient reqClient = new RequestClient(LoginActivity.this,new TheInterface() {
#Override
public void theMethod(String result) {
Log.i("Result =",result);
}
});
reqClient.execute(url); // no get(). pass url to doInBackground()
In your activity class
public interface TheInterface {
public void theMethod(String result);
}
}
AsyncTask
public class RequestClient extends AsyncTask<String, Void, String>{
ProgressDialog pDialog;
Context context;
TheInterface listener;
public RequestClient(Context c,TheInterface listen) {
context = c;
listener = listen;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(context);
pDialog.setMessage("Authenticating user...");
pDialog.show();
}
#Override
protected String doInBackground(String... aurl){
String responseString="";
HttpClient client;
try {
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(aurl[0]); // url
HttpResponse responseGet = client.execute(get);
HttpEntity resEntityGet = responseGet.getEntity();
if (resEntityGet != null) {
responseString = EntityUtils.toString(resEntityGet);
Log.i("GET RESPONSE", responseString);
}
} catch (Exception e) {
Log.d("ANDRO_ASYNC_ERROR", "Error is "+e.toString());
}
Log.d("ANDRO_ASYNC_ERROR", responseString);
client.getConnectionManager().shutdown();
return responseString;
}
#Override
protected void onPostExecute(String response) {
super.onPostExecute(response);
pDialog.dismiss();
if (listener != null)
{
listener.theMethod(result);
}
}
}
It seems that your button code is not correct, because it's async, but you are trying to use it as standart sync code.
Try to move this code into onPostExecute:
String status = ValidateLoginStatus.checkLoginStatus(response);
Log.d("Status recived", status);
if(status.equals("200")){
saveInformation(userId,pass);
startingActivity(HOST_URL);
}else{
error.setText("Incorrect UserName or Password");
}
and make this button click code:
public void postHttpRequest(String userId,String pass,TextView error){
RequestClient reqClient = new RequestClient(LoginActivity.this);
String AppResponse = null;
try {
url = "myurl";
Log.d("URL", url);
reqClient.execute();
} catch (Exception e) {
Log.e("Exception Occured", "Exception is "+e.getMessage());
}
}

Categories

Resources