App crashes when getting data from JSON - java

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

Related

How i can println the statuscode in display with a toast when the request is fail?

Need to println HttpResponse response if the conexion is fail
private class HttpAsyncTask extends AsyncTask<String, Void, String> {
private ProgressDialog pDialog;
#Override
protected String doInBackground(String... params) {
return GET();
}
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Iniciando sesiĆ³n...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected void onPostExecute(String result) {
pDialog.dismiss();
}
public String GET() {
String url = "http://"+ippref+":8080/Activo/webresources/activo.entities.coreusuario/usuarios/" + usuario_ws + "/" +contrasenia_ws+ "";
String result = "";
BufferedReader inStream = null;
try {
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpRequest = new HttpGet(url);
HttpResponse response = httpClient.execute(httpRequest);
response.getStatusLine().getStatusCode();
inStream = new BufferedReader(
new InputStreamReader(
response.getEntity().getContent()));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = inStream.readLine()) != null) {
buffer.append(line);
}
inStream.close();
result = buffer.toString();
respuesta_ws = Integer.valueOf(result);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
Need printl the statuscode
Check for return status. If its value is not 200 then its a failure and toast it.
if(response.getStatusLine().getStatusCode()!=200){
Toast.makeText(getApplicationContext(),
"Request failure!",
Toast.LENGTH_LONG).show();
}
Use this :
Toast.makeText(getApplicationContext(),
response.getStatusLine().getStatusCode(),
Toast.LENGTH_LONG).show();
import android.widget.Toast
And you can change time of toast by changing Toast.LENGTH_LONG
Of course if you want to only show toast when http response is bad,then add the logic for checking the error cases and make toast there.
Hope this helps. :)

Picasso loading image error-Android

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

directing to Activity from Asynctask

