问题描述
我用这个code以下,它完美的安卓2.3.3。然而,在4.0+它不能连接到数据库,不知何故。我看到一些帖子你需要把它在一个异步类。我也试过,但我不能似乎它的工作。我大概用错了,但我很难理解。
I use this code below, it works perfectly in Android 2.3.3. However, in 4.0+ it can't connect to database somehow. I saw some posts about you need to get it in a asynch class. I also tried that, but I can't seems it to work. I probably use it wrong, but it is hard for me to understand.
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 +):
Logcat error (on 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
只有第一个错误行是很重要的,因为它不能连接到一个数据库,它提供了一个空指针(第2和第3的错误)。
Only the first error line is important, because it can't connect to a database, it gives a nullPointer (2nd and 3rd error).
这是我尝试在非同步:
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+什么。
如果您需要更多的信息,只是说,我将它张贴。
code可以是一个有点乱,我真的不干净起来还正常。
Someone that can help me? I don't know for sure what the real cause is why it isn't working for 4.0+.
If you need more info, just say it, and I will post it.
Code can be a bit messy, I didn't really "clean" it up yet properly.
推荐答案
好了吧...10多分钟后寻找几个小时,使得这个问题,那么以后,你找到一个解决方案...
Ok right...After searching for few hours, making this question, then 10 minutes later, you find a solution...
选项1:
我说这行:
Option 1:
I added this line:
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
不过,我建议不要使用选项1,这是真正的一个坏的解决方案。使用选项2!
// ================================================ ===========================
选项2:
But I reccomend NOT to use option 1, this is a bad solution for real. Use option 2!
//===========================================================================
Option 2:
用于本教程作出正确的AsyncTask:HTTP://www.elvenware .COM /查理/开发/安卓/ SimpleHttpGetThread.html
// ============================================= ==============================
二手AsyncTask的作为最终(选项2)。
//===========================================================================
Used ASyncTask as final (option 2).
这篇关于HttpClient的(phpMyAdmin的)不工作在Android 4.0+的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!