Android Volley JSON parse - java

I am trying to fetch data from server and to display it in a ListView, but it is not working here, I am using the Volley library. I am looking for the Volley code but I couldn't get it, so can I get the code corresponding to this?
JSONParse.java:
import android.util.Log;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.client.HttpClient;
import org.json.JSONException;
public class JSONParse {
static InputStream iStream=null;
static JSONArray jarray=null;
static String json="";
public JSONParse(){
}
public JSONArray getJSONFromUrl(String url){
StringBuilder builder=new StringBuilder();
HttpClient client=new DefaultHttpClient();
//------------J.G-----------------
/*HttpClient client=new DefaultHttpClient();
HttpGet httpGet=new HttpGet(url);
httpGet.setHeader("Content-Type", "application/json");
httpGet.setHeader("jwttoken", "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJFUk0iLCJpc3MiOiJFUk0iLCJpYXQiOjE0MzM2OTczMjd9.2zd4OlKjW3Yfcd_q2FOoyEGpNrFbf7EuHeIkZ8ponr0");*/
try {
HttpGet httpGet=new HttpGet(url);
httpGet.setHeader("Content-Type", "application/json");
httpGet.setHeader("jwttoken", "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJFUk0iLCJpc3MiOiJFUk0iLCJpYXQiOjE0MzM2OTczMjd9.2 zd4OlKjW3Yfcd_q2FOoyEGpNrFbf7EuHeIkZ8ponr0");
HttpResponse response = client.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
} else {
Log.e("==>", "Failed to download file");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
jarray= new JSONArray(builder.toString());
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data"+ e.toString());
}
return jarray;
}
}

implement your code like this:
public void getData(){
//Showing a progress dialog
final ProgressDialog loading = ProgressDialog.show(this,"Loading Data", "Please wait...",false,false);
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest
(Request.Method.POST, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
loading.dismiss();
parseData(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// TODO Auto-generated method stub
Log.d("Json Error:",error.toString());
}
});
//Creating request queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
//Adding request to the queue
requestQueue.add(jsonObjectRequest);
}
public void parseData(JSONObject object){
try {
JSONArray jsonArray=object.getJSONArray("worldpopulation");
Log.d("Json Array:", jsonArray.toString());
for (int i=0;i<jsonArray.length();i++){
Data data=new Data();
JSONObject obj;
try {
obj=jsonArray.getJSONObject(i);
data.setImageUrl(obj.getString("flag"));
data.setName(obj.getString("country"));
data.setRank(obj.getString("rank"));
data.setPopulation(obj.getString("population"));
items.add(data);
}
catch (JSONException e){
Log.d("Error in Parse Object:", e.toString());
}
}
} catch (JSONException e) {
Log.d("Error in parse Array:", e.toString());
}
mAdapter = new MyAdapter(items,this);
mRecyclerView.setAdapter(mAdapter);
}
and for more follow this Tutorial

Not sure if this is what you want: JsonRequest.java.
And here's how I use Volley to parse Json data.
Say an url represents the Json data below:
[
{
"name" : "Ravi Tamada",
"email" : "ravi8x#gmail.com",
"phone" : {
"home" : "08947 000000",
"mobile" : "9999999999"
}
},
{
"name" : "Tommy",
"email" : "tommy#gmail.com",
"phone" : {
"home" : "08946 000000",
"mobile" : "0000000000"
}
}
]
The parse code is below:
JsonArrayRequest req = new JsonArrayRequest(urlJsonArry,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
try {
// Parsing json array response
// loop through each json object
jsonResponse = "";
for (int i = 0; i < response.length(); i++) {
JSONObject person = (JSONObject) response
.get(i);
String name = person.getString("name");
String email = person.getString("email");
JSONObject phone = person
.getJSONObject("phone");
String home = phone.getString("home");
String mobile = phone.getString("mobile");
jsonResponse += "Name: " + name + "\n\n";
jsonResponse += "Email: " + email + "\n\n";
jsonResponse += "Home: " + home + "\n\n";
jsonResponse += "Mobile: " + mobile + "\n\n\n";
}
txtResponse.setText(jsonResponse);
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),
"Error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
hidepDialog();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_SHORT).show();
hidepDialog();
}
});
// Adding request to request queue, please substitute here with your own queue
VolleyQueue.add(req);
For more reference see this link.

Related

json parsing error in android java

