Empty Activity When I try to load JSON from S3 - java

When I navigate to the activity that should load a ListView from a JSON hosted on AWS S3, I get nothing but a blank activity. There's no error message, no errors in the debugger, and Logcat doesn't seem to hold any relevant information.
Here's LoadJSONTask.java:
package com.teamplum.projectapple;
import android.os.AsyncTask;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.teamplum.projectapple.NewsDO;
import com.teamplum.projectapple.Response;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
public class LoadJSONTask extends AsyncTask<String, Void, Response> {
public LoadJSONTask(Listener listener) {
mListener = listener;
}
public interface Listener {
void onLoaded(List<NewsDO> androidList);
void onError();
}
private Listener mListener;
#Override
protected Response doInBackground(String... strings) {
try {
String stringResponse = loadJSON(strings[0]);
Gson gson = new Gson();
return gson.fromJson(stringResponse, Response.class);
} catch (IOException e) {
e.printStackTrace();
return null;
} catch (JsonSyntaxException e) {
e.printStackTrace();
return null;
}
}
#Override
protected void onPostExecute(Response response) {
if (response != null) {
mListener.onLoaded(response.getAndroid());
} else {
mListener.onError();
}
}
private String loadJSON(String jsonURL) throws IOException {
URL url = new URL(jsonURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("GET");
conn.setDoInput(true);
conn.connect();
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
StringBuilder response = new StringBuilder();
while ((line = in.readLine()) != null) {
response.append(line);
}
in.close();
return response.toString();
}
}
and here's MainActivity.java:
package com.teamplum.projectapple;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
//import com.teamplum.projectapple.NewsDO;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class MainActivity extends AppCompatActivity implements LoadJSONTask.Listener, AdapterView.OnItemClickListener {
private ListView mListView;
public static final String URL = "https://s3-eu-west-1.amazonaws.com/tyi-work/Work_Experience.json";
private List<HashMap<String, String>> mAndroidMapList = new ArrayList<>();
private static final String KEY_TIT = "title";
private static final String KEY_CAT = "category";
private static final String KEY_DES = "description";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mListView = findViewById(R.id.list_view);
mListView.setOnItemClickListener(this);
new LoadJSONTask(this).execute(URL);
}
#Override
public void onLoaded(List<NewsDO> androidList) {
for (NewsDO work : androidList) {
HashMap<String, String> map = new HashMap<>();
map.put(KEY_TIT, work.getTitle());
map.put(KEY_CAT, work.getCategory());
map.put(KEY_DES, work.getDescription());
mAndroidMapList.add(map);
}
loadListView();
}
#Override
public void onError() {
Toast.makeText(this, "Error !", Toast.LENGTH_SHORT).show();
}
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Toast.makeText(this, mAndroidMapList.get(i).get(KEY_TIT),Toast.LENGTH_LONG).show();
}
private void loadListView() {
ListAdapter adapter = new SimpleAdapter(MainActivity.this, mAndroidMapList, R.layout.list_item,
new String[] { KEY_CAT, KEY_TIT, KEY_DES },
new int[] { R.id.version,R.id.name, R.id.api });
mListView.setAdapter(adapter);
}
}
I used this tutorial to help make this, if you need any extra information please feel free to ask, thank you.

I have tested the async task for the URL connection and its working fine.
The problem is either on the parsing or on the activity side. Have you tried putting breakpoints and follow the data?

Related

Accessing the searchview query text from mainactivity

I am planning to make a news app. I have created a simple search view inside the action bar of my app.
This is the Main activity
package com.example.hp.simplenews;
import android.app.Activity;
import android.app.LoaderManager;
import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.content.Loader;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SearchView;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity implements LoaderManager.LoaderCallbacks<List<News>> {
private int Newsloaderid = 1;
private Newsadapter newslistadapter;
private String search_query_input = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView newslistview = findViewById(R.id.list);
newslistadapter = new Newsadapter(this, new ArrayList<News>());
newslistview.setAdapter(newslistadapter);
LoaderManager loaderManager = getLoaderManager();
loaderManager.initLoader(Newsloaderid, null, MainActivity.this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the options menu from XML
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.options_menu, menu);
// Get the SearchView and set the searchable configuration
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
SearchView searchView = (SearchView) menu.findItem(R.id.search).getActionView();
// Assumes current activity is the searchable activity
searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
searchView.setIconifiedByDefault(false); // Do not iconify the widget; expand it by default
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String newtext) {
search_query_input = newtext;
return true;
}
#Override
public boolean onQueryTextChange(String query) {
return true;
}
});
return true;
}
#Override
public Loader<List<News>> onCreateLoader(int i, Bundle bundle) {
return new NewsLoader(this, search_query_input);
}
#Override
public void onLoadFinished(Loader<List<News>> loader, List<News> news) {
newslistadapter.clear();
if (news != null && !news.isEmpty()) {
newslistadapter.addAll(news);
}
}
#Override
public void onLoaderReset(Loader loader) {
newslistadapter.clear();
}
}
The SearchResultsActivity handles the HTTP request and JSON parsing.
This is the SearchResultsActivity
package com.example.hp.simplenews;
import android.app.Activity;
import android.app.LoaderManager;
import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.content.Loader;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.widget.SearchView;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
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.URL;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
public class SearchResultsActivity extends Activity{
String query_string = "";
private static final String LOG_TAG = SearchResultsActivity.class.getName();
public static URL createUrl(String query_url) throws MalformedURLException {
URL url = null;
String APIKey = "apiKey";
String query = "q";
try {
final String base_url = "https://newsapi.org/v2/everything?";
Uri final_url = Uri.parse(base_url).buildUpon()
.appendQueryParameter(query, query_url)
.appendQueryParameter(APIKey, "48f67c1e66994aa8a92f92a48b5f6581")
.build();
url = new URL(final_url.toString());
Log.i(LOG_TAG, "THE FINAL URL IS" + final_url);
} catch (MalformedURLException e) {
e.printStackTrace();
Log.e(LOG_TAG, "the url couldn't be made");
}
return url;
}
private static final String HTTPREQUEST(URL url) throws IOException {
String jsonresponse = "";
if (jsonresponse == null) {
return null;
}
HttpURLConnection httpURLConnection = null;
InputStream inputStream = null;
try {
httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("GET");
httpURLConnection.setReadTimeout(10000);
httpURLConnection.setConnectTimeout(150000);
httpURLConnection.connect();
if (httpURLConnection.getResponseCode() == 200) {
inputStream = httpURLConnection.getInputStream();
jsonresponse = readfromstream(inputStream);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (inputStream != null) {
inputStream.close();
}
if (httpURLConnection != null) {
httpURLConnection.disconnect();
}
}
return jsonresponse;
}
private static final String readfromstream(InputStream inputStream) throws IOException {
StringBuilder output = new StringBuilder();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, Charset.forName("UTF-8"));
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String urlline = bufferedReader.readLine();
while (urlline != null) {
output.append(urlline);
urlline = bufferedReader.readLine();
}
return output.toString();
}
private static List<News> JSONParser(String NewsJSON) throws JSONException {
if (TextUtils.isEmpty(NewsJSON)) {
return null;
}
List<News> news = new ArrayList<>();
try {
JSONObject basejson = new JSONObject(NewsJSON);
JSONArray articles = basejson.getJSONArray("articles");
for (int i = 0; i < articles.length(); i++) {
News newss = new News();
JSONObject c = articles.getJSONObject(i);
JSONObject source = c.getJSONObject("source");
newss.setMsource(source.getString("name"));
newss.setMtitle(c.getString("title"));
newss.setMdescription(c.getString("description"));
newss.setMtime(c.getString("publishedAt"));
String image = c.getString("urlToImage");
if (image != null) {
newss.setmImage(c.getString("urlToImage"));
}
newss.setNewsURL(c.getString("url"));
news.add(newss);
}
} catch (JSONException j) {
Log.e(LOG_TAG, "couldn't parse jSON");
}
return news;
}
public static List<News> fetchnews(String search_query) throws IOException, JSONException {
URL url = createUrl(search_query);
String JSONRESPONSE = null;
try {
JSONRESPONSE = HTTPREQUEST(url);
} catch (IOException j) {
j.printStackTrace();
}
List<News> news = JSONParser(JSONRESPONSE);
return news;
}
#Override
protected void onNewIntent(Intent intent) {
setIntent(intent);
try {
handleIntent(intent);
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
private void handleIntent(Intent intent) throws MalformedURLException {
if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
query_string = intent.getStringExtra(SearchManager.QUERY);
Log.i(LOG_TAG, "The querytext is" + query_string);
}
}
}
This whole process of refreshing the list view is done by a AsyncTaskLoader
The custom Asyntaskloader class is copied below:
public class NewsLoader extends AsyncTaskLoader<List<News>> {
private String mUrl;
private static String LOG_TAG = NewsLoader.class.getName();
public NewsLoader(Context context, String url) {
super(context);
mUrl = url;
}
#Override
protected void onStartLoading() {
forceLoad();
}
#Override
public List<News> loadInBackground() {
if (mUrl == null) {
return null;
}
List<News> news = null;
try {
news = SearchResultsActivity.fetchnews(mUrl);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return news;
}
}
Now I have the search query entered by the user stored in the search_query_input variable in the MainActivity.
But the app just gets stuck when I press the submit button. The override methods for the asynctaskloader are not getting executed at all.
What is happening? Any help will be much appreciated.
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener(){
onQueryTextChange(String newText){
//when user type in searchview get string as newText parameter
asynTaskMethod(newText);
}
onQueryTextSubmit(String query){
//when user press submit button in searchview get string as query parameter
asynTaskMethod(query);
}
});

Listview not getting populated and is empty. Arrayadapter seems to be working fine

I am new to Android so I am sorry if this is a mundane question. I am working on one of the exercises in a tutorial and I have a simple list which is supposed to display the data I got from a website. My listview is empty despite my adapter being populated correctly. I tried printing the adapter objects and it is working fine. Please help. Thanks in advance.
MainAcitvity.java
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import java.net.URL;
import java.util.ArrayList;
import java.util.concurrent.ExecutionException;
public class MainActivity extends AppCompatActivity {
private static String USGS_URL = "https://earthquake.usgs.gov/fdsnws/event/1/query?format=geojson&starttime=2014-01-01&endtime=2014-12-01&minmagnitude=7";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DownloadTask task = new DownloadTask();
ArrayList<String> place = new ArrayList<>();
try {
place = task.execute(USGS_URL).get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
ArrayAdapter<String> placesAdapter = new ArrayAdapter<String>(getApplicationContext(),android.R.layout.simple_list_item_1,place);
ListView listView = (ListView)findViewById(R.id.listView);
listView.setAdapter(placesAdapter);
}
private class DownloadTask extends AsyncTask<String, Void, ArrayList<String>>
{
#Override
protected ArrayList<String> doInBackground(String... strings) {
ArrayList<String > place = QueryUtils.fetchData(strings[0]);
}return place;
}
}
}
QueryUtils.java
import android.util.Log;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import javax.net.ssl.HttpsURLConnection;
public final class QueryUtils {
private QueryUtils() {
}
protected static ArrayList<String> fetchData(String rawStream) {
URL newUrl = null;
try {
newUrl = createUrl(rawStream);
Log.i("QueryUtils.java", newUrl.toString());
} catch (MalformedURLException e) {
e.printStackTrace();
}
ArrayList<String> values = QueryUtils.makeHttpRequest(newUrl);
}return values;
}
private static URL createUrl(String rawStream) throws MalformedURLException {
URL url = new URL(rawStream);
return url;
}
public static ArrayList<String> makeHttpRequest(URL newUrl) {
HttpsURLConnection url = null;
InputStream in = null;
ArrayList<String> values = new ArrayList<>();
try {
url = (HttpsURLConnection) newUrl.openConnection();
in = url.getInputStream();
String data = fetchJsonData(in);
values = fetchOutput(data);
} }catch (IOException e) {
e.printStackTrace();
}
finally {
if(url !=null)
url.disconnect();
}
return values;
}
private static ArrayList<String> fetchOutput(String data) {
String place = null;
ArrayList<String> values = new ArrayList<>();
try {
JSONObject baseJsonObject = new JSONObject(data);
JSONArray featuresAray =baseJsonObject.getJSONArray("features");
for(int i=0;i<featuresAray.length();i++) {
JSONObject firstArray = featuresAray.getJSONObject(i);
JSONObject properties = firstArray.getJSONObject("properties");
place = properties.getString("place");
values.add(place);
}
} catch (JSONException e) {
e.printStackTrace();
}
return values;
}
private static String fetchJsonData(InputStream in) throws IOException {
StringBuilder output = new StringBuilder();
InputStreamReader inReader = new InputStreamReader(in);
BufferedReader reader = new BufferedReader(inReader);
String line = reader.readLine();
while (line != null) {
output.append(line);
line = reader.readLine();
}
return output.toString();
}
}
So the solution was really really stupid. I cant believe I wasted so much time over this. Apparently the text was white and that's why my listView seemed empty :(:(

