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;
}
Related
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
I am trying to create a Login function so i can verify the users. I pass the Username , Password variables to AsyncTask class but i don't know hot to get results in order to use them. Any help? (I am posting part of the source code due to website restrictions)
btnLogin.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(txtUsername.getText().toString().trim().length() > 0 && txtPassword.getText().toString().trim().length() > 0)
{
// Retrieve the text entered from the EditText
String Username = txtUsername.getText().toString();
String Password = txtPassword.getText().toString();
/*Toast.makeText(MainActivity.this,
Username +" + " + Password+" \n Ready for step to post data", Toast.LENGTH_LONG).show();*/
String[] params = {Username, Password};
// we are going to use asynctask to prevent network on main thread exception
new PostDataAsyncTask().execute(params);
// Redirect to dashboard / home screen.
login.dismiss();
}
else
{
Toast.makeText(MainActivity.this,
"Please enter Username and Password", Toast.LENGTH_LONG).show();
}
}
});
Then i use the AsynkTask to do the check but do not know how to get the results and store them in a variable. Any help?
public class PostDataAsyncTask extends AsyncTask<String, String, String> {
protected void onPreExecute() {
super.onPreExecute();
// do stuff before posting data
}
#Override
protected String doInBackground(String... params) {
try {
// url where the data will be posted
String postReceiverUrl = "http://server.com/Json/login.php";
Log.v(TAG, "postURL: " + postReceiverUrl);
String line = null;
String fail = "notok";
// HttpClient
HttpClient httpClient = new DefaultHttpClient();
// post header
HttpPost httpPost = new HttpPost(postReceiverUrl);
// add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("UserName", params[0]));
nameValuePairs.add(new BasicNameValuePair("Password", params[1]));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// execute HTTP post request
HttpResponse response = httpClient.execute(httpPost);
HttpEntity resEntity = response.getEntity();
line = resEntity.toString();
Log.v(TAG, "Testing response: " + line);
if (resEntity != null) {
String responseStr = EntityUtils.toString(resEntity).trim();
Log.v(TAG, "Response: " + responseStr);
Intent Hotels_btn_pressed = new Intent(MainActivity.this, Hotels.class);
startActivity(Hotels_btn_pressed);
// you can add an if statement here and do other actions based on the response
Toast.makeText(MainActivity.this,
"Error! User does not exist", Toast.LENGTH_LONG).show();
}else{
finish();
}
} catch (NullPointerException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String lenghtOfFile) {
// do stuff after posting data
}
}
Not the best code refactoring, but just to give you a hint.
I would create an interface (lets call it 'LogInListener'):
public interface LoginListener {
void onSuccessfulLogin(String response);
void onFailedLogin(String response);
}
The 'MainActivity' class would implement that interface and set itself as a listener the 'PostDataAsyncTask'. So, creating the async task from the main activity would look like this:
String[] params = {Username, Password};
// we are going to use asynctask to prevent network on main thread exception
PostDataAsyncTask postTask = new PostDataAsyncTask(this);
postTask.execute(params);
I would move 'PostDataAsyncTask' class into a new file:
public class PostDataAsyncTask extends AsyncTask<String, String, String> {
private static final String ERROR_RESPONSE = "notok";
private LoginListener listener = null;
public PostDataAsyncTask(LoginListener listener) {
this.listener = listener;
}
#Override
protected String doInBackground(String... params) {
String postResponse = "";
try {
// url where the data will be posted
String postReceiverUrl = "http://server.com/Json/login.php";
// HttpClient
HttpClient httpClient = new DefaultHttpClient();
// post header
HttpPost httpPost = new HttpPost(postReceiverUrl);
// add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("UserName", params[0]));
nameValuePairs.add(new BasicNameValuePair("Password", params[1]));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// execute HTTP post request
HttpResponse response = httpClient.execute(httpPost);
HttpEntity resEntity = response.getEntity();
postResponse = EntityUtils.toString(resEntity).trim();
} catch (NullPointerException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return postResponse;
}
#Override
protected void onPostExecute(String postResponse) {
if (postResponse.isEmpty() || postResponse.equals(ERROR_RESPONSE) ) {
listener.onFailedLogin(postResponse);
} else {
listener.onSuccessfulLogin(postResponse);
}
}
}
So, 'doInBackground' returns the response to 'onPostExecute' (which runs on the UI thread), and 'onPostExecute' routes the result (success or failure) to the MainActivity, which implements the 'LogInListener' methods:
#Override
public void onSuccessfulLogin(String response) {
// you have access to the ui thread here - do whatever you want on suscess
// I'm just assuming that you'd like to start that activity
Intent Hotels_btn_pressed = new Intent(this, Hotels.class);
startActivity(Hotels_btn_pressed);
}
#Override
public void onFailedLogin(String response) {
Toast.makeText(MainActivity.this,
"Error! User does not exist", Toast.LENGTH_LONG).show();
}
I just assumed that that's what you wanted to do on success: start a new activity, and show a toast on fail.
I want execute http post after getting response from server.
If server response is false the http post will execute else not execute.
How can i do for this.
My android main activity code:
if (Utility.isValidMobile(mobileNumber)) {
String isAvailable = userDelegate.checkUser(mobileNumber, context);
if (isAvailable.equals("false")) {
userDelegate.addUser(userMO, context);
Toast.makeText(getApplicationContext(), "Your mobile number is" + mobileNumber + "name is" + userName, Toast.LENGTH_LONG).show();
} else if (isAvailable.equals("true")) {
Toast.makeText(getApplicationContext(), "Your mobile number is already registerd", Toast.LENGTH_LONG).show();
}
}
when i click signup button this above code will executed
My Userdelegate class code :
public void addUser(final UserMO userMo, final Context context) {
final String jsonStringObject = gson.toJson(userMo);
Thread t = new Thread() {
public void run() {
Looper.prepare(); // for the child Thread
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000); // Timeout
// Limit
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("userBO", jsonStringObject));
HttpPost post = new HttpPost("http://192.168.1.101:8080/warname/user/addUser");
post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = client.execute(post);
BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
Toast.makeText(context, "Your user id " + rd.readLine(), Toast.LENGTH_LONG).show();
} catch (Exception e) {
e.printStackTrace();
}
Looper.loop(); // Loop in the message queue
}
};
t.start();
}
public void getMatchingExistingUserList(final String mobile_number, final Context context) {
final String jsonStringObject = gson.toJson(mobile_number);
Thread t = new Thread() {
public void run() {
Looper.prepare(); // for the child Thread
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000); // Timeout
// Limit
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("userBO", jsonStringObject));
HttpPost post = new HttpPost("http://192.168.1.101:8080/warname/user/addUser");
post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = client.execute(post);
BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
final String responseString = rd.readLine();
} catch (Exception e) {
e.printStackTrace();
}
Looper.loop(); // Loop in the message queue
}
};
t.start();
}
public String checkUser(final String mobile_number, final Context context) {
final StringBuilder isAvailable = new StringBuilder();
Thread t = new Thread() {
#Override
public void run() {
Looper.prepare(); // for the child Thread
try {
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000); // Timeout
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("MobileNumber", gson.toJson(mobile_number)));
HttpPost post = new HttpPost("http://192.168.1.101:8080/warname/user/checkUserMobileNumber");
post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = client.execute(post);
BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
isAvailable.append(rd.readLine());
} catch (Exception e) {
e.printStackTrace();
}
Looper.loop(); // Loop in the message queue
}
};
t.start();
return isAvailable.toString();
}
Problem is i got response false but the if condition not working.
how to solve this problem.
After changing:
if (Utility.isValidMobile(mobileNumber)) {
new AsyncTask<Void, Void, String>() {
#Override
protected String doInBackground(Void... arg0) {
return userDelegate.checkUser(mobileNumber, context);
}
#Override
protected void onPostExecute(String isAvailable) {
Toast.makeText(getApplicationContext(), isAvailable, Toast.LENGTH_LONG).show();
if (isAvailable.equals("false")) {
Toast.makeText(getApplicationContext(), "Your mobile number is" + mobileNumber + "name is" + userName, Toast.LENGTH_LONG).show();
userDelegate.addUser(userMO, context);
} else if (isAvailable.equals("true")) {
Toast.makeText(getApplicationContext(), "Your mobile number is already registerd", Toast.LENGTH_LONG).show();
}
}
}.execute(null, null, null);
}
The if condition is not working ?
If server response is false the http post will execute else not
execute. How can i do for this
Issue occurring because you are using Threads in checkUser and addUser. Thread's execute with-out stopping execution of current Thread.
For example, when checkUser method is called from main thread then final StringBuilder isAvailable = new StringBuilder(); executing on main thread and Thread t is executing in separately. so system return control to next line which is return isAvailable.toString(); without waiting Thread execution complete means checkUser method always return null or empty string.
Same is for addUser method.
To do task accoding to result of checkUser method response use AsyncTask class.
You are using new threads to do http request here. Therefore your delegate methods are not synchronized. addUser and checkUser will return before your http requests finish.
To write multi thread codes like yours, you may want to use a some kind of a listener to do the threads communication work.
For example, you can pass a listener to your delegate which looks like this
class Listener{
private Handler handler = new Handler();
public void onUserAdded(){
handler.post(new Runnable(){
public void run(){
// Toast your thing
}
});
}
public void onUserChecked(final boolean available){
handler.post(new Runnable(){
public void run(){
if(available){
// Toast your thing
}else{
userDelegate.addUser(userMO, context);
}
}
});
}
}
And all your new Thread(){ run(){ codes should end with all call to the listener.
As you can see I use a Handler to post works back to the UI thread. This is very important for you to notify your UI elements of what is going on in your none-UI threads.
Also, I can't see what you are doing with your Looper.prepare() and Looper.loop(). No child thread is there.
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 someone tell me, why progressbar isnt showing when picture is being uploaded. I copied asynctask structure from my old project where it works. In my old project i use asynctask to download pictures from web server, and to show progressbar while downloading.
Here is my code:
public class PreviewPostActivity extends Activity {
ImageView imageView;
TextView tvComment;
Button submit;
MyLocationListener locationListener;
List<NameValuePair> list = new ArrayList<NameValuePair>();
private final String url = "***"; //Url of php script
ProgressDialog pDialog;
String responseMessage="";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.preview_post);
Intent intent = this.getIntent();
imageView = (ImageView)findViewById(R.id.imgPerview);
tvComment = (TextView)findViewById(R.id.txtPreviewComment);
submit = (Button)findViewById(R.id.btnPreviewSubmit);
Bitmap image = (Bitmap)intent.getParcelableExtra("picture");
String comment = intent.getStringExtra("comment");
locationListener = (MyLocationListener)intent.getSerializableExtra("location");
String imagePath = intent.getStringExtra("imagePath");
String date = intent.getStringExtra("date");
imageView.setImageBitmap(image);
tvComment.setText(comment);
//tvComment.append("\n"+locationListener.latitude + "\n"+locationListener.longitude);
list.add(new BasicNameValuePair("image", imagePath));
list.add(new BasicNameValuePair("comment", comment));
list.add(new BasicNameValuePair("longitude", Double.toString(locationListener.longitude)));
list.add(new BasicNameValuePair("latitude", Double.toString(locationListener.latitude)));
list.add(new BasicNameValuePair("date", date));
submit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
new uploadPost().execute();
}
});
}
public void post(List<NameValuePair> nameValuePairs) {
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, 100000);
HttpConnectionParams.setSoTimeout(httpParameters, 200000);
HttpClient httpClient = new DefaultHttpClient(httpParameters);
HttpContext localContext = new BasicHttpContext();
HttpPost httpPost = new HttpPost(url);
try {
MultipartEntity entity = new MultipartEntity();
for(int index=0; index < nameValuePairs.size(); index++) {
if(nameValuePairs.get(index).getName().equalsIgnoreCase("image")) {
// If the key equals to "image", we use FileBody to transfer the data
entity.addPart(nameValuePairs.get(index).getName(), new FileBody(new File(nameValuePairs.get(index).getValue()),"image/jpeg"));
} else {
// Normal string data
entity.addPart(nameValuePairs.get(index).getName(), new StringBody(nameValuePairs.get(index).getValue()));
}
}
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost, localContext);
HttpEntity httpEntity = response.getEntity();
String responseMessage = EntityUtils.toString(httpEntity);
tvComment.setText(responseMessage);
} catch (IOException e) {
e.printStackTrace();
}
}
class uploadPost extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(PreviewPostActivity.this);
pDialog.setMessage("Uploading post. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Getting product details in background thread
* */
protected String doInBackground(String... params) {
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
//post(list);
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, 100000);
HttpConnectionParams.setSoTimeout(httpParameters, 200000);
HttpClient httpClient = new DefaultHttpClient(httpParameters);
HttpContext localContext = new BasicHttpContext();
HttpPost httpPost = new HttpPost(url);
try {
MultipartEntity entity = new MultipartEntity();
for(int index=0; index < list.size(); index++) {
if(list.get(index).getName().equalsIgnoreCase("image")) {
// If the key equals to "image", we use FileBody to transfer the data
entity.addPart(list.get(index).getName(), new FileBody(new File(list.get(index).getValue()),"image/jpeg"));
} else {
// Normal string data
entity.addPart(list.get(index).getName(), new StringBody(list.get(index).getValue()));
}
}
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost, localContext);
HttpEntity httpEntity = response.getEntity();
responseMessage = EntityUtils.toString(httpEntity);
//tvComment.setText(responseMessage);
} catch (IOException e) {
e.printStackTrace();
}
}
});
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once got all details
tvComment.setText(responseMessage);
pDialog.dismiss();
}
}
So when i hit button for upload, screen freezes and stay frozen until upload is complete, and progress bar isnt showing at all. Sometimes it shows, but its rly rear and i dont know why. I have tried calling Post() method from class in doInBackground body insted of whole code (code in body is the same as in post() method) but effect is the same, so i guess i didnt do something right in creating progressbar. But again i say i copied whole asynctask code from old project in witch it worked fine.
EDIT:
I just tryed creating progress bar in constructor of PreviewPostActivity.class and after that i made constructor for asynctask class but it still dosent work. I am rly confused becouse it worked in my old program.
Here is code from him:
class GetSlike extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(KlubSlikeActivity.this);
pDialog.setMessage("Ucitavanje u toku. Molimo vas sacekajte...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Getting product details in background thread
* */
protected String doInBackground(String... params) {
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
String id = Integer.toString(k.getId());
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("klub",id));
slikeUrl = JSONAdapter.getSlike(params);
gv.setAdapter(new SlikeAdapter(slikeUrl,KlubSlikeActivity.this));
}
});
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once got all details
pDialog.dismiss();
}
}
Only thing changed is doInBackground body...
Edited:
Dialog is display after runOnUiThread() is executed.
I found this library which is perfect to accomplish the upload task and also provide a progress handler which could be used to set the value of a ProgressBar:
https://github.com/nadam/android-async-http
It could be used like the following... Set onClickHandler for the upload Button:
#Override
public void onClick(View arg0) {
try {
String url = Uri.parse("YOUR UPLOAD URL GOES HERE")
.buildUpon()
.appendQueryParameter("SOME PARAMETER IF NEEDED 01", "VALUE 01")
.appendQueryParameter("SOME PARAMETER IF NEEDED 02", "VALUE 02")
.build().toString();
AsyncHttpResponseHandler httpResponseHandler = createHTTPResponseHandler();
RequestParams params = new RequestParams();
// this path could be retrieved from library or camera
String imageFilePath = "/storage/sdcard/DCIM/Camera/IMG.jpg";
params.put("data", new File(imageFilePath));
AsyncHttpClient client = new AsyncHttpClient();
client.post(url, params, httpResponseHandler);
} catch (IOException e) {
e.printStackTrace();
}
}
then add this method to your activity code:
public AsyncHttpResponseHandler createHTTPResponseHandler() {
AsyncHttpResponseHandler handler = new AsyncHttpResponseHandler() {
#Override
public void onStart() {
super.onStart();
}
#Override
public void onProgress(int position, int length) {
super.onProgress(position, length);
progressBar.setProgress(position);
progressBar.setMax(length);
}
#Override
public void onSuccess(String content) {
super.onSuccess(content);
}
#Override
public void onFailure(Throwable error, String content) {
super.onFailure(error, content);
}
#Override
public void onFinish() {
super.onFinish();
}
};
return handler;
}
Run on ui thread in asynctask doinbackground() is not correct. Also you are returning null in doInBackground() and you have parameter file_url in onPostExecute(). Return value in doInbackground() recieve value in onPostExecute().
doInBackGround() runs in background so you cannot access or update ui here.
To update ui you can use onPostExecute().
Your AsyncTask should be something like below. You are doing it the wrong way.
http://developer.android.com/reference/android/os/AsyncTask.html. See the topic under The 4 steps
pd= new ProgressDialog(this);
pd.setTitle("Posting data");
new PostTask().execute();
private class PostTask extends AsyncTask<VOid, Void, Void> {
protected void onPreExecute()
{//display dialog.
pd.show();
}
protected SoapObject doInBackground(Void... params) {
// TODO Auto-generated method stub
//post request. do not update ui here. runs in background
return null;
}
protected void onPostExecute(Void param)
{
pd.dismiss();
//update ui here
}