I have this code:
class AttemptLogin extends AsyncTask {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MyAkan.this);
pDialog.setMessage("Attempting login...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String... arg0) {
int success;
String idnumber = etIdnumber.getText().toString();
String password = etPassword.getText().toString();
try {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("idnumber", idnumber));
params.add(new BasicNameValuePair("password", password));
JSONObject json = jsonParser.makeHttpRequest(LOGIN_URL, "POST",
params);
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
Log.d("Login Successful!", json.toString());
Intent i = new Intent("com.gpplsmje.mac.akan.AKANMENU");
String id = json.getString(TAG_IDNUMBER);
i.putExtra("idnumber", id);
finish();
startActivity(i);
return json.getString(TAG_MESSAGE);
} else if (success == 0) {
Log.d("Login Failure!", json.getString(TAG_MESSAGE));
return json.getString(TAG_MESSAGE);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String file_url) {
// TODO Auto-generated method stub
pDialog.dismiss();
if (file_url != null) {
Toast.makeText(MyAkan.this, file_url, Toast.LENGTH_LONG).show();
}
}
}
This app connects to a server and returns encoded JSON data. Whenever I test it on a local server on my machine, it works fine. It connects fine with the server. But when I turn off my server and use the app, the app loads but stops after a minute or so of login attempt. Is there a way to time the progress for maybe 20sec maximum, and then if it consumes the time it must dismiss the progressdialog and return to the main activity?
Thanks.
Your jsonParser object use HTTPURLConnection to do http requests ? If so there is a method setConnectTimeout.
If you are using DefaultHttpClient take a look a this question How to set HttpResponse timeout for Android in Java
Remember that above android 2.2 it's better to use HTTPURLConnection take a look at http://android-developers.blogspot.fr/2011/09/androids-http-clients.html for more details.
Related
I'm trying to retrieve data from JSON but it crashes whenever I try to retrieve data from my Android app.
// Intent i = new Intent(this,MainMenu.class);
// startActivity(i);
new AsyncTask<Void, Void, Void>()
{
ProgressDialog progressDialog;
#Override
protected void onPreExecute()
{
super.onPreExecute();
progressDialog = new ProgressDialog(JobScreen.this);
progressDialog.setMessage("Getting Items..");
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDialog.setIndeterminate(true);
progressDialog.setCancelable(false);
progressDialog.show();
}
#Override
protected Void doInBackground(Void... voids)
{
try
{
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet post = new HttpGet("http://users.abdullahadhaim.com/users/WebServiceResturant.asmx/login?userName=abood&Password=123");
HttpResponse response = httpClient.execute(post);
String responseString = EntityUtils.toString(response.getEntity());
JSONArray jsonArray = new JSONArray(responseString);
JSONObject jsonObject = jsonArray.getJSONObject(0);
ed1.setText(jsonObject.getString("UserName"));
Log.e("Done", "Done");
}
catch (Exception e)
{
e.printStackTrace();
Toast.makeText(JobScreen.this, "Faild", Toast.LENGTH_SHORT).show();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid)
{
super.onPostExecute(aVoid);
progressDialog.dismiss();
}
}.execute();
It looks like the problem is that you're calling ed1.setText() in the background thread.
Just move that call to onPostExecute(), and return the String value that you need from doInBackground().
Also remove the Toast from doInBackground(), and move it to onPostExecute() to be displayed if the return value of doInBackground() is null;
I just ran this, and it worked fine, and set the text to abood:
//use String for last parameter here:
new AsyncTask<Void, Void, String>() {
ProgressDialog progressDialog;
protected void onPreExecute() {
super.onPreExecute();
progressDialog = new ProgressDialog(JobScreen.this);
progressDialog.setMessage("Getting Items..");
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDialog.setIndeterminate(true);
progressDialog.setCancelable(false);
progressDialog.show();
}
//String return value:
protected String doInBackground(Void... unused) {
try
{
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet post = new HttpGet("http://users.abdullahadhaim.com/users/WebServiceResturant.asmx/login?userName=abood&Password=123");
HttpResponse response = httpClient.execute(post);
String responseString = EntityUtils.toString(response.getEntity());
JSONArray jsonArray = new JSONArray(responseString);
JSONObject jsonObject = jsonArray.getJSONObject(0);
Log.e("Done", "Done");
//return the String you need:
return jsonObject.getString("UserName");
}
catch (Exception e)
{
e.printStackTrace();
//remove this Toast:
//Toast.makeText(MainActivity.this, "Faild", Toast.LENGTH_SHORT).show();
}
return null;
}
//String parameter
protected void onPostExecute(String username) {
super.onPostExecute(username);
if (username == null){
//Toast if username is null
Toast.makeText(MainActivity.this, "Failed", Toast.LENGTH_SHORT).show();
}
else{
//Set the text here with the String received:
ed1.setText(username);
}
progressDialog.dismiss();
}
}.execute();
MainActivity.java
class LoadProfile extends AsyncTask<String, String, String>{
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(EventHome.this);
pDialog.setMessage("Loading...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting Profile JSON
* */
protected String doInBackground(String... args) {
// Building Parameters
String json = null;
try {
List<NameValuePair> params = new ArrayList<NameValuePair>();
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(PROFILE_URL);
httppost.setEntity(new UrlEncodedFormEntity(params));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
json = EntityUtils.toString(resEntity);
Log.i("All Events: ", json.toString());
} catch (Exception e) {
e.printStackTrace();
}
return json;
}
#Override
protected void onPostExecute(String json) {
super.onPostExecute(json);
// dismiss the dialog after getting all products
pDialog.dismiss();
try{
event_all = new JSONObject(json);
JSONArray user = event_all.getJSONArray("events");
JSONObject jb= user.getJSONObject(0);
String name = jb.getString("name");
String venue=jb.getString("location");
String date=jb.getString("date_d");
String descr=jb.getString("descr");
image1=jb.getString("images1");
// displaying all data in textview
tv3.setText(name);
tv4.setText(venue+", "+date);
tv5.setText(descr);
Picasso.with(this).load(image1).into(iv7);
}catch(Exception e)
{
e.printStackTrace();
}
}
}
while executing the above code I got some error on line Picasso.with(this).load(image1).into(iv7);
And the error is the method with(context) in the type Picasso is not applicable for the arguments(MainActivity.LoadProfile).
What's the problem in my coding.
You may change
Picasso.with(this).load(image1).into(iv7);
to
Picasso.with(MainActivity.this).load(image1).into(iv7);
give it a try.
You have placed Picasso.with(this).load(image1).into(iv7); this line in AsyncTask's onPostExecute. So, here this refers that AsyncTask not the context of that Activity. You have to do like this
Picasso.with(MainActivity.this).load(image1).into(iv7);
I have an android activity that reads some items from the web server, everything is alright except the image.
I've done the same with only one item and it worked, but I can't think of anyway to read many items and set their value to imageView.
Is there anyway that allows me to set the image value to the listAdapter after ending them by hashmap?
Any help would be greatly appreciated!
Here is the code:
class LoadAllProducts extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(GetAllRecipesActivity.this);
pDialog.setMessage("Loading products. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting All products from url
* */
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("category", R_category));
Log.d("R_category: ", R_category);
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);
// Check your log cat for JSON reponse
Log.d("All Products: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
products = json.getJSONArray(TAG_table);
// looping through All Products
for (int i = 0; i < products.length(); i++) {
JSONObject c = products.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_SCB_ID);
String title = c.getString(TAG_TITLE);
String name = c.getString(TAG_NAME);
name= name.substring(1, name.length());
name="http://studentcookbook.comoj.com/android_connect"+name;
Log.d("NAME OF THE URL!",name);
// here i'm starting to set the image value it's all good here
downloadBitma =downloadBitmap(name);
// creating new HashMap
HashMap<String, Object> map=new HashMap<String, Object>();
// adding each child node to HashMap key => value
map.put(TAG_SCB_ID, id);
map.put(TAG_TITLE, title);
map.put(TAG_NAME, downloadBitma);
// adding HashList to ArrayList
productsList.add(map);
}
} else {
// Launch Add New product Activity
Intent i = new Intent(getApplicationContext(),AddRecipeActivity.class);
// Closing all previous activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
} catch (JSONException e) {
e.printStackTrace();
Log.e("Buffer Error", "Error converting result " + e.toString());
} catch (IOException e) {
e.printStackTrace();
Log.e("Buffer Error", " Image is not passing to hashmap");
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
// here i'm trying to set the image to imageView but it didn't work
// final ImageView imageView = (ImageView) findViewById(R.id.GetAllmg);
// runOnUiThread(new Runnable() {
// #Override
// public void run() {
// imageView.setImageBitmap(downloadBitma); }
// });
ListAdapter adapter = new SimpleAdapter(GetAllRecipesActivity.this, productsList,
R.layout.list_recipe, new String[] { TAG_SCB_ID,TAG_TITLE},
new int[] { R.id.GetAllscbid, R.id.GetAllTitle });
// updating listview
Toast.makeText(GetAllRecipesActivity.this, "onPostExecute", Toast.LENGTH_SHORT).show();
setListAdapter(adapter);
}
});
}
// method for downloading images
private Bitmap downloadBitmap(String url) throws IOException {
HttpUriRequest request = new HttpGet(url.toString());
HttpClient httpClient = new DefaultHttpClient();
HttpResponse response = httpClient.execute(request);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
byte[] bytes = EntityUtils.toByteArray(entity);
Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0,
bytes.length);
return bitmap;
} else {
throw new IOException("Download failed, HTTP response code "
+ statusCode + " - " + statusLine.getReasonPhrase());
}
}
I recommend Universal Image Loader.
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
I have a CreateUser class which creates a user. This worked correctly until I tried to add a new field for a password check.
In the task I'm checking to see if the password fields match and if they dont I cancel the execution and move to a toast.
It correctly checks the passwords and toasts when incorrect but if they match it still cancels execution and never completes creating a new user.
CODE:
public class Register extends Activity implements OnClickListener{
private EditText user, pass, confirmPass;
private Button mRegister;
// Progress Dialog
private ProgressDialog pDialog;
// JSON parser class
JSONParser jsonParser = new JSONParser();
private static final String LOGIN_URL = "https://xxx.xxx.xxx.xxx/xxx.php";
//ids
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.register);
user = (EditText)findViewById(R.id.username);
pass = (EditText)findViewById(R.id.password);
confirmPass = (EditText)findViewById(R.id.passwordConfirm);
mRegister = (Button)findViewById(R.id.register);
mRegister.setOnClickListener(this);
}
#Override
public void onClick(View v) {
new CreateUser().execute();
}
class CreateUser extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
boolean failure = false;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Register.this);
pDialog.setMessage("Creating User...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String... args) {
// TODO Auto-generated method stub
// Check for success tag
int success;
String username = user.getText().toString();
String password = pass.getText().toString();
String passwordCheck = confirmPass.getText().toString();
try {
//-----------------------------------------------------------------------------Password Check
if (password != passwordCheck) {
cancel(true);
}
if (!this.isCancelled()) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", username));
params.add(new BasicNameValuePair("password", password));
Log.d("request!", "starting");
//Posting user data to script
JSONObject json = jsonParser.makeHttpRequest(
LOGIN_URL, "POST", params);
// full json response
Log.d("Login attempt", json.toString());
// json success element
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
Log.d("User Created!", json.toString());
finish();
return json.getString(TAG_MESSAGE);
} else {
Log.d("Login Failure!", json.getString(TAG_MESSAGE));
return json.getString(TAG_MESSAGE);
}
}
}catch(JSONException e){
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once product deleted
pDialog.dismiss();
if (file_url != null){
Toast.makeText(Register.this, file_url, Toast.LENGTH_LONG).show();
}
}
#Override
protected void onCancelled() {
pDialog.dismiss();
Toast.makeText(Register.this, "Passwords do not match", Toast.LENGTH_SHORT).show();
}
}}
In your doInBackground, you're comparing 2 strings using != this will only compare the memory addresses of the strings and therefore will evaluate to false even if the value of the two strings is the same. Change it to equals()
This question already has answers here:
String.equals versus == [duplicate]
(20 answers)
Closed 10 years ago.
I have an AsyncTask class in my application but what I noticed is that whatever the result passed on to to the onPostExecute function is, it will still direct the application to go to the else{} even though it perfectly fits the if statement. Why is that happening?
Here is the AsyncTask I am running :
class CheckPassword extends AsyncTask<String, String, String>{
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(ChooseTable.this);
pDialog.setMessage("Checking Password. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected String doInBackground(String... p) {
String password = p[0];
int success;
String access = "";
try {
// Building Parameter
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("password", password));
//ipaddress of server
Intent i = getIntent();
Bundle b = i.getExtras();
ipaddress = b.getString("IP_Address");
if(ipaddress != "" || ipaddress != "...:")
{
// single table url
String url = "http://"+ipaddress+"/MenuBook/checkSpecial.php";
Log.d("URL", url + "");
JSONObject json = jsonParser.makeHttpRequest(
url, "GET", params);
Log.d("JSON OBJECT", json+"");
// json success tag
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully received table details
JSONArray result = json
.getJSONArray("result"); // JSON Array
// get table availability from JSON Array
JSONObject accessObj = result.getJSONObject(0);
access= accessObj.getString("allowAccess");
}
else
{
status = "TABLE NOT FOUND";
}
}
else
{
status = "FAILED TO RETRIEVE SERVER IP ADDRESS";
}
} catch (JSONException e) {
e.printStackTrace();
}
Log.d("ALLOW ACCESS", access+"");
return access;
}
#Override
protected void onPostExecute(String result) {
pDialog.dismiss();
Log.d("RESULT", result+"");
if(result == "YES"){
Toast.makeText(ChooseTable.this, "ACCESS ALLOWED", Toast.LENGTH_LONG).show();
}else if (result== "NO"){
Toast.makeText(ChooseTable.this, "Access Denied", Toast.LENGTH_LONG).show();
}else{
Toast.makeText(ChooseTable.this, status, Toast.LENGTH_LONG).show();
}
}
}
You need to use the equals method to compare two Strings:
if (result.equals("YES"))
and
if (result.equals("NO"))