简体   繁体   English

httpclient(phpmyadmin)在Android 4.0+上不起作用

[英]httpclient (phpmyadmin) not working on Android 4.0+

I use this code below, it works perfectly in Android 2.3.3. 我在下面使用此代码,它在Android 2.3.3中完美运行。 However, in 4.0+ it can't connect to database somehow. 但是,在4.0+中,它无法以某种方式连接到数据库。 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 error (on 4.0+): 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 

Only the first error line is important, because it can't connect to a database, it gives a nullPointer (2nd and 3rd error). 只有第一个错误行很重要,因为它无法连接到数据库,它给出了nullPointer(第二个和第三个错误)。

This is what I tried in Asynch: 这是我在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;
        }

    }

}

Someone that can help me? 有人可以帮助我吗? I don't know for sure what the real cause is why it isn't working for 4.0+. 我不确定真正的原因是为什么它在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. 代码可能有点混乱,我还没有真正“清理”它。

Since Android 3.0 you are not allowed to do network stuff on the main thread. 从Android 3.0开始,您不允许在主线程上进行网络操作。 Why? 为什么? because network problems will lead to a slow ui. 因为网络问题会导致ui变慢。 So you have to do all the http stuff in a new thread. 因此,您必须在一个新线程中完成所有http工作。 You are on the right path but you made a mistake in your AsyncTask. 您走在正确的道路上,但是您在AsyncTask中犯了一个错误。 Delete the empty doInBackground method in you async task and write @Override over your method. 删除异步任务中的空doInBackground方法,并在方法上写入@Override。

Ok right... After searching for few hours, making this question, then 10 minutes later, you find a solution... 好的,对了...经过几个小时的搜索,提出了一个问题,然后10分钟后,您找到了解决方案...

Option 1: 选项1:
I added this line: 我添加了这一行:

 StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
 StrictMode.setThreadPolicy(policy);

But I reccomend NOT to use option 1, this is a bad solution for real. 但是我建议不要使用选项1,这实际上是一个不好的解决方案。 Use option 2! 使用选项2!
//=========================================================================== // ================================================ ===========================
Option 2: 选项2:

Used this tutorial to make a proper ASyncTask: http://www.elvenware.com/charlie/development/android/SimpleHttpGetThread.html 使用本教程制作了正确的ASyncTask:http://www.elvenware.com/charlie/development/android/SimpleHttpGetThread.html

//=========================================================================== // ================================================ ===========================
Used ASyncTask as final (option 2). 将ASyncTask用作最终版本(选项2)。

android.os.NetworkOnMainThreadException android.os.NetworkOnMainThreadException

this eror comes With HoneyComb(3.0 or Later). 此错误随附HoneyComb(3.0或更高版本)。 you can not perform a networking operation on its main thread as documentation says. 如文档所述,您不能在其主线程上执行联网操作。 to getting ride of this you must use handler or asynctask. 要使用此功能,您必须使用处理程序或asynctask。 AFAIK There is no another way to do it. AFAIK没有其他方法可以做到。

you can See this for More Details WHY ICS Crashes your App 您可以查看此以了解更多详细信息为什么ICS会导致您的应用崩溃

Try Using Below Code Snippet 尝试使用以下代码段

new Thread(){
    public void run(){
        //do your Code Here    
    }
}.start();

为什么在Web连接和Web服务的功能中传递null

getServerData(null);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在Android 4.0+上的PostgreSQL中使用Hibernate或替代品 - Using Hibernate or alternative with PostgreSQL on Android 4.0+ Android 4.0+ EditText禁用自动更正 - Android 4.0+ EditText disable autocorrection 如何在Android 4.0+设备上以编程方式禁用“窗口动画比例”? - How to disable “Window animation scale” programmatically on Android 4.0+ devices? Android 4.0版中的外部SD卡路径读取文件 - External SD card path in android version 4.0+ to read files Android - MediaPlayer即使在Android 4.0+上准备流之前就准备好了 - Android - MediaPlayer's on Prepare Called even before the stream is prepared on Android 4.0+ 为什么在Android 4.0+上支持v7 actionbar进入屏幕底部 - Why support v7 actionbar goes to screen bottom on android 4.0+ 如何检查自动旋转屏幕设置是否在 Android 4.0+ 中打开/关闭 - How to check if auto-rotate screen setting is ON/OFF in Android 4.0+ Apache HttpClient 4.0无法在Android上的套接字超时 - Apache HttpClient 4.0 failing to timeout for socket on Android 如何从Android 4.0中的HttpClient获取响应 - How to Get Response From HttpClient in Android 4.0 如何在4.0+上更改Edittext下划线的颜色? - How change color of the underline of Edittext on 4.0+?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM