我在下面使用此代码,它在Android 2.3.3中完美运行。但是,在4.0+中,它无法以某种方式连接到数据库。我看到了一些有关您需要上急课的帖子。我也尝试过,但似乎无法正常工作。我可能用错了,但我很难理解。
public class connector extends Activity { /** Called when the activity is first created. */ TextView txt; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getServerData(null); } //i use my real ip here public String getServerData(String returnString) { System.out.println("going to connector class"); InputStream is = null; final String KEY_121 = "http://10.0.0.128/connector.php"; String result = ""; //the year data to send // ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); // nameValuePairs.add(new BasicNameValuePair("year","1970")); //http post try{ HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(KEY_121); // 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); StringBuilder sb = new StringBuilder(); String line = null; 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()); } //parse json data try{ JSONArray jArray = new JSONArray(result); for(int i=0;i<jArray.length();i++){ JSONObject json_data = jArray.getJSONObject(i); Log.i("log_tag","ID: "+json_data.getInt("ID")+ ", \nActara: "+json_data.getString("Actara") ); //Get an output to the screen returnString += "\n\t" + jArray.getJSONObject(i); } }catch(JSONException e){ Log.e("log_tag", "Error parsing data "+e.toString()); } return returnString; } }
Logcat错误(4.0及更高版本):
11-12 12:02:35.658: E/log_tag(14083): Error in http connection android.os.NetworkOnMainThreadException 11-12 12:02:35.658: E/log_tag(14083): Error converting result java.lang.NullPointerException 11-12 12:02:35.663: E/log_tag(14083): Error parsing data org.json.JSONException: End of input at character 0 of
只有第一个错误行很重要,因为它无法连接到数据库,它给出了nullPointer(第二个和第三个错误)。
这是我在Asynch中尝试过的:
public class connector extends Activity { /** Called when the activity is first created. */ TextView txt; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); new BackgroundAsyncTask().execute(); } public class BackgroundAsyncTask extends AsyncTask<Void, Integer, Void> { InputStream is = null; final String KEY_121 = "http://10.0.0.128/connector.php"; String result = ""; String returnString = ""; protected void onPostExecute(Void result) { } @Override protected void onPreExecute() { System.out.println("onPreExecute"); } protected Void doInBackground(String... params) { try{ System.out.println("background in progress"); HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(KEY_121); // 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); StringBuilder sb = new StringBuilder(); String line = null; 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()); } //parse json data try{ JSONArray jArray = new JSONArray(result); for(int i=0;i<jArray.length();i++){ JSONObject json_data = jArray.getJSONObject(i); Log.i("log_tag","ID: "+json_data.getInt("ID")+ ", \nActara: "+json_data.getString("Actara") ); //Get an output to the screen returnString += "\n\t" + jArray.getJSONObject(i); } }catch(JSONException e){ Log.e("log_tag", "Error parsing data "+e.toString()); } return null; } protected void onProgressUpdate(Integer... values) { } @Override protected Void doInBackground(Void... params) { // TODO Auto-generated method stub return null; } } }
有人可以帮助我吗?我不确定真正的原因是为什么它在4.0+上不起作用。 如果您需要更多信息,请说出来,我将其发布。 代码可能有点混乱,我还没有真正“清理”它。
好的,对了…经过几个小时的搜索,提出了一个问题,然后10分钟后,您找到了解决方案…
选项1: 我添加了以下行:
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); StrictMode.setThreadPolicy(policy);
但是我建议不要使用选项1,这实际上是一个不好的解决方案。使用选项2! // ================================================ =========================== 选项2:
使用本教程制作了正确的ASyncTask:http://www.elvenware.com/charlie/development/android/SimpleHttpGetThread.html
// ================================================ ===========================将 ASyncTask用作最终版本(选项2)。