2014-04-17 137 views
0

我正在使用此代码从在线数据库加载数据到我的android应用程序。 我想知道我可以添加什么来使此代码更好? 有时进度对话框不停地旋转,永远不会获取数据,应用程序被卡住了,关于如何防止这种情况的任何想法?从在线MySQL数据库加载数据到Android应用程序

class LoadAllSections extends AsyncTask<String, String, String> 
{ 

    // make a progress dialog appear with the selected specifics 
    @Override 
    protected void onPreExecute() { 
     super.onPreExecute(); 
     pDialog = new ProgressDialog(MainActivity.this); 
     pDialog.setMessage("Loading all sections, please wait"); 
     pDialog.setIndeterminate(false); 
     pDialog.setCancelable(false); 
     pDialog.show(); 
    } 

    // in the background run this code to retrieve data from the server 
    protected String doInBackground(String... args) 
    { 
     List<NameValuePair> params = new ArrayList<NameValuePair>(); 

     JSONObject json = jParser.makeHttpRequest(url_Sections,"POST", params); 
     try 
     { 
      int success = json.getInt(TAG_SUCCESS); 
      sections = json.getJSONArray(TAG_SECTIONS); 

      if (success == 1) 
      { 
       for (int i = 0; i < sections.length(); i++) 
       { 
        JSONObject c = sections.getJSONObject(i); 

        section_id = c.getString(TAG_SECTION_ID); 
        section_name = c.getString(TAG_SECTION_NAME); 
        section_desc = c.getString(TAG_SECTION_DESC); 
        section_image = c.getString(TAG_SECTION_IMAGE); 
        section_valid = c.getString(TAG_SECTION_VALID);  

        HashMap <String,String> sectionmap = new HashMap<String,String>(); 

        sectionmap.put(TAG_SECTION_ID, section_id); 
        sectionmap.put(TAG_SECTION_NAME, section_name); 
        sectionmap.put(TAG_SECTION_DESC, section_desc); 
        sectionmap.put(TAG_SECTION_IMAGE, section_image); 
        sectionmap.put(TAG_SECTION_VALID, section_valid); 

        sectionlist.add(sectionmap); 
       } 
      } 
      else 
      { 
      finish(); 
      } 
     } 
     catch (JSONException e) 
     { 
      e.printStackTrace(); 
     } 
     return null; 
    } 

    // disable the progress dialog and load data to the gridview 
    protected void onPostExecute(String file_url) 
    { 
     pDialog.dismiss(); 
     adapter=new SectionAdapter(MainActivity.this,sectionlist); 
     SectionsGridView.setAdapter(adapter); 
    } 
} 
+0

这段代码没有办法工作......你在问“从在线MySQL数据库加载数据到android应用程序”并发送一个“POST”?我会看看这应该如何工作? –

回答

0

我想添加评论,但我不允许。 没有足够的声誉:-(

  • 通URL_SECTION作为参数,而不是doInBackground使其成为全球的。
  • 我会放置的HttpRequest insde一个try catch块。
  • 你有没有设置超时如果HttpRequest中不回答?我会设置到 60秒。我觉得它默认设置为600秒。
  • 为什么你传递给FILE_URL代替onPostExecute经过 sectionList的?
  • 看看AsyncTask。如果你不想在方法之间传递任何东西,你也可以使用Void。所以在你的情况下AsyncTask也会这样做。
+0

谢谢...我会检查所有上述建议,并会回到你...我相对较新的Java机器人,所以我可能需要一些帮助编码你建议。 – Jasser

+0

我把httprequest里面的try catch块...... 我该如何设置超时?任何方向? – Jasser

+0

和我可以调用整个类,它会执行onPreExecute和doInBackground和onPostExecute ....我怎样才能控制传递给每个?我以为我只能调用类LoadAllSections? – Jasser

相关问题