Java 如何通过asyncTask方法解析来自2个不同URL的数据
我有一个从JSON URL获取数据的应用程序。它与一个URL完美配合,但我需要同时从两个JSON URL获取数据。比如一个URL中的一些数据和另一个URL中的一些数据。并在两个文本视图中显示它们 这是我的应用程序,它目前没有加载任何数据 main活动:Java 如何通过asyncTask方法解析来自2个不同URL的数据,java,android,json,android-asynctask,return,Java,Android,Json,Android Asynctask,Return,我有一个从JSON URL获取数据的应用程序。它与一个URL完美配合,但我需要同时从两个JSON URL获取数据。比如一个URL中的一些数据和另一个URL中的一些数据。并在两个文本视图中显示它们 这是我的应用程序,它目前没有加载任何数据 main活动: public class MainActivity extends Activity { //URL to get JSON Array private static String url1 = "http://api.worldbank.or
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;
}
}
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 + "\n");
}
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:
我认为主要的问题是newgetjsontask().execute(url1)
和JSONObject json1=jParser.getJSONFromUrl(url1)代码>因为我不能有2个GetJSontask,也不能同时返回json1和json2
有什么想法吗?变体A)您可以像这样执行GetJSONTask
:
new GetJSONTask().execute(url1, url2);
class GetJSONTask extends AsyncTask<String, Void, JSONObject[]> {
...
JSONObject[] doInBackground(String... urls) {
// Getting JSON from URL
JSONObject json1 = jParser.getJSONFromUrl(urls[1]);
JSONObject json2 = jParser.getJSONFromUrl(url2[2]);
return new JSONObject[] {json1, json2};
}
void onPostExecute(JSONObject[] jsons) { ... }
}
并访问AsyncTask中的URL,如下所示:
new GetJSONTask().execute(url1, url2);
class GetJSONTask extends AsyncTask<String, Void, JSONObject[]> {
...
JSONObject[] doInBackground(String... urls) {
// Getting JSON from URL
JSONObject json1 = jParser.getJSONFromUrl(urls[1]);
JSONObject json2 = jParser.getJSONFromUrl(url2[2]);
return new JSONObject[] {json1, json2};
}
void onPostExecute(JSONObject[] jsons) { ... }
}
类GetJSONTask扩展了异步任务{
...
JSONObject[]doInBackground(字符串…URL){
//从URL获取JSON
JSONObject json1=jParser.getJSONFromUrl(URL[1]);
JSONObject json2=jParser.getJSONFromUrl(url2[2]);
返回新的JSONObject[]{json1,json2};
}
void onPostExecute(JSONObject[]jsons){…}
}
变体B)如果您想让流程真正并行运行,可以添加另一个AsyncTask,创建两个子任务并等待结果。在大多数设备上,这将是执行该任务所需时间的一半
class GetTwoJsonsTask extends AsyncTask<String, Void, JSONObject[]> {
JSONObject[] doInBackground(urls) {
task1 = new GetJSONTask().execute(urls[1]);
task2 = new GetJSONTask().execute(urls[2]);
// block until sub-tasks are finished
JSONObject json1 = task1.get();
JSONObject json2 = task2.get();
return new JSONObject[] {json1, json2};
}
void onPostExecute(JSONObject[] jsons) { ... }
}
类GetTwoJSonTask扩展了AsyncTask{
JSONObject[]doInBackground(URL){
task1=new GetJSONTask().execute(URL[1]);
task2=new GetJSONTask().execute(URL[2]);
//阻止,直到子任务完成
JSONObject json1=task1.get();
JSONObject json2=task2.get();
返回新的JSONObject[]{json1,json2};
}
void onPostExecute(JSONObject[]jsons){…}
}
我建议您将方法更改为
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
}
}
类GetJSONTask扩展了异步任务{
...
受保护的JSONObject[]doInBackground(字符串…URL){
//创建新的JSON解析器
JSONParser jParser=新的JSONParser();
//从URL获取JSON
JSONObject[]jsons=新的JSONObject[2];
jsons[0]=jParser.getJSONFromUrl(url1);
jsons[1]=jParser.getJSONFromUrl(url2);
返回JSON;
}
受保护的void onPostExecute(JSONObject[]jsons){
JSONObject json1=jsons[0];
JSONObject json2=jsons[1];
//这之后你工作吗
}
}
希望这有帮助 我就是这样做的,很容易做到
public class GetSetting extends AsyncTask<List<String>,Void,List<String>> {
String urls[] = new String[]{"http:// first url",
"http:// second url"};
@Override
protected ArrayList<String> doInBackground(List<String>... lists) {
HttpURLConnection urlConnection;
InputStream inputStream;
BufferedReader bufferedReader;
URL urlIfSup;
ArrayList<String> result = new ArrayList<>();
try {
// here to connect and get a different type of data
for (int i = 0; i < 2; i++){ // this one for connect the url from url array in every loop
urlIfSup = new URL(urls[i]);
urlConnection = (HttpURLConnection) urlIfSup.openConnection();
inputStream = urlConnection.getInputStream();
bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"utf-8"));
String data = bufferedReader.readLine();
while(bufferedReader.readLine() != null){
data += bufferedReader.readLine();
}
if (i==0) {
// do something for the first url
}else if (i==1){
// do something for the second url
// use jSON if you want
// then do this at the last url
urlConnection.disconnect();
inputStream.close();
bufferedReader.close();
}
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
}
public类GetSetting扩展了异步任务{
字符串url[]=新字符串[]{“http://first url”,
“http://secondurl”};
@凌驾
受保护的ArrayList doInBackground(列表…列表){
HttpURLConnection-urlConnection;
输入流输入流;
BufferedReader BufferedReader;
URL urlIfSup;
ArrayList结果=新建ArrayList();
试一试{
//这里连接并获取不同类型的数据
对于(inti=0;i<2;i++){//这一个用于从每个循环中的url数组连接url
urlIfSup=新URL(URL[i]);
urlConnection=(HttpURLConnection)urlIfSup.openConnection();
inputStream=urlConnection.getInputStream();
bufferedReader=新的bufferedReader(新的InputStreamReader(inputStream,“utf-8”));
字符串数据=bufferedReader.readLine();
while(bufferedReader.readLine()!=null){
data+=bufferedReader.readLine();
}
如果(i==0){
//对第一个url执行一些操作
}else如果(i==1){
//为第二个url做一些事情
//如果需要,可以使用jSON
//然后在最后一个url上执行此操作
urlConnection.disconnect();
inputStream.close();
bufferedReader.close();
}
}
}捕获(格式错误){
e、 printStackTrace();
}捕获(IOE异常){
e、 printStackTrace();
}
返回结果;
}
}
谢谢您的帮助。但有一个问题。它的错误如下返回新的JSONObject[]{json1,json2}代码>这就是原因:类型不匹配:无法从JSONObject[]转换为JSONObject您需要在泛型AsyncTask中提供正确的类型:GetJSONTask Extendes AsyncTask