Android - How to Handle an Async Http Crash - java

My app is currently crashing whenever it cannot connect to the server. How do I handle this, and instead let the user know that the server is down and to try again.
private void sendPostRequest(String givenEmail, String givenPassword) {
class SendPostRequestTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
String emailInput = params[0];
String passwordInput = params[1];
String jsonUserInput = "{email: " + emailInput + ", password: "
+ passwordInput + "}";
try {
HttpClient httpClient = new DefaultHttpClient();
// Use only the web page URL as the parameter of the
// HttpPost argument, since it's a post method.
HttpPost httpPost = new HttpPost(SERVER_URL);
// We add the content that we want to pass with the POST
// request to as name-value pairs
json = new JSONObject(jsonUserInput);
jsonString = new StringEntity(json.toString());
httpPost.setEntity(jsonString);
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
HttpParams httpParameters = httpPost.getParams();
// Set the timeout in milliseconds until a connection is established.
int timeoutConnection = 1000;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
// Set the default socket timeout (SO_TIMEOUT)
// in milliseconds which is the timeout for waiting for data.
int timeoutSocket = 1000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
// HttpResponse is an interface just like HttpPost.
// Therefore we can't initialize them
HttpResponse httpResponse = httpClient.execute(httpPost);
// According to the JAVA API, InputStream constructor does
// nothing.
// So we can't initialize InputStream although it is not an
// interface
InputStream inputStream = httpResponse.getEntity()
.getContent();
InputStreamReader inputStreamReader = new InputStreamReader(
inputStream);
BufferedReader bufferedReader = new BufferedReader(
inputStreamReader);
StringBuilder stringBuilder = new StringBuilder();
String bufferedStrChunk = null;
while ((bufferedStrChunk = bufferedReader.readLine()) != null) {
stringBuilder.append(bufferedStrChunk);
}
return stringBuilder.toString();
} catch (ClientProtocolException cpe) {
Log.i(LOGIN, "ClientProtocolException");
cpe.printStackTrace();
} catch (ConnectTimeoutException e) {
e.printStackTrace();
} catch (IOException ioe) {
Log.i(LOGIN, "IOException");
ioe.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Log.i(LOGIN, result);
try {
serverResponse = new JSONObject(result);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
if ((serverResponse.has("status"))
&& (serverResponse.get("status").toString()
.equals("200"))) {
Toast.makeText(getApplicationContext(), "SUCCESS!",
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(),
"Incorrect Email/Password!!!",
Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
SendPostRequestTask sendPostRequestTask = new SendPostRequestTask();
sendPostRequestTask.execute(givenEmail, givenPassword);
}
LogCat Error Log
11-11 16:26:14.970: I/R.id.login_button(17379): IOException
11-11 16:26:14.970: W/System.err(17379): org.apache.http.conn.HttpHostConnectException: Connection to http://* refused
11-11 16:26:14.980: W/System.err(17379): at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:183)

I can see that you are already catching the Exceptions and have a String as parameter type to onPostExecute. From inside the exceptions, you can pass a string like "error" to the onPostExecute, whenever an error occurs. Inside the onPostExecute you can check:
if the string is equal to "error":
then create a Alert dialog box from within `onPostExecute` and show it.
else:
continue as desired
Ideally a boolean would do the trick but since you already have a string, you can also use that. Otherwise you can have a struct with a string and a boolean and then pass it to onPostExecute. Hope it gives you the idea.

Or you can create new Object
public class AsyncTaskResult<T> {
private T result;
private Exception error;
public T getResult() {
return result;
}
public Exception getError() {
return error;
}
public AsyncTaskResult(T result) {
super();
this.result = result;
}
public AsyncTaskResult(Exception error) {
super();
this.error = error;
}
public void setError(Exception error) {
this.error = error;
}
}
and pass it to onPostExecute
return new AsyncTaskResult<String>(result)
or
return new AsyncTaskResult<String>(exception)
in onPostExecute you may check exception exists or not
asynctaskresult.getError() != null

You can use droidQuery to simplify everything and include HTTP error handling:
$.ajax(new AjaxOptions().url("http://www.example.com")
.type("POST")
.dataType("json")
.header("Accept", "application/json")
.header("Content-type", "application/json")
.timeout(1000)
.success(new Function() {
#Override
public void invoke($ d, Object... args) {
Toast.makeText(this, "SUCCESS!", Toast.LENGTH_SHORT).show();
JSONObject serverResponse = (JSONObject) args[0];
//handle response
}
})
.error(new Function() {
#Override
public void invoke($ d, Object... args) {
AjaxError error = (AjaxError) args[0];
//toast shows the error code and reason, such as "Error 404: Page not found"
Toast.makeText(this, "Error " + error.status + ": " + error.reason, Toast.LENGTH_SHORT).show();
}
}));

Related

progressDialoge not Updating

i have been using AsyncTask to download a certain file and went through a few tutorials and just failed to get the progress bar to move with the download. the code is and AsyncTask that calls a method to do the HTTP connection and then comes back to assort the data in a proper way to manipulate it for the app
this is my AsynTask that is on the MainActivity
private class getFood extends AsyncTask<Void, Integer, Cursor> {
private ProgressDialog mProgressDialog;
#Override
protected Cursor doInBackground(Void... params) {
// Create URL object
String site = "https://afternoon-ridge-50060.herokuapp.com/allsnacks";
URL url = createUrl(site);
// Perform HTTP request to the URL and receive a JSON response back
String jsonResponse = null;
try {
String jsonResponseEmpty = "";
// If the URL is null, then return early.
if (url == null) {
jsonResponse = jsonResponseEmpty;
}
HttpURLConnection urlConnection = null;
InputStream inputStream = null;
try {
assert url != null;
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setReadTimeout(20000 /* milliseconds */);
urlConnection.setConnectTimeout(25000 /* milliseconds */);
urlConnection.setRequestMethod("GET");
urlConnection.setRequestProperty("Authorization", "\"token\": " + token);
urlConnection.connect();
// If the request was successful (response code 200),
// then read the input stream and parse the response.
if (urlConnection.getResponseCode() == 200) {
int fileLength = urlConnection.getContentLength();
Log.d("size", String.valueOf(fileLength));
inputStream = urlConnection.getInputStream();
StringBuilder output = new StringBuilder();
if (inputStream != null) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, Charset.forName("UTF-8"));
BufferedReader reader = new BufferedReader(inputStreamReader);
String line = reader.readLine();
jsonResponse = output.toString();
} else {
Log.e(LOG_TAG, "Error response code: " + urlConnection.getResponseCode());
}
} catch (IOException e) {
Log.e(LOG_TAG, "Problem retrieving the Food JSON results.", e);
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (inputStream != null) {
// Closing the input stream could throw an IOException, which is why
// the makeHttpRequest(URL url) method signature specifies than an IOException
// could be thrown.
inputStream.close();
}
}
} catch (IOException e) {
Log.e(LOG_TAG, "Problem making the HTTP request.", e);
}
// Extract relevant fields from the JSON response and create a list of {#link Earthquake}s
//*List<FoodList> Food = extractFeatureFromJson(jsonResponse);
Cursor foodTable = extractFeatureFromJson(jsonResponse);
// Return the list of {#link Earthquake}s
Log.d("food", "done");
return foodTable;
}
#Override
protected void onProgressUpdate(Integer... values) {
// if we get here, length is known, now set indeterminate to false
mProgressDialog.setProgress(values[0]);
}
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create progress dialog
mProgressDialog = new ProgressDialog(loginActivity.this);
// Set your progress dialog Title
mProgressDialog.setTitle("Downloading");
// Set your progress dialog Message
mProgressDialog.setMessage("Downloading Important Files, Please Wait!");
mProgressDialog.setIndeterminate(false);
mProgressDialog.setMax(100);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
// Show progress dialog
mProgressDialog.show();
}
#Override
protected void onPostExecute(Cursor data) {
try {
int foodNumberColIndex = data.getColumnIndex(COLUMN_NDB_NO);
int foodNameColIndex = data.getColumnIndex(COLUMN_NAME);
int waterColIndex = data.getColumnIndex(COLUMN_WATER_G);
int energyColIndex = data.getColumnIndex(COLUMN_ENERGY_KCAL);
int proteinColIndex = data.getColumnIndex(COLUMN_PROTEIN_G);
int lipidColIndex = data.getColumnIndex(COLUMN_LIPID_TOT_G);
int ashColIndex = data.getColumnIndex(COLUMN_ASH_G);
int carboColIndex = data.getColumnIndex(COLUMN_CARBOHYDRT_G);
while (data.moveToNext()) {
Log.d("in", " progress");
FoodList foodItem = new FoodList(data.getInt(foodNumberColIndex),
data.getString(foodNameColIndex).trim().replace(",", "."),
data.getDouble(waterColIndex),
data.getDouble(energyColIndex),
data.getDouble(proteinColIndex),
data.getDouble(lipidColIndex),
data.getDouble(ashColIndex),
data.getDouble(carboColIndex));
allFood.add(foodItem);
}
} finally {
data.close();
}
mProgressDialog.dismiss();
startActivity(intentNew);
}
private URL createUrl(String stringUrl) {
URL url = null;
try {
url = new URL(stringUrl);
} catch (MalformedURLException e) {
Log.e(LOG_TAG, "Problem building the URL ", e);
}
return url;
}
private Cursor extractFeatureFromJson(String foodJSON) {
// If the JSON string is empty or null, then return early.
if (TextUtils.isEmpty(foodJSON)) {
return null;
}
try {
// Create a JSONArray from the JSON response string
JSONArray foodArray = new JSONArray(foodJSON);
for (int i = 0; i < foodArray.length(); i++) {
JSONObject foodObject = foodArray.getJSONObject(i);
ContentValues values = new ContentValues();
values.put(COLUMN_NDB_NO, foodObject.optInt(COLUMN_NDB_NO));
values.put(COLUMN_NAME, foodObject.optString(COLUMN_NAME));
values.put(COLUMN_WATER_G, foodObject.optDouble(COLUMN_WATER_G));
values.put(COLUMN_ENERGY_KCAL, foodObject.optDouble(COLUMN_ENERGY_KCAL));
values.put(COLUMN_PROTEIN_G, foodObject.optDouble(COLUMN_PROTEIN_G));
values.put(COLUMN_LIPID_TOT_G, foodObject.optDouble(COLUMN_LIPID_TOT_G));
values.put(COLUMN_ASH_G, foodObject.optDouble(COLUMN_ASH_G));
values.put(COLUMN_CARBOHYDRT_G, foodObject.optDouble(COLUMN_CARBOHYDRT_G));
foodNutriProvider insert = new foodNutriProvider();
insert.insert(CONTENT_URI, values);
}
} catch (JSONException e) {
// If an error is thrown when executing any of the above statements in the "try" block,
// catch the exception here, so the app doesn't crash. Print a log message
// with the message from the exception.
Log.e("foodSearch", "Problem parsing the earthquake JSON results", e);
Log.e("foodSearch", foodJSON);
}
foodNutriProvider getTable = new foodNutriProvider();
// Return the list of earthquakes
return getTable.query(CONTENT_URI, null, null, null, null);
}
}
You have to publish the progress and then only the Integer... values has proper values.
Something like:
#Override
protected String doInBackground(Context... params) {
//Part-1 of the task done
publishProgress(20);
//Part-2 of the task done
publishProgress(50);
//Part-3 of the task done
publishProgress(100);
return “success”;
}
As per android documentation:
"onProgressUpdate(Progress...), invoked on the UI thread after a call to publishProgress(Progress...). The timing of the execution is undefined. This method is used to display any form of progress in the user interface while the background computation is still executing. For instance, it can be used to animate a progress bar or show logs in a text field"
use it

Bug in AsyncTask causing random response

I am using an AsyncTask for a network call. If successful, it should return a JSON Array, and so far it works well on the device I test(Google nexus 5).
But on a Motorola device, it does not work. In the sense, it is not even sending a request to the server.
Here is the code :
private class SimpleTask extends AsyncTask<String, Void, String> {
ProgressDialog dialog;
#Override
protected void onPreExecute()
{
dialog = new ProgressDialog(MainActivity.this,ProgressDialog.STYLE_SPINNER);
dialog.setMessage("Loading Engine");
dialog.show();
}
protected String doInBackground(String... urls) {
String result = "";
try {
//HttpGet httpGet = new HttpGet(urls[0]);
HttpPost httpPost = new HttpPost(urls[0]);
HttpClient client = new DefaultHttpClient();
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("number",details));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = client.execute(httpPost);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 200) {
InputStream inputStream = response.getEntity().getContent();
BufferedReader reader = new BufferedReader
(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
result += line;
}
}
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
//Log.w("PREMIERE::::",result);
return result;
}
protected void onPostExecute(String jsonString) {
//dialog.dismiss();
try {
if ((this.dialog != null) && this.dialog.isShowing()) {
this.dialog.dismiss();
}
} catch (final IllegalArgumentException e) {
// Handle or log or ignore
} catch (final Exception e) {
// Handle or log or ignore
} finally {
this.dialog = null;
}
showData(jsonString);
}
}
private void showData(String jsonString)
{
// try
// {
Log.w("VALS:",""+jsonString);
Gson gson = new Gson();
JsonParser parser = new JsonParser();
JsonArray jArray = parser.parse(jsonString).getAsJsonArray();
SharedPreferences pref = getSharedPreferences("ActivitySession", Context.MODE_PRIVATE);
for(JsonElement obj : jArray )
{
MainPojo cse = gson.fromJson( obj , MainPojo.class);
uid.add(cse);
}
if(!uid.isEmpty())
{
new SimpleTask2().execute(URL2);
}
else
{
Snackbar.make(this.findViewById(android.R.id.content), "Invalid Credentials", Snackbar.LENGTH_LONG).show();
}
/*
}
catch (Exception e){
Snackbar.make(this.findViewById(android.R.id.content), "Check data connection", Snackbar.LENGTH_LONG).show();
e.printStackTrace();
}*/
}
And I purposefully, did not catch exception, and traced the bug via Crashlytics. The bug occurs on this line.
JsonArray jArray = parser.parse(jsonString).getAsJsonArray();
which says :
Fatal Exception: java.lang.IllegalStateException: This is not a JSON
Array.
Which I believes also occurs when the response is empty, and since I can't also trace a request in server, I believe this is because No request is being sent.(Correct me if wrong).
So, my question is : Am I missing something | or is there anything wrong in the way I defined AsyncTask?
EDIT 1
PS: I am using an HTTPS URL in this AsyncTask
In Crashalitics you can log debug messages and stack traces from exceptions that were caught. So the answer for you is to proper collect this information, and then the issue will be clear
// catch everythin n log everything
} catch (ClientProtocolException e) {
Crashlytics.logException(e);
} catch (IOException e) {
Crashlytics.logException(e);
}
also put log messages before the possible crash
Crashlytics.log("Here is the async task that keeps giving me headache");

