2013-08-27 18 views
0

以下代码无法连接到SQLiteAndroid应用程序错误与我的代码

public class MainActivity extends ListActivity { 

    JSONArray jArray; String result = null; InputStream is = null; 
    StringBuilder sb=null; 

    @Override public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 

     ArrayList<NameValuePair> nameValuePairs = new 
     ArrayList<NameValuePair>(); //http post 
     try{ 
      HttpClient httpclient = new DefaultHttpClient(); 
      HttpPost httppost = new HttpPost("http://xxx.xxx.xxx.xxx/"); 
      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 Ravid_id; 
     String Ravid_Name; 
     try{ 
      jArray = new JSONArray(result); 
      JSONObject json_data=null; 
      for(int i=0;i<jArray.length();i++){ 
       json_data = jArray.getJSONObject(i); 
       Ravid_id=json_data.getInt("Ravid_id"); 
       Ravid_Name=json_data.getString("Ravid_Name"); 
      } 
     } catch(JSONException e1){ 
      Toast.makeText(getBaseContext(), "No found" ,Toast.LENGTH_LONG).show(); 
     } catch (ParseException e1) { 
      e1.printStackTrace(); 
     } 
    } 
} 
+0

你可以发布显示错误的日志输出吗? – Ben

回答

0

这只是一个猜测和相关的经常帐问题:你不应该在主线程上执行任何网络操作。此代码...

HttpClient httpclient = new DefaultHttpClient(); 
HttpPost httppost = new HttpPost("http://xxx.xxx.xxx.xxx/"); 
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 
HttpResponse response = httpclient.execute(httppost); 
HttpEntity entity = response.getEntity(); 

...应该是放置在AsncTaskService。有关如何解决此问题的示例,请参见this post(通常为android.os.NetworkOnMainThreadException)。

相关问题