hi i'm trying to get element of this url, but every time an error occured
this url get you a json but i couldn't parse it
i try
private class Geturl extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall("https://www.instagram.com/"+username+"/?__a=1".trim());
//Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
//user is correct or i use wrong
//check url and parse it with online json parser
JSONArray contacts = jsonObj.getJSONArray("user");
JSONObject c = contacts.getJSONObject(0);
//profile_pic_url_hd is node or not ?
img_url=c.getString("profile_pic_url_hd");
} catch (final JSONException e) {
//Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG)
.show();
}
});
}
} else {
//Log.e(TAG, "Couldn't get json from server.");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Couldn't get json from server. Check LogCat for possible errors!",
Toast.LENGTH_LONG)
.show();
}
});
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
}
}
parsed Json in picture
no error occur in http handler just in getting elements error happened
httphandler class
import android.util.Log;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
/**
* Created by jefferson on 3/24/2017.
*/
public class HttpHandler {
private static final String TAG = HttpHandler.class.getSimpleName();
public HttpHandler() {
}
public String makeServiceCall(String reqUrl) {
String response = null;
try {
URL url = new URL(reqUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
// read the response
InputStream in = new BufferedInputStream(conn.getInputStream());
response = convertStreamToString(in);
} catch (MalformedURLException e) {
Log.e(TAG, "MalformedURLException: " + e.getMessage());
} catch (ProtocolException e) {
Log.e(TAG, "ProtocolException: " + e.getMessage());
} catch (IOException e) {
Log.e(TAG, "IOException: " + e.getMessage());
} catch (Exception e) {
Log.e(TAG, "Exception: " + e.getMessage());
}
return response;
}
private String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line;
try {
while ((line = reader.readLine()) != null) {
sb.append(line).append('\n');
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
}
thanks if anyone could tell me i get correct elements or not
thanks in advance.
JSONObject contacts = jsonObj.getJSONObject("user");
img_url=c.getString("profile_pic_url_hd");
The user object is not an array.

ANDROID - how to display JSONArray into textview

I've set up a php script to create json here, but when i try to display the JSONArray i got some error like this on my Android Monitor..
Value (html)(body)(script of type java.lang.String cannot be converted to JSONArray
can someone tell me how to fix it?
MainActivity.java
package flix.yudi.okhttp1;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
public class MainActivity extends AppCompatActivity {
private String TAG = MainActivity.class.getSimpleName();
private ProgressDialog pDialog;
private ListView lv;
// URL to get contacts JSON
private static String url = "http://zxccvvv.cuccfree.com/send_data.php";
ArrayList<HashMap<String, String>> contactList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
contactList = new ArrayList<>();
lv = (ListView) findViewById(R.id.list);
new GetContacts().execute();
}
/**
* Async task class to get json by making HTTP call
*/
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
JSONArray jsonObj = new JSONArray(jsonStr);
// Getting JSON Array node
JSONArray pertanyaan = jsonObj.getJSONArray("pertanyaan");
// looping through All Contacts
for (int i = 0; i < pertanyaan.length(); i++) {
JSONObject c = pertanyaan.getJSONObject(i);
String id = c.getString("id");
String ask = c.getString("ask");
// tmp hash map for single contact
HashMap<String, String> pertanyaans = new HashMap<>();
// adding each child node to HashMap key => value
pertanyaans.put("id", id);
pertanyaans.put("ask", ask);
// adding contact to contact list
contactList.add(pertanyaans);
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG)
.show();
}
});
}
} else {
Log.e(TAG, "Couldn't get json from server.");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Couldn't get json from server. Check LogCat for possible errors!",
Toast.LENGTH_LONG)
.show();
}
});
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
MainActivity.this, contactList,
R.layout.list_item, new String[]{"ask"}, new int[]{R.id.ask});
lv.setAdapter(adapter);
}
}
}
HttpHandler.java
package flix.yudi.okhttp1;
import android.util.Log;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
public class HttpHandler {
private static final String TAG = HttpHandler.class.getSimpleName();
public HttpHandler() {
}
public String makeServiceCall(String reqUrl) {
String response = null;
try {
URL url = new URL(reqUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
// read the response
InputStream in = new BufferedInputStream(conn.getInputStream());
response = convertStreamToString(in);
} catch (MalformedURLException e) {
Log.e(TAG, "MalformedURLException: " + e.getMessage());
} catch (ProtocolException e) {
Log.e(TAG, "ProtocolException: " + e.getMessage());
} catch (IOException e) {
Log.e(TAG, "IOException: " + e.getMessage());
} catch (Exception e) {
Log.e(TAG, "Exception: " + e.getMessage());
}
return response;
}
private String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line;
try {
while ((line = reader.readLine()) != null) {
sb.append(line).append('\n');
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
}
I got the reference code from here
any idea/ another reference method to solve?
EDIT
send_data.php
<?php
include 'dbconfig.php';
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, ask FROM pertanyaan";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row[] = $result->fetch_assoc()) {
$json = json_encode($row);
}
} else {
echo "0 results";
}
mysql_close($dbname);
echo $json;
?>
you are trying to get a jsonarray from jsonObj with key pertanyaan which in-fact is a string value so just traverse through array while fetching the json object using indexes
JSONArray jsonObj = new JSONArray(jsonStr);
// Getting JSON Array node
//JSONArray pertanyaan = jsonObj.getJSONArray("pertanyaan"); problem
// looping through All Contacts
for (int i = 0; i < jsonObj.length(); i++) {
JSONObject c = jsonObj.getJSONObject(i);
String id = c.getString("id");
String ask = c.getString("ask");
HashMap<String, String> pertanyaans = new HashMap<>();
pertanyaans.put("id", id);
pertanyaans.put("ask", ask);
contactList.add(pertanyaans);
}
Note : There is no such jasonarray with key pertanyaan in your response
PHP update : Use
echo json_encode($json);
According to your service, while Response received you will get JSONArray like this [{"id":"1","ask":"pertanyaan ke 1"},{"id":"2","ask":"pertanyaan ke 2"},{"id":"3","ask":"pertanyaan ke 3"},{"id":"4","ask":"pertanyaan ke 4"},{"id":"5","ask":"pertanyaan ke 5"}]
you just need to store this response in JSONArray
JSONArray jsonArray = new JSONArray();
jsonArray = (response);
now you have respons in your jsonArray so you can opt out value from it.
here is the sample code snippet
for (int i = 0; i < jsonArray.length(); i++) {
try {
String id = jsonArray.getJSONObject(i).getString("id");
String ask = jsonArray.getJSONObject(i).getString("ask");
Log.i("TAG", "id "+ id + " ask "+ ask);
//you can set value to text view here
textview.settext(id + " "+ ask);
} catch (JSONException e) {
e.printStackTrace();
}
}

Android misfit API OAuth 2 : How to save access token

With the following android code, i manage to do this:
Display authentification page, on my Android smartphone, to my user
Login, as a valid user, through this page with my credentials
Catch the Auth code
See, on my smarthpone webview, the access_token
public class MainActivity extends AppCompatActivity
{
public static String OAUTH_URL = "https://api.misfitwearables.com/auth/dialog/authorize";
public static String OAUTH_ACCESS_TOKEN_URL = "https://api.misfitwearables.com/auth/tokens/exchange";
public static String CLIENT_ID = "my id";
public static String CLIENT_SECRET = "my secret code";
public static String CALLBACK_URL = "just a simple url";
public static String SCOPE = "public,birthday,email,tracking,session,sleep";
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.other);
String url = OAUTH_URL+ "?response_type=code" +"&client_id=" + CLIENT_ID+ "&redirect_uri=" + CALLBACK_URL + "&scope=" + SCOPE;
WebView webview = (WebView) findViewById(R.id.aaa);
webview.getSettings().setJavaScriptEnabled(true);
webview.setWebViewClient(new WebViewClient() {
public void onPageStarted(WebView view, String url, Bitmap favicon) {
String accessTokenFragment = "access_token=";
String accessCodeFragment = "code=";
if (url.contains(accessCodeFragment))
{
String accessCode = url.substring(url.indexOf(accessCodeFragment));
String query = "grant_type=authorization_code" + "&client_id=" + CLIENT_ID + "&client_secret=" + CLIENT_SECRET + "&" + accessCode + "&redirect_uri=" + CALLBACK_URL;
view.postUrl(OAUTH_ACCESS_TOKEN_URL, query.getBytes());
System.out.println("url:" + url);
System.out.println(accessCode);
}
System.out.println(url);
if (url.contains(accessTokenFragment)) {
String accessToken = url.substring(url.indexOf(accessTokenFragment));
url = url.replace("#", "?");
//view.loadUrl(url);
System.out.println("token=" + accessToken);
}
}
});
webview.loadUrl(url);
}
}
Like I said above, I manage to display the access_token on my webview, on my smarthpone. But I am not able to catch this token, to make get request in order to recover user's data.
I am novice in java/android, but I have some skills in C.
I just took the time to discover Java, so my skills in this area are limited.
Is that someone could advise me?
I have found some piece of code, and made an Android App that works well.
Main
package com.example.vta.webview_example;
/*
* Note that I was a complete novice in Java and Android when I was writting this.
* Note that I found pieces of code that I adapted for my needs.
*/
import org.apache.http.HttpStatus;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.Context;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.os.StrictMode;
import android.util.Log;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Calendar;
public class MainActivity extends Activity
{
private static String CLIENT_ID = "your ID_CLIENT code";
private static String CLIENT_SECRET ="your SECRET_CLIENT code";
private static String REDIRECT_URI="http://localhost";
private static String GRANT_TYPE="authorization_code";
private static String TOKEN_URL ="https://api.misfitwearables.com/auth/tokens/exchange";
private static String OAUTH_URL ="https://api.misfitwearables.com/auth/dialog/authorize";
private static String OAUTH_SCOPE="public,birthday,email,tracking,session,sleep";
WebView web;
Button auth;
SharedPreferences pref;
TextView Access;
#Override
protected void onCreate(Bundle savedInstanceState)
{
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pref = getSharedPreferences("AppPref", MODE_PRIVATE);
Access =(TextView)findViewById(R.id.Access);
auth = (Button)findViewById(R.id.auth);
auth.setOnClickListener(new View.OnClickListener()
{
Dialog auth_dialog;
#Override
public void onClick(View arg0)
{
auth_dialog = new Dialog(MainActivity.this);
auth_dialog.setContentView(R.layout.auth_dialog);
web = (WebView)auth_dialog.findViewById(R.id.webv);
web.getSettings().setJavaScriptEnabled(true);
web.loadUrl(OAUTH_URL+"?redirect_uri="+REDIRECT_URI+"&response_type=code&client_id="+CLIENT_ID+"&scope="+OAUTH_SCOPE);
web.setWebViewClient(new WebViewClient()
{
boolean authComplete = false;
Intent resultIntent = new Intent();
String authCode;
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon)
{
super.onPageStarted(view, url, favicon);
}
#Override
public void onPageFinished(WebView view, String url)
{
super.onPageFinished(view, url);
if (url.contains("?code=") && authComplete != true)
{
Uri uri = Uri.parse(url); //Create an uri, identical to the url
System.out.println("=====> uri <===== \n" + uri);
authCode = uri.getQueryParameter("code"); //Parse the uri to fond the first occurence of "code", and extract his value
Log.i("", "CODE : " + authCode);
System.out.println("=====> code <===== \n" + authCode);
authComplete = true;
resultIntent.putExtra("code", authCode);
MainActivity.this.setResult(Activity.RESULT_OK, resultIntent);
setResult(Activity.RESULT_CANCELED, resultIntent);
SharedPreferences.Editor edit = pref.edit();
edit.putString("Code", authCode);
edit.commit();
auth_dialog.dismiss();
new TokenGet().execute();
Toast.makeText(getApplicationContext(),"Authorization Code is: " +authCode, Toast.LENGTH_SHORT).show();
}
else if(url.contains("error=access_denied"))
{
Log.i("", "ACCESS_DENIED_HERE");
resultIntent.putExtra("code", authCode);
authComplete = true;
setResult(Activity.RESULT_CANCELED, resultIntent);
Toast.makeText(getApplicationContext(), "Error Occured", Toast.LENGTH_SHORT).show();
auth_dialog.dismiss();
}
}
});
auth_dialog.show();
auth_dialog.setTitle("Authorize Misfit");
auth_dialog.setCancelable(true);
}
});
}
private class TokenGet extends AsyncTask<String, String, JSONObject>
{
private ProgressDialog pDialog;
String Code;
#Override
protected void onPreExecute()
{
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Contacting Misfit ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
Code = pref.getString("Code", "");
pDialog.show();
}
#Override
protected JSONObject doInBackground(String... args)
{
GetAccessToken jParser = new GetAccessToken();
JSONObject json = jParser.gettoken(TOKEN_URL,Code,CLIENT_ID,CLIENT_SECRET,REDIRECT_URI,GRANT_TYPE);
System.out.println("=====> json <===== \n" + json);
return json;
}
#Override
protected void onPostExecute(JSONObject json)
{
pDialog.dismiss();
if (json != null)
{
try
{
final String tok = json.getString("access_token");
Log.d("Token Access", tok);
System.out.println("TOKN = " + tok);
auth.setText("Authenticated");
Access.setText("Access Token:" + tok);
}
catch (JSONException e)
{
e.printStackTrace();
}
getRequestToMisfit(json);
}
else
{
Toast.makeText(getApplicationContext(), "Network Error", Toast.LENGTH_SHORT).show();
pDialog.dismiss();
}
}
}
public void getRequestToMisfit(JSONObject json)
{
try
{
URL url;
HttpURLConnection connection;
String tok;
InputStream is;
BufferedReader rd;
String line;
String responseStr;
StringBuffer response;
String end_date;
String today;
String start_date;
Context context;
File file;
File file_value;
String filepath;
String filepath_value;
String result;
result = null;
context = MyApp.getContext();
connection = null;
rd = null;
tok = json.getString("access_token");
FileManagement fm = new FileManagement();
Calendar c = Calendar.getInstance();
String d = String.valueOf(c.get(Calendar.DAY_OF_MONTH));
String m = String.valueOf((c.get(Calendar.MONTH) + 1));
String y = String.valueOf(c.get(Calendar.YEAR));
today = y + "-" + m + "-" + d;
end_date = new String(today);
filepath = context.getFilesDir().getPath().toString() + "/sync_date.txt";
filepath_value = context.getFilesDir().getPath().toString() + "/sync_value.txt";
file = new File(filepath);
file_value = new File(filepath_value);
//IF YOU WANT TO SIMULATE AN OLD SYNC
//fm.writeToFile("2016-03-28", filepath);
//If you want to delete file that contain previous synchronisation date
//fm.deleteFile(file);
if ((start_date = fm.readFromFile(filepath, file)) == null)
start_date = new String(today);
//String dataUrl = "https://api.misfitwearables.com/move/resource/v1/user/me/profile?access_token=" + tok;
String dataUrl = "https://api.misfitwearables.com/move/resource/v1/user/me/activity/summary?start_date="+start_date+"&end_date="+end_date+"&access_token=" + tok;
System.out.println("=====> access_token <===== \n" + tok);
try
{
// Create connection
url = new URL(dataUrl);
setContentView(R.layout.activity_main);
TextView wv = (TextView) findViewById(R.id.misfit);
System.out.println("=====> url <===== \n" + url);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setDoInput(true);
//if setDoOutput is set to "true", HttpUrlConnection will send POST request.
connection.setDoOutput(false);
// Send request
int status = connection.getResponseCode();
// Get Response
if(status >= HttpStatus.SC_BAD_REQUEST)
is = connection.getErrorStream();
else
is = connection.getInputStream();
rd = new BufferedReader(new InputStreamReader(is));
response = new StringBuffer();
while ((line = rd.readLine()) != null)
{
System.out.println("line = " + line);
response.append(line);
response.append('\r');
}
rd.close();
responseStr = response.toString();
JSONObject json_res = new JSONObject(responseStr);
System.out.println("JSON_OBJ" + json_res);
result = json_res.getString("points");
Log.d("Server response", responseStr);
System.out.println(responseStr);
System.out.println(start_date);
System.out.println(end_date);
System.out.println(result);
wv.setText("nombre de point :\ndu " + start_date + " au " + end_date + "\n" + "*** " + result + " ***");
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
if (connection != null)
connection.disconnect();
if (rd != null)
{
try
{
rd.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
if (!file.exists())
{
try
{
file.createNewFile();
file.mkdir();
}
catch (IOException e)
{
e.printStackTrace();
}
}
fm.writeToFile(today, filepath);
if (!file_value.exists())
{
try
{
file_value.createNewFile();
file_value.mkdir();
}
catch (IOException e)
{
e.printStackTrace();
}
}
fm.writeToFile(result, filepath_value);
System.out.println(fm.readFromFile(filepath_value, file));
Toast.makeText(context, "Result added to file ==> OK", Toast.LENGTH_LONG);
}
catch (JSONException e)
{
e.printStackTrace();
}
}
}
GetAccessToken
package com.example.vta.webview_example;
/*
* Find on
* http://stackoverflow.com/questions/22499066/invalid-client-in-jsonresponse-in-oauth2-android
*/
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class GetAccessToken
{
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
List<NameValuePair> params = new ArrayList<NameValuePair>();
Map<String, String> mapn;
DefaultHttpClient httpClient;
HttpPost httpPost;
public GetAccessToken()
{
}
public JSONObject gettoken(String address,String token,String client_id,String client_secret,String redirect_uri,String grant_type)
{
// Making HTTP request
try
{
// DefaultHttpClient
httpClient = new DefaultHttpClient();
httpPost = new HttpPost(address);
params.add(new BasicNameValuePair("code", token));
params.add(new BasicNameValuePair("client_id", client_id));
params.add(new BasicNameValuePair("client_secret", client_secret));
params.add(new BasicNameValuePair("redirect_uri", redirect_uri));
params.add(new BasicNameValuePair("grant_type", grant_type));
httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
catch (UnsupportedEncodingException e)
{
e.printStackTrace();
}
catch (ClientProtocolException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
try
{
BufferedReader reader;
StringBuilder sb;
String line;
reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
sb = new StringBuilder();
line = null;
while ((line = reader.readLine()) != null)
{
System.out.println("=+=+=+> getAccessToken : line <+=+=+= \n" + line);
sb.append(line + "\n");
}
is.close();
json = sb.toString();
System.out.println("=+=+=+> getAccessToken : json <+=+=+= \n" + json);
Log.e("JSONStr", json);
}
catch (Exception e)
{
e.getMessage();
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// Parse the String to a JSON Object
try
{
jObj = new JSONObject(json);
}
catch (JSONException e)
{
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// Return JSON String
return jObj;
}
}
The entire project :
https://github.com/v3t3a/android/tree/master/marvin_project/webview_example/app/src/main/java/com/example/vta/webview_example

Sending json Post date in android with parameter

I'm trying to make a POST request with Android, but I'm not succeeding. I think the problem is in how to set the parameters for resquisição and Header. Below is my method I do the request ...
public void testPostDate() {
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000);
HttpResponse response;
Gson gson = new Gson();
CrimePOST.Crime crime = new CrimePOST().new Crime(10, "São Paulo",
"descrição", 10.00, 30.00);
CrimePOST crimePost = new CrimePOST();
crimePost.setCrime(crime);
List<NameValuePair> params = new LinkedList<NameValuePair>();
params.add(new BasicNameValuePair("token",
"0V1AYFK12SeCZHYgXbNMew==$tRqPNplipDwtbD0vxWv6GPJIT6Yk5abwca3IJa6JhMs="));
String json = gson.toJson(crimePost);
String paramString = URLEncodedUtils.format(params, Utils.ENCODE);
try {
HttpPost post = new HttpPost(
"http://safe-sea-4024.herokuapp.com/crimes/mobilecreate"
+ "?" + paramString);
post.setHeader("Content-Type", "application/json");
StringEntity entitty = new StringEntity(json);
entitty.setContentType(new BasicHeader(HTTP.CONTENT_TYPE,
"application/json"));
post.setEntity(entitty);
response = client.execute(post);
/* Checking response */
if (response != null) {
InputStream in = response.getEntity().getContent();
String a = toString(in);
System.out.println(a);
}
} catch (Exception e) {
e.printStackTrace();
}
}
This method is responsible for converting an inputStream to String
private String toString(InputStream is) throws IOException {
byte[] bytes = new byte[1024];
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int lidos;
while ((lidos = is.read(bytes)) > 0) {
baos.write(bytes, 0, lidos);
}
return new String(baos.toByteArray());
}
Really I am passing the Header correctly?
You have to do this in an AsyncTask
I wrote this tutorial while back. it does send json data via HTTP Post to a url. Check it out. Original post can be found here:http://androidhappenings.blogspot.com/2013/03/android-app-development-201-1st.html
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Timer;
import java.util.TimerTask;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
public class MainActivity extends Activity implements LocationListener{
private TextView textView =null;
LocationManager locationManager=null;
Location location=null;
protected String url;
protected JSONObject jsonData=null;
private EditText urlText=null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
final boolean gpsEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
if(gpsEnabled!=true) {
Toast.makeText(getApplicationContext(), "GPS Disbled! Please Enable to Proceed!", Toast.LENGTH_SHORT).show();
startActivity(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));
}
textView = (TextView)findViewById(R.id.textView);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 1, this);
urlText = (EditText)findViewById(R.id.urlTextbox);
Button submitButton = (Button)findViewById(R.id.submitUrl);
submitButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
if (urlText.getText()!=null) {
url=urlText.getText().toString();
System.out.println(url);//for testing only, not required
Toast.makeText(getApplicationContext(), "Url Submitted, Sending data to Web Service at url: " + url, Toast.LENGTH_SHORT).show();
}
}
});
}
#Override
public void onLocationChanged(final Location location) {
this.location=location;
final Handler handler = new Handler();
Timer ourtimer = new Timer();
TimerTask timerTask = new TimerTask() {
int cnt=1;
public void run() {
handler.post(new Runnable() {
public void run() {
Double latitude = location.getLatitude();
Double longitude = location.getLongitude();
Double altitude = location.getAltitude();
Float accuracy = location.getAccuracy();
textView.setText("Latitude: " + latitude + "\n" + "Longitude: " + longitude+ "\n" + "Altitude: " + altitude + "\n" + "Accuracy: " + accuracy + "meters"+"\n" + "Location Counter: " + cnt);
try {
jsonData = new JSONObject();
jsonData.put("Latitude", latitude);
jsonData.put("Longitude", longitude);
jsonData.put("Altitude", altitude);
jsonData.put("Accuracy", accuracy);
System.out.println(jsonData.toString());//not required, for testing only
if(url!=null) {
new HttpPostHandler().execute();
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
cnt++;
}
});
}};
ourtimer.schedule(timerTask, 0, 120000);
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
public class HttpPostHandler extends AsyncTask<Void,Void,Void> {
#Override
protected Void doInBackground(Void... arg0) {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
StringEntity dataEntity = null;
try {
dataEntity = new StringEntity(jsonData.toString());
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
httpPost.setEntity(dataEntity);
httpPost.setHeader("Content-Type", "application/json");
try {
httpClient.execute(httpPost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
try {
this.finalize();
} catch (Throwable e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}

Android Emulator connecting to Local Web service

Hi all I have a local web service set up on my machine, it is a web service which was built in netbeans using the JPA. I have it connecting locally to a mySQL server also. I have both the database and web service connecting. The webservice can display XML/JSON. My problem is getting the android emulator to consume the JSON from the web service. The URL we are using is "http://10.0.2.2:8080/Web4/resources/hotel2s/" this should allow the emulator to connect to the web service am I correct? When I try to launch and consume the emulator crashes. Here is some source code. We are sure that it should read in and parse with GSON etc but we are not sure if it is connecting or not.
RESULT CLASS
public class hotel_Result
{
#SerializedName("hotelAddress")
protected String hotelAddress;
#SerializedName("HotelDescription")
protected String hotelDescription;
#SerializedName("hotelName")
protected String hotelName;
#SerializedName("hotelRating")
protected int hotelRating;
}
HOTEL RESPONSE CLASS
public class hotel_Response
{
public List<hotel_Result> hotelresults;
public String query;
}
MAIN CLASS
public class connectRest extends Activity
{
// We tried Reg's machines ip here as well and it crashed also used different ips is this correct for the emulator to connect to it?
String url = "http://10.0.2.2:8080/Web4/resources/hotel2s/";
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
InputStream source = retrieveStream(url); // Stream in the URL
Gson gson = new Gson(); // GSON object
Reader reader = new InputStreamReader(source); // Read in the stream
hotel_Response response = gson.fromJson(reader,hotel_Response.class); // Fill in the variables in the class hotel_response
Toast.makeText(this,response.query,Toast.LENGTH_SHORT).show();
List<hotel_Result> hotelresults = response.hotelresults;
for(hotel_Result hotel_Result : hotelresults)
{
Toast.makeText(this,hotel_Result.hotelName,Toast.LENGTH_SHORT).show();
}
}
private InputStream retrieveStream(String url)
{
DefaultHttpClient client = new DefaultHttpClient();
HttpGet getRequest = new HttpGet(url);
try{
HttpResponse getResponse = client.execute(getRequest);
final int statusCode = getResponse.getStatusLine().getStatusCode();
if(statusCode != HttpStatus.SC_OK)
{
Log.w(getClass().getSimpleName(),"Error" + statusCode + " for URL " + url);
return null;
}
HttpEntity getResponseEntity = getResponse.getEntity();
return getResponseEntity.getContent();
}
catch(IOException e)
{
getRequest.abort();
Log.w(getClass().getSimpleName(),"Error for URL " + url, e);
}
return null;
}
}
Make sure you have the allow internet access permission in your manifest.
Here's a better try-catch implementation and it does the work in an AsyncTask() to keep the UI thread happy :) The original article can be found on Java Code Geeks (http://www.javacodegeeks.com/2011/01/android-json-parsing-gson-tutorial.html) but it lacks my improvements!
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import android.app.Activity;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.google.gson.Gson;
import com.javacodegeeks.android.json.model.Result;
import com.javacodegeeks.android.json.model.SearchResponse;
public class JsonParsingActivity extends Activity {
private static final String url = "http://search.twitter.com/search.json?q=javacodegeeks";
protected InitTask _initTask;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button button = (Button)findViewById(R.id.button1);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
_initTask = new InitTask();
_initTask.execute( getApplicationContext() );
}
});
}
#Override
public void onStop() {
super.onStop();
_initTask.cancel(true);
}
protected class InitTask extends AsyncTask<Context, String, SearchResponse>
{
#Override
protected SearchResponse doInBackground( Context... params )
{
InputStream source = retrieveStream(url);
SearchResponse response = null;
if (source != null) {
Gson gson = new Gson();
Reader reader = new InputStreamReader(source);
try {
response = gson.fromJson(reader, SearchResponse.class);
publishProgress( response.query );
reader.close();
} catch (Exception e) {
Log.w(getClass().getSimpleName(), "Error: " + e.getMessage() + " for URL " + url);
}
}
if (!this.isCancelled()) {
return response;
} else {
return null;
}
}
#Override
protected void onProgressUpdate(String... s)
{
super.onProgressUpdate(s);
Toast.makeText(getApplicationContext(), s[0], Toast.LENGTH_SHORT).show();
}
#Override
protected void onPostExecute( SearchResponse response )
{
super.onPostExecute(response);
StringBuilder builder = new StringBuilder();
if (response != null) {
String delim = "* ";
List<Result> results = response.results;
for (Result result : results) {
builder.append(delim).append(result.fromUser);
delim="\n* ";
}
}
if (builder.length() > 0) {
Toast.makeText(getApplicationContext(), builder.toString(), Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "The response was empty.", Toast.LENGTH_SHORT).show();
}
}
#Override
protected void onCancelled() {
super.onCancelled();
Toast.makeText(getApplicationContext(), "The operation was cancelled.", 1).show();
}
private InputStream retrieveStream(String url) {
DefaultHttpClient client = new DefaultHttpClient();
HttpGet getRequest;
try {
getRequest = new HttpGet(url);
HttpResponse getResponse = client.execute(getRequest);
HttpEntity getResponseEntity = getResponse.getEntity();
return getResponseEntity.getContent();
} catch (Exception e) {
Log.w(getClass().getSimpleName(), "Error for URL " + url, e);
return null;
}
}
}
}
Here's a full try-catch implementation of the code above. I implemented this first and then realized all I really needed to know was pass/fail. Anyway, might help someone. Again, props go to Java Code Geeks for getting me started ... Android JSON Parsing with GSON Tutorial
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import android.app.Activity;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.google.gson.Gson;
import com.google.gson.JsonIOException;
import com.google.gson.JsonSyntaxException;
import com.javacodegeeks.android.json.model.Result;
import com.javacodegeeks.android.json.model.SearchResponse;
public class JsonParsingActivity extends Activity {
private static final String url = "http://search.twitter.com/search.json?q=javacodegeeks";
protected InitTask _initTask;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button button = (Button)findViewById(R.id.button1);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
_initTask = new InitTask();
_initTask.execute( getApplicationContext() );
}
});
}
#Override
public void onStop() {
super.onStop();
_initTask.cancel(true);
}
protected class InitTask extends AsyncTask<Context, String, SearchResponse>
{
#Override
protected SearchResponse doInBackground( Context... params )
{
InputStream source = retrieveStream(url);
SearchResponse response = null;
if (source != null) {
Gson gson = new Gson();
Reader reader = new InputStreamReader(source);
try {
response = gson.fromJson(reader, SearchResponse.class);
publishProgress( response.query );
} catch (JsonSyntaxException e) {
Log.w(getClass().getSimpleName(), "Error: " + e.getMessage() + " for URL " + url);
return null;
} catch (JsonIOException e) {
Log.w(getClass().getSimpleName(), "Error: " + e.getMessage() + " for URL " + url);
return null;
} finally {
try {
reader.close();
} catch (IOException e) {
Log.w(getClass().getSimpleName(), "Error: " + e.getMessage() + " for URL " + url);
}
}
}
if (!this.isCancelled()) {
return response;
} else {
return null;
}
}
#Override
protected void onProgressUpdate(String... s)
{
super.onProgressUpdate(s);
Toast.makeText(getApplicationContext(), s[0], Toast.LENGTH_SHORT).show();
}
#Override
protected void onPostExecute( SearchResponse response )
{
super.onPostExecute(response);
StringBuilder builder = new StringBuilder();
if (response != null) {
String delim = "* ";
List<Result> results = response.results;
for (Result result : results) {
builder.append(delim).append(result.fromUser);
delim="\n* ";
}
}
if (builder.length() > 0) {
Toast.makeText(getApplicationContext(), builder.toString(), Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "The response was empty.", Toast.LENGTH_SHORT).show();
}
}
#Override
protected void onCancelled() {
super.onCancelled();
Toast.makeText(getApplicationContext(), "The operation was cancelled.", 1).show();
}
private InputStream retrieveStream(String url) {
DefaultHttpClient client = new DefaultHttpClient();
HttpGet getRequest;
try {
getRequest = new HttpGet(url);
try {
HttpResponse getResponse = client.execute(getRequest);
final int statusCode = getResponse.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
Log.w(getClass().getSimpleName(), "Error " + statusCode + " for URL " + url);
return null;
}
HttpEntity getResponseEntity = getResponse.getEntity();
try {
return getResponseEntity.getContent();
} catch (IllegalStateException e) {
getRequest.abort();
Log.w(getClass().getSimpleName(), "Error for URL " + url, e);
return null;
} catch (IOException e) {
getRequest.abort();
Log.w(getClass().getSimpleName(), "Error for URL " + url, e);
return null;
}
} catch (ClientProtocolException e) {
getRequest.abort();
Log.w(getClass().getSimpleName(), "Error for URL " + url, e);
} catch (IOException e) {
getRequest.abort();
Log.w(getClass().getSimpleName(), "Error for URL " + url, e);
}
} catch (IllegalArgumentException e) {
Log.w(getClass().getSimpleName(), "Error for URL " + url, e);
}
return null;
}
}
}

Categories

Resources