Cannot evaluate com.android.okhttp.HttpUrl$Builder.toString() - android

The following code seems to cause this exception to be thrown:
public static String GET(String url) throws Exception {
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("GET");
if (con.getResponseCode() == HttpURLConnection.HTTP_OK) { <--**Here**
....
}
.....
}
This is the method in the MainActivity that calls this function:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new AsyncTask<Void,Void,List<Client>>(){
#Override
protected void onPostExecute(List<Client> clients) {
super.onPostExecute(clients);
myList=clients;
}
#Override
protected List<Client> doInBackground(Void... voids) {
return getClients();
}
}.execute();
if(myList == null)
Log.v("Tag", "its null");
else
Log.v("Tag", "it works");
}
public List<Client> getClients() {
List<Client> result = new ArrayList<Client>();
try {
String str = PHPtools.GET(WEB_URL + "Client.php");
JSONArray array = new JSONObject(str).getJSONArray("Client");
for (int i = 0; i < array.length(); i++) {
JSONObject jsonObject = array.getJSONObject(i);
Client client = new Client();
client.setLastName(jsonObject.getString("lastName"));
client.setFirstName(jsonObject.getString("firstName"));
client.setId(jsonObject.getInt("_id"));
client.setPhoneNumber(jsonObject.getString("phoneNumber"));
client.setEmail(jsonObject.getString("email"));
client.setCreditCardNumber(jsonObject.getLong("creditCardNumber"));
result.add(client);
}
return result;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
The URL I am passing has been tested and works fine. I tried it on Chrome and the JSON I am trying to parse displays perfectly fine.
but the problem starts when trying to establish connection at the line mentioned above.
I am calling this method from an AsyncTask and also added an Internet permission to the Manifest file.
This is the full error I am receiving:
"Method threw 'java.lang.NullPointerException' exception. Cannot evaluate com.android.okhttp.HttpUrl$Builder.toString()"
Thanks in advance

Related

How to get response from url in json for android and than after reponse i want to parse it

I am trying to fetch data from thingspeak api and I am taking Input for channel id and passing it on URL. But I have to check if the url is responding or not, if it is responding than go ahead with the code else user have to change channel id.
Error I am getting is 'int java.lang.String.length()' on a null object reference
and
W/System.err: java.io.FileNotFoundException: https://api.thingspeak.com/channels/497971/feeds.json?results=1
This is invalid url if I change it to
https://api.thingspeak.com/channels/497970/feeds.json?results=1
This will work
Code I am trying is
public class MainActivity extends AppCompatActivity {
TextView a, b;
String result = "";
String field1,field2,field3;
private int count = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
a = (TextView) findViewById(R.id.a);
b = (TextView) findViewById(R.id.b);
new CountDownTimer(100000, 10000) {
#Override
public void onTick(long l) {
DownloadTask task = new DownloadTask();
task.execute("https://api.thingspeak.com/channels/497970/feeds.json?results=1");
}
#Override
public void onFinish() {
}
}.start();
}
public class DownloadTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
URL url;
result = "";
HttpURLConnection urlConnection = null;
try {
url = new URL(urls[0]);
urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = urlConnection.getInputStream();
InputStreamReader reader = new InputStreamReader(in);
int data = reader.read();
while (data != -1) {
char current = (char) data;
result += current;
data = reader.read();
}
return result;
} catch (MalformedURLException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(final String result) {
super.onPostExecute(result);
search(result);
}
public void search(String result) {
try {
JSONObject jsonObject = new JSONObject(result);
JSONObject fieldinfo = jsonObject.getJSONObject("channel");
String ff1 = fieldinfo.optString("field1","No Value");
String ff2 = fieldinfo.optString("field2","No Value");
JSONArray weatherInfo = jsonObject.getJSONArray("feeds");
JSONObject legsobject = weatherInfo.getJSONObject(0);
field1 = legsobject.getString("field1");
field2 = legsobject.getString("field2");
a.setText(ff1);
c.setText(field1);
} catch (JSONException e1) {
e1.printStackTrace();
}
}
}
}
Here is the Image of error
The issue here is that you are not taking into account that HTTP connections sometimes do fail, like in this case. And it fails because the channel id does not exist.
When you set a correct channel id, the URL is also correct because the resource exists and therefore you get the desired results.
However, when you set a wrong channel id the HTTP request fails (because that URL does not exist). Regardless of this, you are attempting to read the response and that's when it all blows up.
When you make an HTTP request to a server, it responds with a status code indicating what happened with your request. You are completely ignoring this status code.
Look at the headers that a request to that URL throws using:
curl -i https://api.thingspeak.com/channels/497971/feeds.json?results=1:
HTTP/1.1 400 Bad Request
Content-Type: text/html; charset=utf-8
Transfer-Encoding: chunked
Connection: close
Status: 400 Bad Request
... [Shortened] ...
You can learn all about HTTP status codes in a simple Google search but the summary is that it is a number between 100 and 599 that indicates:
Request successfully handled: when it is between 200 and 299.
Request could not be handled, it failed: when it is between 400 and 499.
The request failed because the server basically blew up: (> 500).
In order to retrieve this status code, you need to call the getResponseCode() method of the urlConnection instance.
Only when the status code is successful (between 200 and 299) the call to urlConnection.getInputStream() will succeed. In case of error you need to call urlConnection.getErrorStream().
So in order to fix your code, you need to do something like this:
#Override
protected String doInBackground(String... urls) {
URL url;
result = "";
HttpURLConnection urlConnection = null;
try {
url = new URL(urls[0]);
// Open the conection
urlConnection = (HttpURLConnection) url.openConnection();
// Retrieve status code
int statusCode = urlConnection.getResponseCode();
// Determine whether the request was handled successfully or not
boolean success = (statusCode >= 200) && (statusCode < 300);
InputStream in;
if(success) {
// Read the response when request was handled successfully
in = urlConnection.getInputStream();
} else {
// Read the error stream when the request failed
in = urlConnection.getErrorStream();
}
InputStreamReader reader = new InputStreamReader(in);
int data = reader.read();
while (data != -1) {
char current = (char) data;
result += current;
data = reader.read();
}
return result;
} catch (MalformedURLException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
} finally {
// Close the connection
if(urlConnection != null) {
urlConnection.disconnect();
}
}
return null;
}
First of all, don't forget to close the connection once you are done (I included the disconnection in the finally {} block).
If you debug or log that code, you will see that the status code you are receiving is 400. That is the HTTP status code for Bad Request, indicating that your request is not correct and you need to fix it. If you analyze the content of the result variable, you will see that the value equals to -1.
Therefore in the onPostExecute callback you should make sure the value is different than -1 before attempting to deserialize it, since otherwise it will blow up again.
You can fix your onPostExecute callback like this:
#Override
protected void onPostExecute(final String result) {
super.onPostExecute(result);
if(result.equals(-1)) {
// Do something else, show an error to the user indicating the channel id is wrong
} else {
// Since there is no error, you can proceed with the deserialization of the response
search(result);
}
}
I hope it helps and that it was clear enough.
Cheers!
As you described you need to update your code like
public class MainActivity extends AppCompatActivity {
TextView a, b;
String result = "";
String field1,field2,field3;
private int count = 0;
int channelId=497970;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
a = (TextView) findViewById(R.id.a);
b = (TextView) findViewById(R.id.b);
startCounter(channelId);
}
public void startCounter(int channelId){
new CountDownTimer(100000, 10000) {
#Override
public void onTick(long l) {
DownloadTask task = new DownloadTask();
task.execute("https://api.thingspeak.com/channels/"+channelId+"/feeds.json?results=1");
}
#Override
public void onFinish() {
}
}.start();
}
public class DownloadTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
URL url;
result = "";
HttpURLConnection urlConnection = null;
try {
url = new URL(urls[0]);
urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = urlConnection.getInputStream();
InputStreamReader reader = new InputStreamReader(in);
int data = reader.read();
while (data != -1) {
char current = (char) data;
result += current;
data = reader.read();
}
return result;
} catch (FileNotFoundException e){
startCounter(channelId+1);
}
catch (MalformedURLException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(final String result) {
super.onPostExecute(result);
search(result);
}
public void search(String result) {
try {
JSONObject jsonObject = new JSONObject(result);
JSONObject fieldinfo = jsonObject.getJSONObject("channel");
String ff1 = fieldinfo.optString("field1","No Value");
String ff2 = fieldinfo.optString("field2","No Value");
JSONArray weatherInfo = jsonObject.getJSONArray("feeds");
JSONObject legsobject = weatherInfo.getJSONObject(0);
field1 = legsobject.getString("field1");
field2 = legsobject.getString("field2");
a.setText(ff1);
c.setText(field1);
} catch (JSONException e1) {
e1.printStackTrace();
}
}
}
}

