How to parse data from 2 different URLs by asyncTask method(如何通过 asyncTask 方法解析来自 2 个不同 URL 的数据)
问题描述
我有一个从 JSON URL 获取数据的应用程序.它适用于一个 URL,但我需要同时从两个 JSON URL 获取数据.就像来自一个 URL 的一些数据和来自另一个 URL 的一些数据一样.并在两个 textViews 中显示它们.
I have an app that get data from a JSON URL. It works perfectly with one URL, but I need to get data from two JSON URLs at the same time. Like some data from one URL and some from the other one. And show them in two textViews.
这是我的应用程序,它当前不加载任何数据.
Here is my app, it does not load any data currently.
主要活动:
public class MainActivity extends Activity {
//URL to get JSON Array
private static String url1 = "http://api.worldbank.org/countries/de?format=json";
private static String url2 = "http://api.worldbank.org/countries/it?format=json";
//JSON Node Names
private static final String CountryNAME1 = "name";
private static final String CountryNAME2 = "name";
JSONArray user = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new GetJSONTask().execute(url1);
//new GETJSONTask().execute(url2);
}
class GetJSONTask extends AsyncTask<String, Void, JSONObject> {
protected JSONObject doInBackground(String... urls) {
// Creating new JSON Parser
JSONParser jParser = new JSONParser();
// Getting JSON from URL
JSONObject json1 = jParser.getJSONFromUrl(url1);
JSONObject json2 = jParser.getJSONFromUrl(url2);
return json1;
}
protected void onPostExecute(JSONObject json1, JSONObject json2) {
//Getting JSON Array
try {
//For Country 1
// Get the array
JSONArray countryArC1 = json1.getJSONArray("myValues");
JSONObject countryObC1 = countryArC1.getJSONObject(0);
JSONArray countryAr2C1 = countryArC1.getJSONArray(1);
JSONObject countryOb2C1 = countryAr2C1.getJSONObject(0);
//For Country 2
// Get the array
JSONArray countryArC2 = json2.getJSONArray("myValues");
JSONObject countryObC2 = countryArC2.getJSONObject(0);
JSONArray countryAr2C2 = countryArC2.getJSONArray(1);
JSONObject countryOb2C2 = countryAr2C2.getJSONObject(0);
//Storing JSON item in a Variable
String name1 = countryOb2C1.getString(CountryNAME1);
String name2 = countryOb2C2.getString(CountryNAME2);
//Importing TextView
final TextView textView1 = (TextView)findViewById(R.id.url1);
final TextView textView2 = (TextView)findViewById(R.id.url2);
//Set JSON Data in TextView
textView1.setText(name1);
textView2.setText(name2);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
JSONParser:
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url) {
//System.out.println("url getJSONfromUrl " + url);
//url = "http://api.worldbank.org/countries/CA/indicators/SP.POP.TOTL?date=1980:1981&format=json";
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
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 = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "
");
}
is.close();
json = sb.toString();
System.out.println("JSONParser string: " + json);
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
if (json.startsWith("[")) {
// We have a JSONArray
try {
jObj = new JSONObject();
jObj.put("data", new JSONArray(json));
} catch (JSONException e) {
Log.d("JSON Parser", "Error parsing JSONArray " + e.toString());
}
return jObj;
}
// try 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;
}
}
XML:
<TextView
android:id="@+id/url1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<TextView
android:id="@+id/url2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="@+id/url1"
android:layout_marginTop="104dp"
/>
我认为主要问题是 new GetJSONTask().execute(url1);
和 JSONObject json1 = jParser.getJSONFromUrl(url1);
因为我不能有 2 个 GetJSONTASKs并且不能同时返回json1和json2.
I think the main problem is new GetJSONTask().execute(url1);
and JSONObject json1 = jParser.getJSONFromUrl(url1);
As I cant have 2 GetJSONTASKs and also cant return json1 and json2 at the same time.
有什么想法吗?
推荐答案
建议你把方法改成
class GetJSONTask extends AsyncTask<String, Void, JSONObject[]> {
...
protected JSONObject[] doInBackground(String... urls) {
// Creating new JSON Parser
JSONParser jParser = new JSONParser();
// Getting JSON from URL
JSONObject[] jsons = new JSONObject[2];
jsons[0] = jParser.getJSONFromUrl(url1);
jsons[1] = jParser.getJSONFromUrl(url2);
return jsons;
}
protected void onPostExecute(JSONObject[] jsons) {
JSONObject json1 = jsons[0];
JSONObject json2 = jsons[1];
// do you work after this
}
}
希望对您有所帮助!
这篇关于如何通过 asyncTask 方法解析来自 2 个不同 URL 的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何通过 asyncTask 方法解析来自 2 个不同 URL 的数


基础教程推荐
- 修改 void 函数的输入参数,然后读取 2022-01-01
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
- Struts2 URL 无法访问 2022-01-01
- 如何对 Java Hashmap 中的值求和 2022-01-01
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
- 使用堆栈算法进行括号/括号匹配 2022-01-01
- RabbitMQ:消息保持“未确认"; 2022-01-01
- 存储 20 位数字的数据类型 2022-01-01