Loading Dialog on HTTP call OptimusHTTP - android

im using OptimusHTTP library on my android project. im trying to show loading if my app is contacting server. my problem is why my progress dialog does not dismiss. here is my code.
public void connectREST()
{
//using data json dummy
String SERVER = "http://jsonplaceholder.typicode.com/posts/1";
OptimusHTTP client = new OptimusHTTP();
client.enableDebugging();
client.setMethod(OptimusHTTP.METHOD_GET);
//parameter
ArrayMap<String, String> params = new ArrayMap<>();
params.put("email", "abc#abc.com");
params.put("pass", "abc");
//make request
ArrayList<HttpReq> refHttpReqList = new ArrayList<>();
try {
//mprogressdialog.show(this, "", "Loading", true);
// makeRequest() returns the reference of the request made
// which can be used later to call the cancelReq() if required
// if no request is made the makeRequest() returns null
HttpReq req = client.makeRequest(MainActivity.this, SERVER, params, responseListener);
if (req != null)
refHttpReqList.add(req);
mprogressdialog.show(this, "Loading", "Wait while loading...");
if (mprogressdialog != null && mprogressdialog.isShowing()) {
mprogressdialog.dismiss();
}
} catch (Exception e) {
e.printStackTrace();
}
}
private final OptimusHTTP.ResponseListener responseListener = new OptimusHTTP.ResponseListener() {
#Override
public void onSuccess(String msg) {
System.out.println(msg);
//mprogressdialog.dismiss();
Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
}
#Override
public void onFailure(String msg) {
System.out.println(msg);
}
};
i know that this library (OptimusHTTP) is using asnyc when contacting server.
is there any configuration whether im using sync or async on the http connection ?
what if im include get method in some async code (double async) ?
i know that my question seem like some newbie question. but it takes learn process to become a pro :) Thanks.

#navotera : You can show a ProgressDialogue just before making a request and when the request completes , under the listener just dismiss the progress dialogue.
i.e
...
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
...
...
// Initialize the progressdialog
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Connecting");
...
...
// Show the progressdialog just before making a request
progressDialog.show();
// Make the request
req = client.makeRequest(MainActivity.this, SERVER_URL, params,new OptimusHTTP.ResponseListener(){
#Override public void onSuccess(String msg) {
System.out.println(msg);
// Dismiss the progressdialog
progressDialog.dismiss();
}
#Override public void onFailure(String msg) {
System.out.println(msg);
// Dismiss the progressdialog
progressDialog.dismiss();
}
});

You see this library (OptimusHTTP) is using asnyc when contacting server.But why did you update UI on the same thread ?
private final OptimusHTTP.ResponseListener responseListener = new OptimusHTTP.ResponseListener() {
#Override
public void onSuccess(String msg) {
System.out.println(msg);
//mprogressdialog.dismiss();
Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
}
#Override
public void onFailure(String msg) {
System.out.println(msg);
}
};

Related

Calling a function inside onRespons method

