android


onPostExecute does not execute


After completing the task ImageUploadTask(), the method itself will return sResponse which supposedly would trigger the onPostExecute(). However, I am unable to get onPostExecute() to work.
The code for the Intent is:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
upload.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (bitmap == null) {
Toast.makeText(getApplicationContext(),
"Please select image", Toast.LENGTH_SHORT).show();
} else if (subject.getText() == null) {
Toast.makeText(getApplicationContext(),
"Please enter subject title", Toast.LENGTH_SHORT).show();
} else if (msg == null) {
Toast.makeText(getApplicationContext(),
"Please enter message", Toast.LENGTH_SHORT).show();
} else {
dialog = ProgressDialog.show(MainActivity.this, "Uploading",
"Please wait...", true);
new ImageUploadTask().execute();
}
}
});
The ImageUploadTask() is:
class ImageUploadTask extends AsyncTask <Void, Void, String>{
#Override
protected String doInBackground(Void... params) {
try {
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpPost httpPost = new HttpPost("http://203.117.178.181/test3/postdata2.php");
MultipartEntity entity = new MultipartEntity(
HttpMultipartMode.BROWSER_COMPATIBLE);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.JPEG, 100, bos);
byte[] data = bos.toByteArray();
entity.addPart("userfile", new ByteArrayBody(data,
"myImage.jpg"));
entity.addPart("subject", new StringBody(subject.getText()
.toString()));
entity.addPart("message", new StringBody(msg.getText()
.toString()));
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost,
localContext);
BufferedReader reader = new BufferedReader(
new InputStreamReader(
response.getEntity().getContent(), "UTF-8"));
String sResponse = reader.readLine();
return sResponse;
} catch (Exception e) {
if (dialog.isShowing())
dialog.dismiss();
Toast.makeText(getApplicationContext(),
getString(R.string.exception_message),
Toast.LENGTH_LONG).show();
Log.e(e.getClass().getName(), e.getMessage(), e);
return null;
}
// (null);
}
The code for the onPostExecute() is:
#Override
protected void onPostExecute(String sResponse) {
super.onPostExecute(sResponse);
try {
if (dialog.isShowing())
dialog.dismiss();
if (sResponse != null) {
JSONObject JResponse = new JSONObject(sResponse);
int success = JResponse.getInt("SUCCESS");
String message = JResponse.getString("MESSAGE");
if (success == 0) {
Toast.makeText(getApplicationContext(), message,
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(),
"Photo uploaded successfully",
Toast.LENGTH_SHORT).show();
subject.setText("");
msg.setText("");
}
}
} catch (Exception e) {
Toast.makeText(getApplicationContext(),
getString(R.string.exception_message),
Toast.LENGTH_LONG).show();
Log.e(e.getClass().getName(), e.getMessage(), e);
}
}
}}
Thanks in advance =D
Change it to this:
#Override
protected void onPostExecute(String... sResponse) {
Add the ...
Edit: also as #Raghunandan points out, you cannot call Toast from your doInBackground, it's a mere background thread and does not support UI commands. For that, you must use publishProgress() and onProgressUpdate().
Try this..
#Override
protected void onPostExecute(String sResponse) {
if (dialog.isShowing())
dialog.dismiss();
try {
if (sResponse != null) {
JSONObject JResponse = new JSONObject(sResponse);
int success = JResponse.getInt("SUCCESS");
String message = JResponse.getString("MESSAGE");
if (success == 0) {
Toast.makeText(getApplicationContext(), message,
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(),
"Photo uploaded successfully",
Toast.LENGTH_SHORT).show();
subject.setText("");
msg.setText("");
}
}
} catch (Exception e) {
Toast.makeText(getApplicationContext(),
getString(R.string.exception_message),
Toast.LENGTH_LONG).show();
Log.e(e.getClass().getName(), e.getMessage(), e);
}
}
}}
Your might be getting exception.
You have this in doInbackground.
Toast.makeText(getApplicationContext(),
getString(R.string.exception_message),
Toast.LENGTH_LONG).show();
doInbackground is invoked on a background thread. You cannot display toast/ update ui from doInbackground. So return response and display toast in onPostExecute
You need to change this
catch (Exception e) {
if (dialog.isShowing())
dialog.dismiss();
Toast.makeText(getApplicationContext(),
getString(R.string.exception_message),
Toast.LENGTH_LONG).show();
Log.e(e.getClass().getName(), e.getMessage(), e);
return null;
}
To
catch (Exception e) {
e.printStacktrace();
}
For more info check the docs under the topic The 4 steps.
http://developer.android.com/reference/android/os/AsyncTask.html
Probably your doInBackGround method is throwing an exception. Also you can remove super.
super.onPostExecute() as it is redundant.

Related Links

Mediawiki JSON response: retrieving thumbnail of each category members
Allocation Tracking on Android Studio 2.2.1
Can I use same Alias and keystore file for different application for playstore upload
Android collapsing toolbar, collapse only when user touches recycler view
Can't allow my app to use draw over other apps permission
I want to make a call from a button but this error comes in the dialogue
How to change android notifications color and fontsize?
Specify route for integrated/embedded NativeScript from Java
How to resolve java.util.ZipException:duplicate entry occurs due to multidex in android studio
RenderScript: do not provide .so in aar
Does the UI layer change between iOS and Android in React Native?
Android Dynamic view creation with view controlles at run time
Tracking change in touch direction without lifting the finger
Organizing files into groups in Android Project [duplicate]
how to detect no answer when outgoing call voip skype
Align to objects outside your layout

Categories

HOME
grok
ggplot2
datastore
zend-framework
rsa
swt
serialization
solaris
cakephp-3.4
pyqt4
lanczos
performancepoint
sendgrid-api-v3
reactive-programming
redis-sentinel
rtf
naivebayes
endpoint
plink
glyphicons
google-data-studio
xmonad
symfony-console
jmp
google-maps-autocomplete
poedit
backpack-for-laravel
named-entity-recognition
joptionpane
game-theory
bringtofront
magento-1.8
gitlab-api
jmockit
glib
playstation-portable
erb
code-snippets
classcastexception
keras-layer
pop3
jwplayer6
raft
lint
nohup
loading
stringtokenizer
movilizer
importerror
nanoc
yii2-api
vugen
tinymce-3
trojan
modelsim
ngmaterial
objectscript
mapxtreme
builtins
actor-platform
tinkerpop3
mongodb-php
avspeechsynthesizer
nservicebus5
cda
sklearn-pandas
createprocess
fink
libav
cycle2
dynatree
java-money
gocql
coda
mod-proxy
dronekit-android
keyup
phpldapadmin
teaspoon
psr-4
universal-image-loader
mintty
grails-plugin-rabbitmq
twitter-bootstrap-rails
amslidemenu
xmltodict
asdf
node-blade
dolby-audio-api
joomla-template
wp7test
http-status-code-410
tree-balancing
redis-py
procedures
twitterizer
objective-j
web-garden
zen
complex-event-processing
xpsdocument
application-planning
change-management

Resources

Encrypt Message