How to import class from another file in java in Android Studio?

I'm trying to call the function getUrlContents(string) inside my seismic_text.java file to my MainActivity.java file. How can I call the function from anywhere in the file? Any information or tip is appreciated. I include my files down below.
This is my MainActivity.java:
package bt.alfaquake;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.app.NotificationManager;
import android.content.Intent;
import android.view.View;
import android.app.PendingIntent;
import android.support.v7.app.ActionBarActivity;
import android.support.v4.app.NotificationCompat;
import bt.alfaquake.seismic_text;
public class MainActivity extends AppCompatActivity {
NotificationCompat.Builder notification;
private static final int uniqueID = 123;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
notification = new NotificationCompat.Builder(this);
}
}
This is my seismic_text.java:
package bt.alfaquake;
import java.net.*;
import java.io.*;
public class seismic_text {
public static String getUrlContents(String theUrl) {
StringBuilder content = new StringBuilder();
try
{
URL url = new URL(theUrl);
URLConnection urlConnection = url.openConnection();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
String line;
while ((line = bufferedReader.readLine()) != null)
{
content.append(line + "\n");
}
bufferedReader.close();
}
catch(Exception e)
{
e.printStackTrace();
}
return content.toString();
}
}
}
You can call seismic_text.getUrlContents(url); but it will cause NetworkOnMainThreadException
Just wrap this call to Simple AsynkTask.
class MyTask extends AsyncTask<Void, Void, String> {
#Override
protected String doInBackground(Void... params) {
try {
return seismic_text.getUrlContents(url);
} catch (InterruptedException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
// TODO handle result here
}
}
And call it from your code:
new MyTask().execute();
Simply call this in your MainActivty.java:
seismic_text.getUrlContents(url);

setListAdapter unable to be resolved

a real amateur developer here in dire need of some assistance. I've been trying to parse JSON data and turn it into a list of items, but I am having difficulties attempting to use the setListAdapter method despite importing it into the class. Any help would be massively appreciated.
Here is my main activity, error is in the onPostExecute method
import java.io.IOException;
import java.util.List;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import android.app.Activity;
import android.net.http.AndroidHttpClient;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.ArrayAdapter;
public class JSON extends Activity {
// Coordinates used for centering the Map
private final static String UNAME = "aporter";
private final static String URL = "http://api.geonames.org/earthquakesJSON?north=44.1&south=-9.9&east=-22.4&west=55.2&username="
+ UNAME;
public static final String TAG = "MapsEarthquakeMapActivity";
// Set up UI and get earthquake data
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
new HttpGetTask().execute(URL);
}
private class HttpGetTask extends
AsyncTask<String, Void, List<GeonameRec>> {
AndroidHttpClient mClient = AndroidHttpClient.newInstance("");
#Override
protected List<GeonameRec> doInBackground(String... params) {
HttpGet request = new HttpGet(params[0]);
JSONResponseHandler responseHandler = new JSONResponseHandler();
try {
// Get Earthquake data in JSON format
// Parse data into a list of EarthQuakeRecs
return mClient.execute(request, responseHandler);
} catch (ClientProtocolException e) {
Log.i(TAG, "ClientProtocolException");
} catch (IOException e) {
Log.i(TAG, "IOException");
}
return null;
}
#Override
protected void onPostExecute(List<GeonameRec> result) {
if (null != mClient)
mClient.close();
setListAdapter(new ArrayAdapter<String>(
JSON.this,
R.layout.listitem, result));
}
}
}
}
And here is my class where I format the JSON response.
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.impl.client.BasicResponseHandler;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;
public class JSONResponseHandler implements
ResponseHandler<List<GeonameRec>> {
#Override
public List<GeonameRec> handleResponse(HttpResponse response)
throws ClientProtocolException, IOException {
List<GeonameRec> result = new ArrayList<GeonameRec>();
String JSONResponse = new BasicResponseHandler()
.handleResponse(response);
try {
JSONObject object = (JSONObject) new JSONTokener(JSONResponse)
.nextValue();
JSONArray earthquakes = object.getJSONArray("earthquakes");
for (int i = 0; i < earthquakes.length(); i++) {
JSONObject tmp = (JSONObject) earthquakes.get(i);
result.add(new GeonameRec(
tmp.getDouble("lat"),
tmp.getDouble("lng")));
}
} catch (JSONException e) {
e.printStackTrace();
}
return result;
}
}
setListAdapter method is available in ListActivity not in Activity.
to do so in an Activity sub class, you should define your ListView and call listView.setAdapter