Use of an API toke in my android app

I got an api token for my api but don't know how to implement it in my code...
this is the code i have for reaching my api:
public class DataVoetbalWebservice extends AsyncTask<VoetbalDataInterface, Void, JSONArray> {
private static final int CONNECTION_TIMEOUT = 12000;
private static final int DATARETRIEVAL_TIMEOUT = 12000;
VoetbalDataInterface listener;
private ProgressDialog dialog;
Context context;
public void setActivity(Context context) {
this.context = context;
dialog = new ProgressDialog(context);
}
#Override
protected void onPreExecute() {
dialog.setMessage("De Verschillende competities ophalen, even geduld aub.");
dialog.show();
}
#Override
protected JSONArray doInBackground(VoetbalDataInterface... params) {
listener = params[0];
// execute search
disableConnectionReuseIfNecessary();
HttpURLConnection urlConnection = null;
try {
// create connection
//URL urlToRequest = new URL("http://datatank.stad.gent/4/bevolking/geboortes.json?%2Fbevolking%2Fgeboortes=");
URL urlToRequest = new URL("http://api.football-data.org/v1/competitions");
urlConnection = (HttpURLConnection)
urlToRequest.openConnection();
urlConnection.setConnectTimeout(CONNECTION_TIMEOUT);
urlConnection.setReadTimeout(DATARETRIEVAL_TIMEOUT);
// handle issues
int statusCode = urlConnection.getResponseCode();
if (statusCode == HttpURLConnection.HTTP_UNAUTHORIZED) {
} else if (statusCode != HttpURLConnection.HTTP_OK) {
// handle any other errors, like 404, 500,..
}
// create JSON object from content
InputStream in = new BufferedInputStream(
urlConnection.getInputStream());
return new JSONArray(getResponseText(in));
} catch (MalformedURLException e) {
// URL is invalid
Log.d("Info", e.getMessage());
} catch (SocketTimeoutException e) {
// data retrieval or connection timed out
Log.d("Info", e.getMessage());
} catch (IOException e) {
// could not read response body
// (could not create input stream)
Log.d("Info", e.getMessage());
} catch (JSONException e) {
// response body is no valid JSON string
Log.d("Info", e.getMessage());
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
return null;
}
#Override
protected void onPostExecute(JSONArray json) {
if (dialog.isShowing()) {
dialog.dismiss();
}
ArrayList <Competitie> competities = new ArrayList<>();
try {
for (int i = 0; i < json.length(); i++) {
Competitie competitie = new Competitie();
JSONObject jsonObject = json.getJSONObject(i);
competitie.setId(jsonObject.getInt("id"));
competitie.setCaption(jsonObject.getString("caption"));
competitie.setLeague(jsonObject.getString("league"));
competitie.setYear(jsonObject.getString("year"));
competitie.setCurrentMatchday(jsonObject.getInt("currentMatchday"));
competitie.setNumberOfMatchdays(jsonObject.getInt("numberOfMatchdays"));
competitie.setNumberOfTeams(jsonObject.getInt("numberOfTeams"));
competitie.setNumberOfGames(jsonObject.getInt("numberOfGames"));
JSONObject links = jsonObject.getJSONObject("_links");
JSONObject teams = links.getJSONObject("teams");
JSONObject stand = links.getJSONObject("leagueTable");
competitie.setTeamString(teams.getString("href"));
competitie.setStandUrl(stand.getString("href"));
competities.add(competitie);
}
} catch (JSONException e) {
e.printStackTrace();
}
listener.updateScreenCompetities(competities);
}
/**
* required in order to prevent issues in earlier Android version.
*/
private static void disableConnectionReuseIfNecessary() {
// see HttpURLConnection API doc
if (Integer.parseInt(Build.VERSION.SDK)
< Build.VERSION_CODES.FROYO) {
System.setProperty("http.keepAlive", "false");
}
}
private static String getResponseText(InputStream inStream) {
// very nice trick from
// http://weblogs.java.net/blog/pat/archive/2004/10/stupid_scanner_1.html
return new Scanner(inStream).useDelimiter("\\A").next();
}
}
where do i add the token so i can contact the api?..
because for know i can't read anymore data because the request capacity is full. i already got my api token emailed to me.
This is the documentation for the api, how do i add the request header?
Documentation about token use
thanks in advance
EDIT
added this line of code and now it works!
urlConnection.setRequestProperty("X-Auth-Token","6a0c52afadac44f5bc65bd0dcfb363c2");

How to parse data from two json by using AssyncTask method?

I have seen one similar question to this, but i couldn't solve my problem like he did.
Here i'm getting data from url:
public class AsyncHttpTask extends AsyncTask<String, Void, Integer> {
#Override
protected void onPreExecute() {
setProgressBarIndeterminateVisibility(true);
}
#Override
protected Integer doInBackground(String... params) {
Integer result = 0;
HttpURLConnection urlConnection;
try {
URL url = new URL(params[0]);
urlConnection = (HttpURLConnection) url.openConnection();
int statusCode = urlConnection.getResponseCode();
// 200 represents HTTP Ok
if (statusCode == 200) {
BufferedReader r = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
StringBuilder response = new StringBuilder();
String line;
while ((line = r.readLine()) != null) {
response.append(line);
}
parseResult(response.toString());
result = 1; // Successful
} else {
result = 0; //"Failed to fetch data!";
}
} catch (Exception e) {
Log.d(TAG, e.getLocalizedMessage());
}
return result; //"Failed to fetch data!";
}
#Override
protected void onPostExecute(Integer result) {
// Download complete. Let us update UI
progressBar.setVisibility(View.GONE);
if (result == 1) {
giftListAdapter = new GiftListAdapter(GiftsActivity.this, gifts);
recyclerView.setAdapter(giftListAdapter);
} else {
SuperActivityToast.create(GiftsActivity.this, getString(R.string.no_internet_connection),
SuperToast.Duration.SHORT, Style.getStyle(Style.RED, SuperToast.Animations.FLYIN)).show();
}
}
}
private void parseResult(String result) {
try {
JSONObject response = new JSONObject(result);
JSONArray posts = response.optJSONArray("gifts");
gifts = new ArrayList<>();
for (int i = 0; i < posts.length(); i++) {
JSONObject post = posts.optJSONObject(i);
GiftItem item = new GiftItem();
item.setThumbnail(post.optString("image"));
item.setTitle(post.optString("title"));
item.setDescription(post.optString("description"));
item.setSource(getString(R.string.source) + " " + post.optString("source"));
item.setTotalRating(post.optInt("rating"));
item.setPrice(post.optDouble("price"));
gifts.add(item);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
And here i'm executing that url. I'm trying now to parse this second url and load all items after first data is loaded:
new AsyncHttpTask().execute(url_movies);
new AsyncHttpTask().execute(url_books); // This is the second url i'm trying to get
How could i do that?
I'm trying now to parse this second url and load all items after first
data is loaded:
Then instead of calling execute method just after first, call it inside onPostExecute method when first url all items are loaded successfully.
Also add second call in if-else block to avoid it execute again :
#Override
protected void onPostExecute(Integer result) {
// Download complete. Let us update UI
progressBar.setVisibility(View.GONE);
... your code here
if(params[0].equals(url_movies)){
new AsyncHttpTask().execute(url_books);
}
}
also add
If you want both urls than send them as an String array like this
String urls[] = new String[]{"url1" , "url2"};
new AsyncHttpTask().execute(urls);
and in doinbackground method exec them like
url1 = params[0];
url2 = params[1];

Android call to webservice returns no result although the URL works fine

This the most bizarre problem I have ever seen. I get "No product available" although there are products in my database.
Here my service:
public class AllProductsService {
private String URL = "xxxx";
Gson gson;
public AllProductsService(int page) {
gson = new Gson();
URL = URL + "?page=" + Integer.toString(page);
}
private InputStream sendRequest(URL url) throws Exception {
try {
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.connect();
if (urlConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
return urlConnection.getInputStream();
}
} catch (Exception e) {
throw new Exception("");
}
return null;
}
public List<Product> getProducts() {
try {
InputStream inputStream = sendRequest(new URL(URL));
if(inputStream != null) {
InputStreamReader reader = new InputStreamReader(inputStream);
return gson.fromJson(reader, new TypeToken<List<Product>>(){}.getType());
}
}
catch (Exception e) {
}
return null;
}
}
And my AsyncTask class:
private class AllProductsTask extends AsyncTask<Void, Void, List<Product>> {
#Override
protected void onPreExecute() {
setSupportProgressBarIndeterminateVisibility(true);
}
#Override
protected List<Product> doInBackground(Void... params) {
AllProductsService allProductsService = new AllProductsService(current_page);
List<Product> liste = allProductsService.getProducts();
if (liste != null && liste.size() >= 1)
return liste;
return new ArrayList<Product>();
}
protected void onPostExecute(java.util.List<Product> result) {
setSupportProgressBarIndeterminateVisibility(false);
if (result.isEmpty() && isInternetPresent && current_page < 2) {
Crouton.makeText(MainActivity.this, "No product available!", Style.ALERT).show();
}
//populate adapter
}
}
When I call the URL from the browser, results are displayed correctly. I also try with a different URL with the same code and it works fine. I don't know why.
I think problem is; you are returning the
new ArrayList<Product>();
in doInBackground() of Asynctask which is null. You should return the liste here. or place the return new ArrayList<Product>(); in else condition
I found the solution: just have to remove the slash at the end of the URL. Thank you #trevor-e. Knowing the HTTP code status help me.

Can I use AsyncTask inside ListFragment? or should I use AsyncTaskLoader?

I tried the code below and also tried the AsyncTaskLoader approach. The app crashes when I instantiate the AsyncTask. Pleas advise me on the best approach to load JSON in a list fragment inside tab host.
The code below is the tab fragment (I use action bar tabs in main activity):
public class TabTop extends ListFragment {
Context context = getActivity().getBaseContext();
String API_URL = "http://api.rottentomatoes.com/api/public/v1.0/movies/770672122/similar.json?apikey=crhhxb4accwwa6cy6fxrm8vj&limit=1";
ArrayList<Deal> deals;
DealsListAdapter adapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
#SuppressWarnings("unused")
int a = 0;
return super.onCreateView(inflater, container, savedInstanceState);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
GetTopDeals getTopDeals = new GetTopDeals(context);
getTopDeals.execute(API_URL);
super.onActivityCreated(savedInstanceState);
}
class GetTopDeals extends AsyncTask<String, Void, ArrayList<Deal>>{
ProgressDialog progressDialog;
public GetTopDeals(Context activity) {
this.progressDialog = new ProgressDialog(activity);
}
#Override
protected void onPostExecute(ArrayList<Deal> result) {
adapter = new DealsListAdapter(context, result);
setListAdapter(adapter);
super.onPostExecute(result);
}
#Override
protected void onPreExecute() {
progressDialog.setCancelable(true);
progressDialog.setProgress(0);
progressDialog.setMessage("loading Top deals...");
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
super.onPreExecute();
}
#Override
protected ArrayList<Deal> doInBackground(String... urls) {
String response = sendRequest(urls[0]); // make request for json
return processResponse(response); // parse the Json and return ArrayList to postExecute
}
private String sendRequest(String apiUrl) {
BufferedReader input = null; // get the json
HttpURLConnection httpCon = null; // the http connection object
StringBuilder response = new StringBuilder(); // hold all the data from the jason in string separated with "\n"
try {
URL url = new URL(apiUrl);
httpCon = (HttpURLConnection) url.openConnection();
if (httpCon.getResponseCode() != HttpURLConnection.HTTP_OK) { // check for connectivity with server
return null;
}
input = new BufferedReader(new InputStreamReader(httpCon.getInputStream())); // pull all the json from the site
String line;
while ((line = input.readLine()) != null) {
response.append(line + "\n");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (input != null) {
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (httpCon != null) {
httpCon.disconnect();
}
}
return response.toString();
}
}
public ArrayList<Deal> processResponse(String response) {
try {
JSONObject responseObject = new JSONObject(response); // Creates a new JSONObject with name/value mappings from the JSON string.
JSONArray results = responseObject.getJSONArray("movies"); // Returns the value mapped by name if it exists and is a JSONArray.
deals = new ArrayList<Deal>();
for (int i = 0; i < results.length(); i++) { // in this loop i copy the json array to movies arraylist in order to display listView
JSONObject jMovie = results.getJSONObject(i);
int api_id = jMovie.getInt("id");
String name = jMovie.getString("title");
String content = jMovie.getString("synopsis");
JSONObject posters = jMovie.getJSONObject("posters");
String image_url = posters.getString("profile");
}
}catch (JSONException e) {
e.printStackTrace();
}
return deals;
}
#Override
public void onStart() {
super.onStart();
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
Intent intent = new Intent(getActivity().getBaseContext(), DealInformation.class);
startActivity(intent);
super.onListItemClick(l, v, position, id);
}
}
Make your asynctask in his own file.
And when your asynctask is finish, implement OnPostExecute which is automatically call. Notify your adapter by a notifyDataSetChanged like that :
#Override
protected void onPostExecute(List<NewItem> list) {
Adapter.getListe().clear();
Adapter.getListe().addAll(list);
Adapter.notifyDataSetChanged();
}
thank you guys,
i want to post my answer. after some research i decided to go with AsyncTaskLoader.
this is my code
public class TabOurPicks extends ListFragment implements LoaderCallbacks<String[]> {
// when activity loads- onActivityCreated() calls the initLoader() who activate onCreateLoader()
#Override
public void onActivityCreated(Bundle savedInstance) {
super.onActivityCreated(savedInstance);
setListAdapter(new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, new String[]{}));
getLoaderManager().initLoader(0, null,this).forceLoad();
}
// onCreateLoader instantiate the asynctaskloaser who work in bg
#Override
public RSSLoader onCreateLoader(int arg0, Bundle arg1) {
return new RSSLoader(getActivity()); //
}
// after bg process invoke onLoadFinished() who work in ui thread
#Override
public void onLoadFinished(Loader<String[]> loader, String[] data) {
setListAdapter(new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, data
) );
}
#Override
public void onLoaderReset(Loader<String[]> arg0) {
// TODO Auto-generated method stub
}
and this is the inner class for the loader:
static public class RSSLoader extends AsyncTaskLoader<String[]>
{
public RSSLoader(Context context) {
super(context);
}
#Override
public String[] loadInBackground() {
String url = "http://api.rottentomatoes.com/api/public/v1.0/movies/770672122/similar.json?apikey=crhhxb4accwwa6cy6fxrm8vj&limit=1";
String response = sendRequest(url);
return processResponse(response);
}
private String sendRequest(String url) {
BufferedReader input = null; // get the json
HttpURLConnection httpCon = null; // the http connection object
StringBuilder response = new StringBuilder(); // hold all the data from the jason in string separated with "\n"
try {
URL apiUrl = new URL(url);
httpCon = (HttpURLConnection) apiUrl.openConnection();
if (httpCon.getResponseCode() != HttpURLConnection.HTTP_OK) { // check for connectivity with server
return null;
}
input = new BufferedReader(new InputStreamReader(httpCon.getInputStream())); // pull all the json from the site
String line;
while ((line = input.readLine()) != null) {
response.append(line + "\n");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (input != null) {
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (httpCon != null) {
httpCon.disconnect();
}
}
return response.toString();
}
private String[] processResponse(String response) {
String[] deals = null;
try {
JSONObject responseObject = new JSONObject(response); // Creates a new JSONObject with name/value mappings from the JSON string.
JSONArray results = responseObject.getJSONArray("movies"); // Returns the value mapped by name if it exists and is a JSONArray.
deals = new String[10];
for (int i = 0; i < 9; i++) { // in this loop i copy the json array to movies arraylist in order to display listView
JSONObject jMovie = results.getJSONObject(i);
String name = jMovie.getString("title");
deals[i] = name;
}
}catch (JSONException e) {
e.printStackTrace();
}
return deals;
}
}
}
It doesn't matter if your asynctask has its own file. You just don't want your activity to extends asynctask as this would make your activity asynchronous - but this is impossible to do anyways due to java's double inheritance rule.
Based on the architecture of your app and your programming style the asyntask can be an inner class in the activity. on the PostExecute method make sure you have given data to your adapter and that the adapter is set to the list, then just run notifyDataSetChanged().
Assuming your asynctask is loading data from cache or the network you are on the right track with your approach to this.

Categories

Resources