How to read HttpResponse in Android?

I am trying to upload a audio file to my webserver. But don't know how to read the the response. Here is the very simplified test.php:
<?php
echo 'I want to see this in the Toast';
?>
fff And here is my onClick that must send the file to the webserver and get a response:
public void send(View v){
Uri uri = new Uri.Builder().scheme("http").authority("sub.domain.nl").path("test.php")
.appendQueryParameter("action", "sendMessage")
.appendQueryParameter("idto", "18")
.appendQueryParameter("idfrom", "36")
.appendQueryParameter("type", "audio")
.build();
String urlString = uri.toString();
new SendAudioTask().execute(urlString);
}
private class SendAudioTask extends AsyncTask<String, Integer, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
String url = params[0];
File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath(),
"/audio.3gpp");
HttpResponse response = null;
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
InputStreamEntity reqEntity = new InputStreamEntity(
new FileInputStream(file), -1);
reqEntity.setContentType("binary/octet-stream");
reqEntity.setChunked(true);
httppost.setEntity(reqEntity);
response = httpclient.execute(httppost);
} catch (Exception e) {
publishProgress(1);
}
return response.toString();
}
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
Toast.makeText(MainActivity.this, "Dev message: = " + values[0], Toast.LENGTH_SHORT).show();
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Toast.makeText(MainActivity.this, result, Toast.LENGTH_SHORT).show();
}
}
Result.toString() in the onPostExecute() is
org.apache.http.message.basicHttpRespons#43b4cc68
If toString() is the right way to read the response. What is wrong with my code? My code doesn't execute the publishProgress.
HttpEntity entity = httpResponse.getEntity();
InputStream is = entity.getContent();
String result = convertStreamToString(is);
private static String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append((line + "\n"));
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
change
return response.toString();
to
return EntityUtils.toString(response.getEntity());
So what getEntity() does,
getEntity()
Obtains the message entity of this response, if any.

