I'm trying to fix a Thread error for one of my preferred examples from java code geeks.
Here's the code:
public class JsonParsingActivity extends Activity {
String url = "http://search.twitter.com/search.json?q=javacodegeeks";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
new RetreiveFeedTask().execute(url);
}
}
The RetrieveFeedTask:
public class RetreiveFeedTask extends
AsyncTask<String, Void, JsonParsingActivity> {
private Exception exception;
String url = "http://search.twitter.com/search.json?q=javacodegeeks";
protected JsonParsingActivity doInBackground(String... urls) {
try {
InputStream source = retrieveStream(url);
Gson gson = new Gson();
Reader reader = new InputStreamReader(source);
SearchResponse response = gson.fromJson(reader, SearchResponse.class);
// Toast.makeText(this, response.query, Toast.LENGTH_SHORT).show();
List<Result> results = response.results;
for (Result result : results) {
Toast.makeText(JsonParsingActivity.class, result.fromUser, Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
this.exception = e;
return null;
}
}
protected void onPostExecute(JsonParsingActivity feed) {
// TODO: check this.exception
// TODO: do something with the feed
}
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;
}}
What's the best way to do that without errors?
It's currently giving a Toast error (?).
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…