this is the LoginActivty
public class MainActivity extends Activity {
ProgressDialog prgDialog;
TextView errorMsg;
EditText emailET;
EditText pwdET;
Button button;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
errorMsg = (TextView) findViewById(R.id.login_error);
emailET = (EditText) findViewById(R.id.loginEmail);
pwdET = (EditText) findViewById(R.id.loginPassword);
prgDialog = new ProgressDialog(this);
prgDialog.setMessage("Please wait...");
prgDialog.setCancelable(false);
button = (Button) findViewById(R.id.btnLogin);
final Button button = (Button) findViewById(R.id.btnLogin);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
// Get Email Edit View Value
String email = emailET.getText().toString();
// Get Password Edit View Value
String password = pwdET.getText().toString();
// When Email Edit View and Password Edit View have values
// other than Null
if (Utility.isNotNull(email) && Utility.isNotNull(password)) {
// When Email entered is Valid
if (Utility.validate(email)) {
// call the async task
JSONObject js = new HttpAsyncTask(
getApplicationContext()).execute(email,
password).get();
Toast.makeText(getApplicationContext(),
"Asynctask started", Toast.LENGTH_SHORT)
.show();
}
// When Email is invalid
else {
Toast.makeText(getApplicationContext(),
"Please enter valid email",
Toast.LENGTH_LONG).show();
}
}
// When any of the Edit View control left blank
else {
Toast.makeText(
getApplicationContext(),
"Please fill the form, don't leave any field blank",
Toast.LENGTH_LONG).show();
}
} catch (Exception ex) {
}
}
});
TextView registerScreen = (TextView) findViewById(R.id.link_to_register);
// Listening to register new account link
registerScreen.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Switching to Register screen
Intent i = new Intent(getApplicationContext(),
RegisterActivity.class);
startActivity(i);
}
});
}
}
then I am using a AsyncTask, this the code
public class HttpAsyncTask extends AsyncTask<String, Integer, JSONObject> {
private static InputStream stream = null;
private static String API;
private JSONObject responseJson = null;
private Context contxt;
private Activity activity;
public HttpAsyncTask(Context context) {
// API = apiURL;
this.contxt = context;
}
// async task to accept string array from context array
#Override
protected JSONObject doInBackground(String... params) {
String path = null;
String response = null;
HashMap<String, String> request = null;
JSONObject requestJson = null;
DefaultHttpClient httpClient = null;
HttpPost httpPost = null;
StringEntity requestString = null;
ResponseHandler<String> responseHandler = null;
// get the username and password
Log.i("Email", params[0]);
Log.i("Password", params[1]);
try {
path = "http://192.168.x.xxx/xxxxService/UserAuthentication";
new URL(path);
} catch (MalformedURLException e) {
e.printStackTrace();
}
try {
// set the API request
request = new HashMap<String, String>();
request.put(new String("Email"), params[0]);
request.put(new String("Password"), params[1]);
request.entrySet().iterator();
// Store locations in JSON
requestJson = new JSONObject(request);
httpClient = new DefaultHttpClient();
httpPost = new HttpPost(path);
requestString = new StringEntity(requestJson.toString());
// sets the post request as the resulting string
httpPost.setEntity(requestString);
httpPost.setHeader("Content-type", "application/json");
// Handles the response
responseHandler = new BasicResponseHandler();
response = httpClient.execute(httpPost, responseHandler);
responseJson = new JSONObject(response);
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
try {
responseJson = new JSONObject(response);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
return responseJson;
}
#Override
protected void onPostExecute(JSONObject result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
String myResJson;
try {
myResJson = responseJson.getString("status");
String test = myResJson;
if (test.equals("200")) {
Log.i("Login Success", "Success message");
} else {
Log.e("Login Error", "Error converting result ");
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
when I enter correct email and password, it comes to this line
Log.i("Login Success", "Success message");
from there I want to open the HomeActivty but it doesn't allow me to use intent, or even to toast
I need help to implement directing to Home Activity once the logging is success.
Here:
JSONObject js = new HttpAsyncTask(
getApplicationContext()).execute(email,
password).get();
Because you are getting result on Main Thread by calling AsyncTask.get() method AsyncTask.
First just call AsyncTask.execute method to start AsyncTask task :
new HttpAsyncTask(MainActivity.this).execute(email,password);
then use onPreExecute() to show progessbar and onPostExecute for starting next Activity :
#Override
protected void onPreExecute() {
// show ProgressDialog here
}
#Override
protected void onPostExecute(Void result) {
// parse json here and start Home Activity
//.........your code here
if (test.equals("200")) {
Log.i("Login Success", "Success message");
Intent intent = new Intent(contxt,HomeActivity.class);
contxt.startActivity(intent);
} else {
Log.e("Login Error", "Error converting result ");
}
}
You can start activity like this from AsyncTask, You should use the context.
mContext.startActivity(new Intent(CurrentActivity.this, Home.class));
Or try like this also
Intent intent = new Intent();
intent.setClass(getApplicationContext(),Home.class);
startActivity(intent);
I know there is another valid answer to fix your problem. But to precisely explain why your error exists, I give my answer below.
To create an Intent for startActivity(), this can be done by:
Intent i = new Intent(currentActivity, NextActivity.class);
startActivity(i);
Notice that the first parameter of constructor of Intent is android.content.Context, in which Activity is a subclass of it. So in any situation, you can always pass the Context to your custom class and start a new Activity or create a Toast with this Context.
In your question, private Context contxt; in HttpAsyncTask is the context your need to do everything.
Reference: http://developer.android.com/reference/android/content/Intent.html#Intent%28android.content.Context,%20java.lang.Class%3C?%3E%29

How to set progressbar while fetching data from server on click? [duplicate]

This question already has answers here:
Updating progress dialog in Activity from AsyncTask
(2 answers)
How to use AsyncTask to show a ProgressDialog while doing background work in Android? [duplicate]
(2 answers)
Closed 8 years ago.
I want to add progressbar while new activity is not opened.
on next activity I am also fetching data so I want to add a progress bar on next activity also.
Here is my code.
login=(Button)dialog.findViewById(R.id.buttonLogin);
login.setOnClickListener(new OnClickListener() {
#SuppressLint("DefaultLocale")
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if(LoginUsername.getText()==null||LoginUsername.getText().toString().equals(""))
{
LoginUsername.setHint("Enter Username");
LoginUsername.setHintTextColor(Color.RED);
}
else if(LoginPassword.getText()==null||LoginPassword.getText().toString().equals("")||LoginPassword.getText().toString().length()<6)
{
LoginPassword.setText("");
LoginPassword.setHint("Enter Password");
LoginPassword.setHintTextColor(Color.RED);
}
else
{
String username=LoginUsername.getText().toString();
String password=LoginPassword.getText().toString();
username1=username.toLowerCase();
// fetch the Password form database for respective user name
//String loginentries=database.getSingleEntry(username1);
//type=database.getType(username1);
try{
HttpClient client=new DefaultHttpClient();
HttpPost post=new HttpPost("http://www.universal-cinemas.com/android/login.php");
JSONObject jobj=new JSONObject();
jobj.put("username",username1);
jobj.put("password", password);
post.setEntity(new StringEntity(jobj.toString()));
Log.i("Info", "Sending request");
HttpResponse res=client.execute(post);
Log.i("Info", "Executed");
InputStream inp=res.getEntity().getContent();
BufferedReader bf = new BufferedReader(new InputStreamReader(inp));
StringBuilder sb= new StringBuilder();
sb.append(bf.readLine()+"\n");
String tmp="0";
while((tmp=bf.readLine())!=null)
{
sb.append(tmp+"\n");
}
String result= sb.toString();
JSONArray jarray=new JSONArray(result);
for(int i=0;i<jarray.length();i++)
{
a=1;
JSONObject job=jarray.getJSONObject(i);
type=job.getString("type");
currency=job.getString("currency");
}
}
catch(Exception e)
{
e.printStackTrace();
}
if(a==1)
{
i=new Intent(getApplicationContext(),User_MainOptions_List.class);
startActivity(i);
finish();
Toast.makeText(getApplicationContext(), "Welcome "+username, Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(getApplicationContext(), "Username and Password is not correct", Toast.LENGTH_SHORT).show();
}
}
}
});
dialog.show();
WindowManager.LayoutParams lp = dialog.getWindow().getAttributes(); // retrieves the windows attributes
lp.dimAmount=0.7f;// sets the dimming amount to zero
dialog.getWindow().setAttributes(lp); // sets the updated windows attributes
dialog.getWindow().addFlags(WindowManager.LayoutParams.FLAG_BLUR_BEHIND); // adds the flag to blur bg
}
});
class MyLodingAsycTask extends AsyncTask<Void, Void, Void>{
private ProgressDialog progressDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
runOnUiThread(new Runnable() {
public void run() {
progressDialog = new ProgressDialog(CameraActivity.this);
progressDialog.setMessage("Loding...");
progressDialog.setCancelable(false);
progressDialog.show();
}
});
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
runOnUiThread(new Runnable() {
public void run() {
if(progressDialog.isShowing())
progressDialog.dismiss();
}
});
}
#Override
protected Void doInBackground(Void... params) {
//call HTTP service
return null;
}
}
try this
private class MyAsync extends AsyncTask {
ProgressDialog PD;
#Override
protected void onPreExecute() {
super.onPreExecute();
PD = new ProgressDialog(MainActivity.this);
PD.setTitle("Please Wait..");
PD.setMessage("Loading...");
PD.setCancelable(false);
PD.show();
}
#Override
protected Void doInBackground(Void... params) {
//do what u want
return result;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
PD.dismiss();
}
}
}

Showing Progress Dialog while loading data from the internet

I want to show a Progress Dialog on button click in my app while data is loaded from the internet. I can't get it to work, could someone give me some tips on where to put the Dialog function?
This is my AsyncTask method:
private class GetTweets extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... twitterURL) {
//start building result which will be json string
StringBuilder tweetFeedBuilder = new StringBuilder();
//should only be one URL, receives array
for (String searchURL : twitterURL) {
HttpClient tweetClient = new DefaultHttpClient();
try {
//pass search URL string to fetch
HttpGet tweetGet = new HttpGet(searchURL);
//execute request
HttpResponse tweetResponse = tweetClient.execute(tweetGet);
StatusLine searchStatus = tweetResponse.getStatusLine();
if (searchStatus.getStatusCode() == 200) {
//get the response
HttpEntity tweetEntity = tweetResponse.getEntity();
InputStream tweetContent = tweetEntity.getContent();
InputStreamReader tweetInput = new InputStreamReader(tweetContent);
BufferedReader tweetReader = new BufferedReader(tweetInput);
String lineIn;
while ((lineIn = tweetReader.readLine()) != null) {
tweetFeedBuilder.append(lineIn);
}
}
else
tweetDisplay.setText("Error!");
}
catch(Exception e){
tweetDisplay.setText("Error!");
e.printStackTrace();
}
}
//return result string
return tweetFeedBuilder.toString();
}
protected void onPostExecute(String result) {
//start preparing result string for display
StringBuilder tweetResultBuilder = new StringBuilder();
try {
//get JSONObject from result
JSONObject resultObject = new JSONObject(result);
//get JSONArray contained within the JSONObject retrieved - "results"
JSONArray tweetArray = resultObject.getJSONArray("results");
//loop through each item in the tweet array
for (int t=0; t<tweetArray.length(); t++) {
//each item is a JSONObject
JSONObject tweetObject = tweetArray.getJSONObject(t);
tweetResultBuilder.append(tweetObject.getString("from_user")+": ");
tweetResultBuilder.append(tweetObject.get("text")+"\n\n");
}
}
catch (Exception e) {
tweetDisplay.setText("Error!");
e.printStackTrace();
}
//check result exists
if(tweetResultBuilder.length()>0)
tweetDisplay.setText(tweetResultBuilder.toString());
else
tweetDisplay.setText("no results!");
}
}
In the AsyncTask class use onPrexecute method to display progress dialog and use onPostExecute to dismiss it:
#Override
protected void onPreExecute()
{
super.onPreExecute();
pDialog = new ProgressDialog(YOUR_ACTIVITY_CLASS_NAME.this);
pDialog.setMessage("Please Wait");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected void onPostExecute(String str)
{
// Dismiss the dialog once finished
pDialog.dismiss();
}
Don't forget to define pDialog before you call it:
ProgresDialog pDialog;

Categories