0

How do i implement this using asynctask. i have tried lots of ways that wont work. for now im just reducing the build version to allow network operations on the main thread. what i want to do is retrieve data from a php script that ive hosted and populate the listview. Some help would be highly appreciated :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();
    }


}
4

5 回答 5

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();
    }
}

}

于 2013-05-06T07:03:15.380 回答
0

您收到 NetworkOnMainThreadException 的异常,有两种可能的解决方案来解决它:

=>惰性解决方案如下:

StrictMode.ThreadPolicy 策略 = new StrictMode.ThreadPolicy.Builder().permitAll().build(); StrictMode.setThreadPolicy(policy);

=>标准解决方案:实现 AsyncTask

步骤/提示如下:

  • 直接的方法包括网络和 AsyncTask 内部长时间运行的调用,然后在onCreate()方法内部执行该 AsyncTask。
  • 仅供参考,您不能doInBackground()直接从方法更新 UI,是的,如果您想在执行doInBackground()任何操作时更新 UI,然后执行runOnUiThread()

    或者

    从 更新用户界面onPostExecute()

于 2013-05-06T07:05:03.947 回答
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;
        }
    }
}
于 2013-05-06T07:11:13.173 回答
0

把它写在你的 oncreate 方法中,这里 rssFeed 是你传递的 url。

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;
}
于 2013-05-06T06:58:34.933 回答
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 类作为活动类的内部类

   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

onPreExecute 在 ui 线程上调用。显示进度对话框

doInBackground(param) 在后台线程上调用。不要在这里更新ui

onPostExecute(param) doInBackground() 计算的结果是 onPostExecute() 的参数。关闭进度对话框并在此处更新 ui。

于 2013-05-06T07:14:17.570 回答