Why doesn't the function get data from php in android?

I want to get response after post data but it fails. I want to create a login system, I have successfully submited data to php file, everything is working fine now I want to get response from same function but I'm unable to know where the issue is.
Here is the Java function:
public class PostDataGetRes extends AsyncTask<String, String, String> {
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... strings) {
try {
postRData();
} catch (NullPointerException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String lenghtOfFile) {
// do stuff after posting data
}
}
public void postRData() {
String result = "";
InputStream isr = null;
final String email = editEmail.getText().toString();
final String pass = editPass.getText().toString();
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://website.com/appservice.php");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("id", email));
nameValuePairs.add(new BasicNameValuePair("stringdata", pass));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
resultView.setText("Inserted");
HttpEntity entity = response.getEntity();
isr = entity.getContent();
//convert response to string
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(isr,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
isr.close();
result=sb.toString();
}
catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}
//parse json data
try {
String s = "";
JSONArray jArray = new JSONArray(result);
for(int i=0; i<jArray.length();i++){
JSONObject json = jArray.getJSONObject(i);
s = s +
"Name : "+json.getString("first_name")+"\n\n";
//"User ID : "+json.getInt("user_id")+"\n"+
//"Name : "+json.getString("first_name")+"\n"+
//"Email : "+json.getString("email")+"\n\n";
}
resultView.setText(s);
} catch (Exception e) {
// TODO: handle exception
Log.e("log_tag", "Error Parsing Data "+e.toString());
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
resultView.setText("Done");
}
And here is php code:
if($id){
$query = mysql_query("SELECT first_name FROM users where email = '$id' ");
while($row=mysql_fetch_assoc($query)){
$selectedData[]=$row;
}
print(json_encode($selectedData));
}
Please help me I have tried so far but could not achieve any results. Please help me how can I get response from php file after query execution.
At first be sure you get correct JSON object from your website - try printing it as Toast.makeText(). As far the web browsers keep the html comments away, android gets it in response.
AsyncTask objects and classes aren't designed to be made the way u provided and also you can't make any UI operations in doInBackground(). AsyncTask is made in a way to not to block GUI.
Here is a not much different example how it uses methods you have in AsyncTask class:
class Logging extends AsyncTask<String,String,Void>{
JSONObject json=null;
String output="";
String log=StringCheck.buildSpaces(login.getText().toString());
String pas=StringCheck.buildSpaces(password.getText().toString());
String url="http://www.mastah.esy.es/webservice/login.php?login="+log+"&pass="+pas;
protected void onPreExecute() {
Toast.makeText(getApplicationContext(), "Operation pending, please wait", Toast.LENGTH_SHORT).show();
}
#Override
protected Void doInBackground(String... params) {
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(url);
request.addHeader("User-Agent", "User-Agent");
HttpResponse response;
try {
response = client.execute(request);
BufferedReader br = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String line="";
StringBuilder result = new StringBuilder();
while ((line = br.readLine()) != null) {
result.append(line);
}
output=result.toString();
} catch (ClientProtocolException e) {
Toast.makeText(getApplicationContext(), "Connection problems", Toast.LENGTH_LONG).show();
} catch (IOException e) {
Toast.makeText(getApplicationContext(), "Conversion problems", Toast.LENGTH_LONG).show();
}
return null;
}
#Override
protected void onPostExecute(Void w) {
try {
json = new JSONObject(output);
if(json.getInt("err")==1){
Toast.makeText(getApplicationContext(), json.getString("msg"), Toast.LENGTH_LONG).show();
}else{
String id_user="-1";
Toast.makeText(getApplicationContext(), json.getString("msg"), Toast.LENGTH_LONG).show();
JSONArray arr = json.getJSONArray("data");
for(int i =0;i<arr.length();i++){
JSONObject o = arr.getJSONObject(i);
id_user = o.getString("id_user");
}
User.getInstance().setName(log);
User.getInstance().setId(Integer.valueOf(id_user));
Intent i = new Intent(getApplicationContext(),Discover.class);
startActivity(i);
}
} catch (JSONException e) {
}
super.onPostExecute(w);
}
}
PHP file content:
$data = array(
'err' => 0,
'msg' => "",
'data' => array(),
);
$mysqli = new MySQLi($dbhost,$dbuser,$dbpass,$dbname);
if($mysqli->connect_errno){
$data['err'] = 1;
$data['msg'] = "Brak polaczenia z baza";
exit(json_encode($data));
}
if(isset($_GET['login']) && isset($_GET['pass'])){
$mysqli->query("SET CHARACTER SET 'utf8';");
$query = $mysqli->query("SELECT banned.id_user FROM banned JOIN user ON user.id_user = banned.id_user WHERE user.login ='{$_GET['login']}' LIMIT 1;");
if($query->num_rows){
$data['err']=1;
$data['msg']="User banned";
exit(json_encode($data));
}else{
$query = $mysqli->query("SELECT login FROM user WHERE login='{$_GET['login']}' LIMIT 1;");
if($query->num_rows){
$query = $mysqli->query("SELECT pass FROM user WHERE pass ='{$_GET['pass']}' LIMIT 1;");
if($query->num_rows){
$data['msg']="Logged IN!";
$query = $mysqli->query("SELECT id_user FROM user WHERE login='{$_GET['login']}' LIMIT 1;");
$data['data'][]=$query->fetch_assoc();
exit(json_encode($data));
}else{
$data['err']=1;
$data['msg']="Wrong login credentials.";
exit(json_encode($data));
}
}else{
$data['err']=1;
$data['msg']="This login doesn't exist.";
exit(json_encode($data));
}
}
}else{
$data['err']=1;
$data['msg']="Wrong login credentials";
exit(json_encode($data));
}
I have created there small dictionary $data for my app. I used its err key as a flag to know if any error appeared, msg to inform user about operation results and data to send JSON objects.
Thing you would want to do with if(response == true) if it had exist is similar to construction i used in my onPostExecute(Void w) method in AsyncTask:
if(json.getInt("err")==1){
//something went wrong
}else{
//everything is okay, get JSON, inform user, start new Activity
}
Also here is the way I used $data['data'] to get JSON response:
if($query->num_rows){
while($res=$query->fetch_assoc()){
$data['data'][]=$res;
}
exit(json_encode($data));
}