errors in extracting json object

I have to retrieve json object from json file from this url.
My code is throwing java.lang.RuntimeException in doInBackground() and string to jsonObject conversion exception.
Can anyone help me at this? I am new to Android programming.
package course.examples.networkingearthquake;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.os.AsyncTask;
import android.widget.Button;
import android.view.View;
import android.widget.TextView;
import android.widget.EditText;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;
import android.net.http.AndroidHttpClient;
public class HttpActivity extends ActionBarActivity {
TextView mTextView;
EditText etInput;
TextView input;
String number;//edited
int num;//edited
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_socket);
mTextView = (TextView)findViewById(R.id.text1);
input = (TextView)findViewById(R.id.input);
etInput = (EditText)findViewById(R.id.etInput);
input.setText("Input");
//number = etInput.getText().toS();
final Button btDisplay = (Button)findViewById(R.id.btDisplay);
btDisplay.setText("DISPLAY");
btDisplay.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
new HttpGetTask().execute();
}
});
}
private class HttpGetTask extends AsyncTask<Void, Void, String>{
private static final String TAG = "HttpGetTask";
private static final String URL = "http://earthquake.usgs.gov/earthquakes/feed/geojsonp/2.5/week";
AndroidHttpClient mClient = AndroidHttpClient.newInstance("");
#Override
protected String doInBackground(Void... params){
HttpGet request = new HttpGet(URL);
JSONResponseHandler responseHandler = new JSONResponseHandler();
// ResponseHandler<String> responseHandler = new BasicResponseHandler();
try{
return mClient.execute(request,responseHandler);
}catch(ClientProtocolException exception){
exception.printStackTrace();
}catch(IOException exception){
exception.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result){
if(null != mClient)
mClient.close();
mTextView.setText(result);
}
}
private class JSONResponseHandler implements ResponseHandler<String>{
#Override
public String handleResponse(HttpResponse response)
throws ClientProtocolException, IOException {
String result = null;
String JSONResponse = new BasicResponseHandler().handleResponse(response);
JSONResponse = JSONResponse.substring(17, JSONResponse.length()-3);
num = Integer.parseInt(number);// edited
try {
JSONObject responseObject = (JSONObject) new JSONTokener(
JSONResponse).nextValue();
JSONArray features = responseObject.getJSONArray("features");
JSONObject retObject = (JSONObject)features.get(num);//edited
// JSONObject geometry = (JSONObject)retObject.get("geometry");
result = retObject.toString();
} catch (JSONException e) {
e.printStackTrace();
}
return result;
}
}
The JSON returned by the URL you specify containts eqfeed_callback() which needs to be stripped in order to make it valid JSON.
It seems like you have done this in your response handler, but you are cutting off one character too much at both the start and the end.
Try this:
JSONResponse = JSONResponse.substring(16, JSONResponse.length()-2);

Categories

Resources