Toast from onProgressUpdate not showing up - android

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();
}

Related

android httpost request always return 404

the following code is for make and httpost request to a server always response 404
but if i make the same request on postman works fine i send only one parameter on post an base 64 image string
private class SendData extends AsyncTask<String,String,String>{
#Override
protected String doInBackground(String... strings) {
// Create a new HttpClient and Post Header
try{
MobileUtil.HTTP_PARAMS = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(MobileUtil.HTTP_PARAMS, MobileUtil.HTTP_TIMEOUT);
HttpConnectionParams.setSoTimeout(MobileUtil.HTTP_PARAMS, MobileUtil.HTTP_TIMEOUT);
MobileUtil.HTTP_CLIENT = new DefaultHttpClient(MobileUtil.HTTP_PARAMS);
MobileUtil.HTTP_CLIENT = sslClient(MobileUtil.HTTP_CLIENT);
HttpPost post = new HttpPost("http://aplicacion.fractal.com.pe:9090/fractalMobile/mobile/guardarFotoTest");
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("foto",encodedImage));
post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse resp = MobileUtil.HTTP_CLIENT.execute(post);
Log.d("Info",resp.getStatusLine().getReasonPhrase());
Log.d("Info",resp.getStatusLine().toString());
String respStr = EntityUtils.toString(resp.getEntity());
Log.d("Info",respStr);
if(respStr.equals("1"))
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(MainActivity.this,"Se Realizo la Operacion con Exito",Toast.LENGTH_LONG).show();
}
});
} catch (Exception e){
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
}
}
and i try to debug but don't know what is wrong on postman the request response with 1 if ok and 0 if go wrong
any idea how to make the request

AsyncTask doInBackGround is not called

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;
}
}

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?

Can't show Toast inside AsyncTask inside a DialogFragment