Parse Simple Json response

Am trying to parse this Json response. For some weird reason its not working. Please bear with me . I really suck at Json.
Here is the Url am trying to parse:
This is the code am using to parse it:
public class AsyncTaskParseJson extends AsyncTask<String, String, String> {
final String TAG = "AsyncTaskParseJson.java";
// set your json string url here
#Override
protected void onPreExecute() {
Toast.makeText(getActivity(), "started", Toast.LENGTH_SHORT).show();
}
#Override
protected String doInBackground(String... arg0) {
String str = "";
HttpResponse response;
HttpClient myClient = new DefaultHttpClient();
HttpPost myConnection = new HttpPost("http://gdata.youtube.com/feeds/api/videos/iS1g8G_njx8?v=2&alt=jsonc");
try {
response = myClient.execute(myConnection);
str = EntityUtils.toString(response.getEntity(), "UTF-8");
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try{
JSONObject myJson = new JSONObject(str);
String grande = myJson.getString("title");
Toast.makeText(getActivity(), ""+grande, Toast.LENGTH_SHORT).show();
} catch ( JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String strFromDoInBg) {
Toast.makeText(getActivity(), "done", Toast.LENGTH_SHORT).show();
}
}
i just need to parse the Title and descrption only. thanks
Its seems you have not parsed properly
Change your try block with the following code
try{
JSONObject myJson = new JSONObject(str);
JSONObject entityObject = myJson.getJSONObject("entity");
// Parsing title
JSONOBject titleObject = entityObject.getJSONObject("title");
String grande = titleObject.getString("$t");
// Do the same for Description as well (Like above two line)
Toast.makeText(getActivity(), ""+grande, Toast.LENGTH_SHORT).show();
} catch ( JSONException e) {
e.printStackTrace();
}
I think that toast message of yours (in doInBackground) is posing problems, try commenting it out and then check!
Moreover, best practice is to send the response to onPostExecute as an argument and then parse the Json in onPostExecute
try like this,
#Override
protected String doInBackground(String... arg0) {
String str = "";
HttpResponse response;
HttpClient myClient = new DefaultHttpClient();
HttpPost myConnection = new HttpPost("http://gdata.youtube.com/feeds/api/videos/iS1g8G_njx8?v=2&alt=jsonc");
try {
response = myClient.execute(myConnection);
str = EntityUtils.toString(response.getEntity(), "UTF-8");
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
#Override
protected void onPostExecute(String result) {
try{
JSONObject myJson = new JSONObject(result);
JSONObject entry = results.getJSONObject("entry");
JSONObject grande = results.getJSONObject("title");
String title = grande.getString("$t");
Toast.makeText(getActivity(), title, Toast.LENGTH_SHORT).show();
} catch ( JSONException e) {
e.printStackTrace();
}
Toast.makeText(getActivity(), "done", Toast.LENGTH_SHORT).show();
}

Categories

Resources