【问题标题】:implementing AsyncTask实现 AsyncTask
【发布时间】:2023-03-07 18:15:01
【问题描述】:

我如何使用 asynctask 来实现它。我已经尝试了很多不起作用的方法。现在我只是减少构建版本以允许在主线程上进行网络操作。 我想做的是从我托管的 php 脚本中检索数据并填充列表视图。一些帮助将不胜感激: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();
    }


}

【问题讨论】:

    标签: android json android-listview android-asynctask


    【解决方案1】:

    试试这个

    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】:

      在你的 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;
      }
      

      【讨论】:

        【解决方案3】:

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

        => 惰性解决方案如下:

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

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

        步骤/提示如下:

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

          onPostExecute() 更新用户界面。

        【讨论】:

          【解决方案4】:

          这应该可以工作

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

          【讨论】:

            【解决方案5】:
                  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));
            }
               }
            

            有关更多信息,请查看下面的链接,尤其是标题下的主题 The 4 steps

            http://developer.android.com/reference/android/os/AsyncTask.html

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

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

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

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2016-07-03
              • 2014-12-23
              • 2014-04-20
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多