I am working on an Android app.
This is one function inside a fragment:
private void guardar_paciente() {
String tag_string_req = "req_login";
StringRequest strReq = new StringRequest(Request.Method.POST,
URL_CHECK, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
String id_paciente = jObj.getString("id");
String id_nhc = jObj.getString("nhc");
if (!error) {
editor2.putString("id_paciente", id_paciente);
editor2.putString("nhc", id_nhc);
editor2.apply();
} else {
// Error in login. Get the error message
// String errorMsg = jObj.getString("error_msg");
}
} catch (JSONException e) {
// JSON error
e.printStackTrace();
// Toast.makeText(getActivity(), "Json error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getActivity(),
error.getMessage(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() {
// Posting parameters to login url
Map<String, String> params = new HashMap<String, String>();
params.put("nombre_completo", nombre_completo);
params.put("apellidos", apellidos);
params.put("tel1", tel1);
params.put("tel2", tel2);
params.put("email", email);
params.put("profesion", profesion);
params.put("sexo", sexo);
params.put("fecha_nacimiento", fecha_nacimiento);
params.put("edad", edad);
params.put("peso", peso);
params.put("talla", talla);
params.put("IMC", IMC);
params.put("consentimiento", "1");
params.put("clinica_paciente", clinica_actual);
params.put("imagen_paciente", imagen_paciente);
params.put("firma_paciente", numero+".JPG");
params.put("DNI", DNI);
params.put("direccion", direccion);
params.put("raza", raza);
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
What I need is to execute another function, abrirPaciente(), just after guardar_paciente() has finished all its methods and it is safe to change the UI.
I have tried calling abrirPaciente() just after editor2.apply();, but the app crashes.
Making use of callbacks :
public class foo {
interface ExampleInterface {
void finishedServiceCallNoErrors();
void finishedServiceCallWithError(String error);
}
void guardar_paciente(ExampleInterface exampleInterface) {
...
#Override
public void onResponse(String response) {
....
//there was no error
exampleInterface.finishedServiceCallNoErrors();
//there was an error
exampleInterface.finishedServiceCallWithError("your error message here");
....
}
...
}
}
and an example of how you'd make use of this :
public class bar implements foo.ExampleInterface {
//simple example of how you'd use this
private void callingIt() {
new foo().guardar_paciente(this); //here, we can pass `this` because our class is implementing the interface
}
//these now get returned to the class making use of the service call, so you can easily handle things here, instead of worrying about the logic in your service call response
#Override
public void finishedServiceCallNoErrors() {
//TODO("Handle the response with no error");
//your call completed and everything was fine, now do something else
}
#Override
public void finishedServiceCallWithError(String error) {
// TODO("Handle the response with an error")
// there was an error, handle it here
}
}
I'm not sure if this callback pattern will be safe to use if it's being triggered from a background thread, so for that you'd need to switch threads inside the callbacks, so inside finishedServiceCallNoErrors and inside finishedServiceCallWithError you'd potentially need like a Runnable, so you can make use of the main thread, or inside the onResponse of the service call, before triggering the callbacks, you could also change there to the main thread. You can find help with something like that here

How to save a variable in AsyncTask in Android

I am using Twitter 4j to post tweet on single button. If user revoke access of my app then its showing Error in Logcat in do in background i want this error and if this error comes my another hide button of twitter authorize app visible. how do i do that please help. I need that error and if its exists i want to hide show my buttons.
class updateTwitterStatus extends AsyncTask<String, String, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
protected Void doInBackground(String... args) {
String status = args[0];
try {
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.setOAuthConsumerKey(consumerKey);
builder.setOAuthConsumerSecret(consumerSecret);
String access_token = mSharedPreferences.getString(PREF_KEY_OAUTH_TOKEN, "");
String access_token_secret = mSharedPreferences.getString(PREF_KEY_OAUTH_SECRET, "");
AccessToken accessToken = new AccessToken(access_token, access_token_secret);
twitter4j.Twitter twitter = new TwitterFactory(builder.build()).getInstance(accessToken);
StatusUpdate statusUpdate = new StatusUpdate(status);
File extStore = Environment.getExternalStoragePublicDirectory("/Twitter/Cache/demo.jpg");
statusUpdate.setMedia(extStore);
twitter4j.Status response = twitter.updateStatus(statusUpdate);
} catch (TwitterException e) {
Log.d("Failed to post!", e.getMessage());
error=e; //error is exception
}
return null;}
#Override
protected void onPostExecute(Void result) {
pDialog.dismiss();
Toast.makeText(getContext(), "Posted to Twitter!"+error, Toast.LENGTH_SHORT).show();
/* i need a variable like int a =10; access it globally, How i do that/*
} } }
You can save the exception in a variable and check it in onPostExecute()
and hide your button ..
new AsyncTask<Void, Void, Boolean>() {
Exception error;
#Override
protected Boolean doInBackground(Void... params) {
try {
// do work
return true;
} catch (Exception e) {
error = e;
return false;
}
}
#Override
protected void onPostExecute(Boolean result) {
if (result) {
Toast.makeText(ctx, "Success!",
Toast.LENGTH_SHORT).show();
} else {
if (error != null) {
Toast.makeText(getApplicationContext(), error.getMessage(),
Toast.LENGTH_SHORT).show();
//error occurs hide button here
}
}
}
}

Unable to navigate to Activity after successful login - Android volley

Issue
After successful login verification from the server, unable to open New activity. Activity stays at Login Activity
Background
What I am trying to achieve here is open "Welcome" activity after successful User login. The server correctly validates the user login and displays the Toast, but not opening the activity
Code
private static final String LOGIN_URL = "<myURL>/login.php";
public static final String KEY_LOGUSERNAME = "loUname";
public static final String KEY_LOGPASSWORD = "loPass";
EditText LogUser, LogPass;
Button btnsLogin;
String loUser, loPassword;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
initalizevars();
btnsLogin.setOnClickListener(this);
}
public void initalizevars() {
LogUser = (EditText) findViewById(R.id.etLogUser);
LogPass = (EditText) findViewById(R.id.etLogPass);
btnsLogin = (Button) findViewById(R.id.btnLogin);
}
private void login() {
loUser = LogUser.getText().toString().trim();
loPassword = LogPass.getText().toString().trim();
StringRequest stringRequest1 = new StringRequest(Request.Method.POST, LOGIN_URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if(response.trim().equals("Success"))
{
Toast.makeText(Login.this,response,Toast.LENGTH_LONG).show();
openProfile();
}else
{
Toast.makeText(Login.this,response,Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(Login.this,error.toString(),Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> map = new HashMap<String, String>();
map.put(KEY_LOGUSERNAME, loUser);
map.put(KEY_LOGPASSWORD, loPassword);
return map;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest1);
}
private void openProfile() {
Intent i = new Intent(this,Welcome.class);
startActivity(i);
}
#Override
public void onClick(View v) {
if (v == btnsLogin) {
login();
}
}
The Toast is being displayed from the server response on successful verification
What i tried
I tried changing the Intent to below
Intent i = new Intent(Login.this,Welcome.class);
startActivity(i);
But no luck. Am stuck and unable to figure out where and what went wrong.
Requesting your help in putting me in the right direction.
Thanks
EDIT
i modified the if condition to be more meaningful and to debug as well
if (response.trim().equals("Success")) {
Toast.makeText(Login.this, response + " Right", Toast.LENGTH_LONG).show();
openProfile();
} else {
Toast.makeText(Login.this, response + " Wrong", Toast.LENGTH_LONG).show();
openProfile();
}
As suggested by user #user1232726, the else part is being considered and the activity is opened which should not be the case.
My login.php outputs
Success
<!-- Hosting24 Analytics Code -->
<script type="text/javascript" src="http://stats.hosting24.com/count.php"></script>
<!-- End Of Analytics Code -->
Basically the issue was with the server response as it did return some javascript along with the success message. Guidance from #cricket_007, #IshitaSinha actually help me fix the issue.
Solution : Additional javascript/ or messages can be added When using free hosting sites. Check the entire response before comparing it with the actual response

Progressdialog is not getting dismissed inside the volley response block

My app performs uploading operation to backend php server.My problem is i cannot dismiss the progressdialog inside volley Onresponse() method.Onresponse() method gets executed and toast is displayed in background of the Progressdialog so that means Onresponse() gets called currectly.
I declared ProgressDialog variable in public
onCreate() method look like this
ProgressDialog dialog;
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.signup);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dialog=new ProgressDialog(context,ProgressDialog.STYLE_SPINNER);
dialog.setIndeterminate(true);
dialog.show(context,"Signing up","Please wait...");
login_call();
}
Login_call() performs volley request and inside the onResponse() i need to dismiss the dialog but its not working.
public void login_call()
{
RequestQueue queue= Volley.newRequestQueue(getApplicationContext());
StringRequest request = new StringRequest(Request.Method.POST, "http://192.168.56.1/sign.php", new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if (response.equals("success"))
{
dialog.dismiss();
getApplicationContext().startActivity(new Intent(getApplicationContext(), MainActivity.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
}
else
{
dialog.dismiss()
Toast.makeText(getApplicationContext(), response, Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
dialog.dismiss();
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
}
}
) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> param = new HashMap<>();
param.put("user",user.getText().toString());
param.put("pass",pass.getText().toString());
param.put("name",name.getText().toString());
param.put("mob",mob.getText().toString());
param.put("email",email.getText().toString());
param.put("photo",photo);
return param;
}
};
queue.add(request);
}
Toast message is displaying correctly but progressdialog is not gettting dismissed.
Any ideas to solve the problem??
Just change this :
RequestQueue queue= Volley.newRequestQueue(getApplicationContext());
StringRequest request = new StringRequest(Request.Method.POST, "http://192.168.56.1/sign.php", new Response.Listener<String>() {
#Override
public void onResponse(String response) {
dialog.dismiss(); // write it there
if (response.equals("success")) {
// dialog.dismiss(); remove this from here..!!
getApplicationContext().startActivity(new Intent(getApplicationContext(), MainActivity.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
);
} else {
Toast.makeText(getApplicationContext(), response, Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
dialog.dismiss();
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
}
}
Edit : set this
dialog.setIndeterminate(false);
first in first you didn't check all conditions
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if (response.equals("success")) {
dialog.dismiss();
getApplicationContext().startActivity(new Intent(getApplicationContext(), MainActivity.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
**} else {
Toast.makeText(getApplicationContext(), response, Toast.LENGTH_LONG).show();
}**
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
dialog.dismiss();
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
}
The else block doesn't hide the dialog so you should change it in this way
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
dialog.dismiss();
if (response.equals("success")) {
getApplicationContext().startActivity(new Intent(getApplicationContext(), MainActivity.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
} else {
Toast.makeText(getApplicationContext(), response, Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
dialog.dismiss();
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
}
I think that the mistake is this, of course assuming that your dialog is accessible from the callback
Change your Dialog.show method to use this version: show(Context context, CharSequence title, CharSequence message, boolean indeterminate, boolean cancelable) like this:
final ProgressDialog dialog = ProgressDialog.show(context, "Signing up","Please wait...", false, true);
So your onClick code should change to something like this:
public void onClick(View view) {
final ProgressDialog dialog = ProgressDialog.show(context, "Signing up","Please wait...", false, true);
login_call();
}
Please give this a try and let me know if it helps.

How to load progress bar in android until response comes from server

Hi In my Application I'm sending one request to server to validate the user,after sending the request I'm storing that value in database and making the status as 1, after some time I'm changing the status to 2 in database.Now my android app should wait till the status becomes 2. For this I'm showing the user in mobile progress bar.But my problem is as soon as I send the request progress bar stops displaying in the mobile.
Here is what I have tried.
progressDialog = new ProgressDialog(MainActivity.this);
progressDialog.show();
progressDialog.setTitle("Please Wait");
progressDialog.setMax(100);
e1 = edittext.getText().toString();
//Toast.makeText(MainActivity.this, "" + e1, Toast.LENGTH_SHORT).show();
AsyncHttpClient client = new AsyncHttpClient();
final RequestParams params = new RequestParams();
params.put("sendingJSON", composeJSON());
client.post("http://192.168.43.137/gpstracker/check_user.php", params, new AsyncHttpResponseHandler() {
public void onSuccess(String response) {
Gson gson = new GsonBuilder().create();
try {
progressDialog.dismiss();
JSONArray arr = new JSONArray(response);
for (int i = 0; i < arr.length(); i++) {
JSONObject obj = (JSONObject) arr.get(i);
String general = obj.get("success").toString();
Toast.makeText(getApplicationContext(), ""+general, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void onFailure(int statusCode, Throwable error, String content) {
if (statusCode == 404) {
Toast.makeText(getApplicationContext(), "Requested resource not found", Toast.LENGTH_LONG).show();
} else if (statusCode == 500) {
Toast.makeText(getApplicationContext(), "Something went wrong at server end", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "Unexpected Error occcured! [Most common Error: Device might not be connected to Internet]",Toast.LENGTH_LONG).show();
}
}
});
}
});
alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int whichButton) {
// what ever you want to do with No option.
}
}
);
alert.show();
}
A good solution in this cases is to work with events. Using events you can notify everywhere that something is happening. In your case, you can send an event when "the status changes to 2 in the database" and dismiss the progress dialog. There is a powerful and easy-to-use library to work with events called eventbus:
https://github.com/greenrobot/EventBus
I hope this helps to clarify!
I would recomend you to use an AsynkTask to do it. You can create the progress dialog in the onPreExecute() method, do what you are trying to do (post action or database update) in doInBackground() and once you have everything you want, in the onPostExecute() you can dismiss the dialog and send the result/data, if you need to, to your activity.
public class yourAsyncTask extends AsynkTask<Params, Params, Params>
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(context);
pDialog.setMessage("Charging...");
pDialog.setCancelable(true);
pDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
errorMesaje = "Process cancelled";
cancel(true);
}
});
pDialog.show();
}
#Override
protected Void doInBackground(Params... params) {
//Do your things here...
#Override
protected void onPostExecute(Void void) {
super.onPostExecute(void);
//Use an interface to call your activity and pass the data, you will have to change the attribute of the method in order to do it.
// Dismiss your dialog when your requests have finished
pDialog.dismiss();
}
I donĀ“t understand what are you trying to do exactly, if you just want to be sure that the post action is completed before the progress bar goes off, this solution will be fine. You can also call in the doInBackground() to your database and update it.
Hope it's clear enough!

Categories

Resources