I'm using a DialogFragment to show a simple form, which then is posted to a remote server and a success/fail code is sent back.
However whenever I want to show a Toast when an error occurred I get an exception in which getActivity() returns null. Any idea why this is?
This is a summary of the code:
private class UploadNewGroupToServer extends AsyncTask<String, Void, Void>
{
ProgressDialog createGroupProgressDialog;
#Override
protected Void doInBackground(String... params)
{
getActivity().runOnUiThread(new Runnable()
{
public void run()
{
createGroupProgressDialog = new ProgressDialog(getActivity());
createGroupProgressDialog.setTitle("Creating group...");
createGroupProgressDialog.show();
}
});
String encodedImage = params[0];
String groupTitle = params[1];
String groupDesc = params[2];
//Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(URL_API_CREATE_GROUP);
try
{
// Add data
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
if(encodedImage != null)
{
nameValuePairs.add(new BasicNameValuePair("picture", encodedImage));
}
nameValuePairs.add(new BasicNameValuePair("title", groupTitle));
nameValuePairs.add(new BasicNameValuePair("desc", groupDesc));
nameValuePairs.add(new BasicNameValuePair("token", "MY_TOKEN_HERE!"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
ResponseHandler<String> responseHandler = new BasicResponseHandler();
Log.d("APP", "Going to execute ");
final String responseBody = httpclient.execute(httppost, responseHandler);
Log.d("APP", "Back from execute, responseBody is " + responseBody);
//More business logic here
// . . . . .
throw new Exception(); //simulate an error
} catch (final Exception e)
{
Log.d("APP", "Exception es " + e.getMessage());
createGroupProgressDialog.dismiss();
getActivity().runOnUiThread(new Runnable() //App dies here!
{
public void run()
{
Toast.makeText(getActivity(), "Error!", Toast.LENGTH_LONG).show();
}
});
}
return null;
}
Here's the logcat:
11-04 00:16:18.414: E/AndroidRuntime(7229): Caused by: java.lang.NullPointerException
11-04 00:16:18.414: E/AndroidRuntime(7229): at com.myapp.android.GroupCreateDialogFragment$UploadNewGroupToServer.doInBackground(GroupCreateDialogFragment.java:204)
11-04 00:16:18.414: E/AndroidRuntime(7229): at com.myapp.android.GroupCreateDialogFragment$UploadNewGroupToServer.doInBackground(GroupCreateDialogFragment.java:1)
11-04 00:16:18.414: E/AndroidRuntime(7229): at android.os.AsyncTask$2.call(AsyncTask.java:287)
11-04 00:16:18.414: E/AndroidRuntime(7229): at java.util.concurrent.FutureTask.run(FutureTask.java:234)
11-04 00:16:18.414: E/AndroidRuntime(7229): ... 4 more
When you invoke asynctask use
new UploadNewGroupToServer(getActivity()).execute();.
Now in the constructor
Context mContext;
pulic void UploadNewGroupToServer(Context context)
{
mContext = context;
}
Also move your progressdialog initialization to the constructor
pulic void UploadNewGroupToServer(Context context)
{
createGroupProgressDialog = new ProgressDialog(context);
createGroupProgressDialog.setTitle("Creating group...");
}
In onPreExecute
public void onPreExecute()
{
super.onPreExecute();
createGroupProgressDialog.show();
}
Also instead of displaying toast in doInbackground return result and in onPostExecute dismiss dialog and show toast accordingly.
Could your create a handler in your async task? If handler created in UI thread(If use MainLooper) post method samely runOnUiThread.
private class UploadNewGroupToServer extends AsyncTask<String, Void, Void>
{
ProgressDialog createGroupProgressDialog;
Handler handler;
protected void onPreExecute(){
handler = new Handler();
}
#Override
protected Void doInBackground(String... params)
{
handler.post(new Runnable()
{
public void run()
{
createGroupProgressDialog = new ProgressDialog(getActivity());
createGroupProgressDialog.setTitle("Creating group...");
createGroupProgressDialog.show();
}
});
String encodedImage = params[0];
String groupTitle = params[1];
String groupDesc = params[2];
//Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(URL_API_CREATE_GROUP);
try
{
// Add data
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
if(encodedImage != null)
{
nameValuePairs.add(new BasicNameValuePair("picture", encodedImage));
}
nameValuePairs.add(new BasicNameValuePair("title", groupTitle));
nameValuePairs.add(new BasicNameValuePair("desc", groupDesc));
nameValuePairs.add(new BasicNameValuePair("token", "MY_TOKEN_HERE!"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
ResponseHandler<String> responseHandler = new BasicResponseHandler();
Log.d("APP", "Going to execute ");
final String responseBody = httpclient.execute(httppost, responseHandler);
Log.d("APP", "Back from execute, responseBody is " + responseBody);
//More business logic here
// . . . . .
throw new Exception(); //simulate an error
} catch (final Exception e)
{
Log.d("APP", "Exception es " + e.getMessage());
createGroupProgressDialog.dismiss();
handler.post(new Runnable() //App dies here!
{
public void run()
{
Toast.makeText(getActivity(), "Error!", Toast.LENGTH_LONG).show();
}
});
}
return null;
}

onPostExecute never called?

public static class TestTask extends AsyncTask<Void, Integer, Integer> {
private String stacktrace;
public TestTask (String stacktrace){
this.stacktrace = stacktrace;
}
#Override
protected Integer doInBackground(Void... params) {
try {
Log.i("async", "doInBackground 1"); //this gets logged
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://xx.xx:8080/android/service.php");
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("action", "logexception"));
nameValuePairs.add(new BasicNameValuePair("stacktrace", stacktrace));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
Log.i("async", "doInBackground 2"); //this gets logged
return 1;
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
protected void onPreExecute(){
Log.i("async", "onPreExecute"); //this gets logged
}
#Override
protected void onPostExecute(Integer result) {
Log.i("async", "onPostExecute"); //this doenst get logged!
}
}
I've been checking out the other SO threads regarding this, but according to them, my code looks correct as far as i can tell. So why do i never reach Log.i("async", "onPostExecute");? Thanks
Did you create your AsyncTask on UI Thread?
Others seems good. Generics and annotations are fine.
So probably problem is that your doInBackground method never returns because onPostExecute is automatic called when doInBackground something will return.
You have to call the super in onPostExecute()
So you code should be like this:
#Override
public void onPostExecute(Integer result) {
super.onPostExecute(result);
Log.i("async", "onPostExecute");
}
And this should work

Categories

Resources