如何使用asynctask实现此功能。我尝试了很多不能工作的方法。现在我只是减少构建版本,以允许主线程上的网络操作。 我想要做的是从我托管的php脚本中检索数据并填充listview。一些帮助将受到高度赞赏:D
public class Database extends ListActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String url="http://www.mahuwa.com/api/phpserv.php";
String result = null;
InputStream is = null;
StringBuilder sb = null;
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
List<String> b = new ArrayList<String>();
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}
catch(Exception e){
Toast.makeText(getBaseContext(),e.toString() ,Toast.LENGTH_LONG).show();
}
//response to inputstream
try
{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"UTF-8"));
sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
is.close();
result = sb.toString();
}
catch(Exception e)
{
Toast.makeText(getBaseContext(),e.toString() ,Toast.LENGTH_LONG).show();
}
// to string
try{
JSONArray jArray = new JSONArray(result);
JSONObject json_data=null;
for(int i=0;i<jArray.length();i++)
{
json_data = jArray.getJSONObject(i);
b.add(json_data.getString("Organization"));
}
setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,b));
}
catch(JSONException e1){
Toast.makeText(getBaseContext(),e1.toString() ,Toast.LENGTH_LONG).show();
} catch (ParseException e1) {
Toast.makeText(getBaseContext(),e1.toString() ,Toast.LENGTH_LONG).show();
}
}
答案 0 :(得分:0)
在你的oncreate方法中写这个,这里rssFeed是你传递的网址。
MyTask().execute(rssFeed);
并创建一个名为MyTask的新类,它扩展了asynctask。
class MyTask extends AsyncTask<String, Void, String> {
ProgressDialog pDialog;
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Loading...");
pDialog.setCancelable(false);
pDialog.show();
}
@Override
protected String doInBackground(String... params) {
return Utils.getJSONString(params[0]);
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (null != pDialog && pDialog.isShowing()) {
pDialog.dismiss();
}
if (null == result || result.length() == 0) {
showToast("No data found from web!!!");
MainActivity.this.finish();
} else {
try { JSONArray jArray = new JSONArray(result);
JSONObject json_data=null;
for(int i=0;i<jArray.length();i++)
{
json_data = jArray.getJSONObject(i);
b.add(json_data.getString("Organization"));
}
setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,b));
}
catch(JSONException e1){
Toast.makeText(getBaseContext(),e1.toString() ,Toast.LENGTH_LONG).show();
} catch (ParseException e1) {
Toast.makeText(getBaseContext(),e1.toString() ,Toast.LENGTH_LONG).show();
}
}
创建一个名为Utils的新类,然后在那里做Http。
public class Utils {
public static String getJSONString(String url) {
String jsonString = null;
HttpURLConnection linkConnection = null;
try {
URL linkurl = new URL(url);
linkConnection = (HttpURLConnection) linkurl.openConnection();
int responseCode = linkConnection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
InputStream linkinStream = linkConnection.getInputStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int j = 0;
while ((j = linkinStream.read()) != -1) {
baos.write(j);
}
byte[] data = baos.toByteArray();
jsonString = new String(data);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (linkConnection != null) {
linkConnection.disconnect();
}
}
return jsonString;
}
答案 1 :(得分:0)
试试这个
public class Database extends ListActivity {
String url = "http://www.mahuwa.com/api/phpserv.php";
String result = null;
InputStream is = null;
StringBuilder sb = null;
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
List<String> b = new ArrayList<String>();
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(/* Your layout */);
new DatabaseThread().execute();
}
class DatabaseThread extends AsyncTask<Void, Void, Void> {
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected Void doInBackground(Void... params) {
parseJson();
return null;
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
setListAdapter(new ArrayAdapter<String>(Database.this,
android.R.layout.simple_list_item_1, b));
}
}
private void parseJson() {
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.toString(), Toast.LENGTH_LONG)
.show();
}
// response to inputstream
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "UTF-8"));
sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.toString(), Toast.LENGTH_LONG)
.show();
}
// to string
try {
JSONArray jArray = new JSONArray(result);
JSONObject json_data = null;
for (int i = 0; i < jArray.length(); i++) {
json_data = jArray.getJSONObject(i);
b.add(json_data.getString("Organization"));
}
}
catch (JSONException e1) {
Toast.makeText(getBaseContext(), e1.toString(), Toast.LENGTH_LONG)
.show();
} catch (ParseException e1) {
Toast.makeText(getBaseContext(), e1.toString(), Toast.LENGTH_LONG)
.show();
}
}
}
答案 2 :(得分:0)
您获得NetworkOnMainThreadException的异常,为了解决它,有两种可能的解决方案:
=&GT; 懒惰解决方案如下:
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()permitAll()建立()。; StrictMode.setThreadPolicy(策略);
=&GT; 标准解决方案:实施AsyncTask
onCreate()
方法中执行该AsyncTask。仅供参考,您无法直接从doInBackground()
方法更新用户界面,如果您想在执行doInBackground()
时更新用户界面,请执行runOnUiThread()
OR
从onPostExecute()
更新用户界面。
答案 3 :(得分:0)
这应该有效
public class Database extends ListActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String url="http://www.mahuwa.com/api/phpserv.php";
new ConnectToServer(this, url, getListView());
}
class ConnectToServer extends AsyncTask<String, Integer, String> {
private ProgressDialog dialog;
Context context;
String url;
ListView lv;
List<String> b = new ArrayList<String>();
ConnectToServer(Context context, String url, ListView lv) {
this.context = context;
this.url = url;
this.lv = lv;
}
@Override
protected void onPreExecute() {
// UI work allowed here
dialog = new ProgressDialog(Database.this);
// setup dialog here
dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
dialog.setMessage("Please Wait...");
dialog.setCancelable(false);
dialog.show();
}
@Override
protected void onPostExecute(String returnVal) {
Sync s = new Sync(Database.this);
try {
dialog.dismiss();
dialog = null;
} catch (Exception e) {
}
try{
JSONArray jArray = new JSONArray(returnVal);
JSONObject json_data=null;
for(int i=0;i<jArray.length();i++)
{
json_data = jArray.getJSONObject(i);
b.add(json_data.getString("Organization"));
}
lv.setAdapter(new ArrayAdapter<String>(context, android.R.layout.simple_list_item_1,b));
}
catch(JSONException e1){
Toast.makeText(getBaseContext(),e1.toString() ,Toast.LENGTH_LONG).show();
} catch (ParseException e1) {
Toast.makeText(getBaseContext(),e1.toString() ,Toast.LENGTH_LONG).show();
}
return;
}
@Override
protected String doInBackground(String... strReq) {
String result = null;
InputStream is = null;
StringBuilder sb = null;
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}
catch(Exception e){
Toast.makeText(getBaseContext(),e.toString() ,Toast.LENGTH_LONG).show();
}
//response to inputstream
try
{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"UTF-8"));
sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
is.close();
result = sb.toString();
}
catch(Exception e)
{
Toast.makeText(getBaseContext(),e.toString() ,Toast.LENGTH_LONG).show();
}
return result;
}
}
}
答案 4 :(得分:0)
String url="http://www.mahuwa.com/api/phpserv.php";
String result = null;
InputStream is = null;
StringBuilder sb = null;
ProgressDialog pd;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
pd = new ProgressDialog(DataBase.this,"Wait..");
new TheTask().execute();
Asynctask类作为活动类的ainner类
class TheTask ends AsyncTask<Void, Void, List> {
protected void onPreExecute()
{
pd.show();
}
@Override
protected List doInBackground(Void... arg0) {
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
List<String> b = new ArrayList<String>();
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"UTF-8"));
sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
is.close();
result = sb.toString();
JSONArray jArray = new JSONArray(result);
JSONObject json_data=null;
for(int i=0;i<jArray.length();i++)
{
json_data = jArray.getJSONObject(i);
b.add(json_data.getString("Organization"));
}
}
catch(Exception e){
e.printStacktrace();
}
return b;
}
protected void onPostExecute(List b)
{
pd.dismiss();
setListAdapter(new ArrayAdapter<String> Database.this, android.R.layout.simple_list_item_1,b));
}
}
有关更多信息,请查看以下链接,尤其是标题为“4个步骤”
下的主题http://developer.android.com/reference/android/os/AsyncTask.html
在ui线程上调用onPreExecute。显示进度对话框
在后台线程上调用doInBackground(param)。不要在这里更新ui
onPostExecute(param)doInBackground()计算的结果是onPostExecute()的参数。关闭进度对话框并在此更新ui。