gpt4 book ai didi

java - 在 Android 中从 PHP 获取数据

转载 作者:行者123 更新时间:2023-12-01 19:04:00 24 4
gpt4 key购买 nike

我已经看过几个这方面的教程,但它们都比阻止主线程中的网络调用的 Android 更新更旧。我尝试将调用它的代码移至 RetrieveFeedTask,但这对我没有帮助,因为我无法在主线程中获取数据。这是我所做的:

class RetrieveFeedTask extends AsyncTask <String, Void, String>
{

private Exception exception;

private String doInBackground()
{
String returnString = "sample";

ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
//http post
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://localhost/sample_array.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.e("log_tag", "Error in http connection"+e.toString());
}
//convert response to string
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
sb = new StringBuilder();
sb.append(reader.readLine() + "\n");

String line="0";
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result=sb.toString();
}catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}
//paring data
int step_num;
String description;
try{
jArray = new JSONArray(result);
JSONObject json_data=null;
for(int i=0;i<jArray.length();i++){
json_data = jArray.getJSONObject(i);
step_num=json_data.getInt("step_num");
description=json_data.getString("description");
}
}
catch(JSONException e1){
Toast.makeText(getBaseContext(), "No step found" ,Toast.LENGTH_LONG).show();
} catch (ParseException e1) {
e1.printStackTrace();
}

//System.out.println(result);
return result;
}

@Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
return null;
}

}

然后在主线程中,我这样做了:

AsyncTask<String, Void, String> returnString = new RetrieveFeedTask().execute();

那么如何获取该信息以在主线程中使用?

最佳答案

您几乎可以接受,但有两个错误:

  1. 您正在重载永远无法调用的 doInBackground 方法。
  2. 在“当前”空的 doInBackground 实现中实现您的内容。

如果您想在主线程上取回数据,您可以:

  1. 使用runOnUiThread方法
  2. 创建 Anonymous Inner Class在您的 Activity 中,它将扩展您的异步任务并覆盖 onPostExecute方法。 (在 ui 线程上运行)

:)

关于java - 在 Android 中从 PHP 获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10967915/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com