无法使用Android应用程序连接到PHP

时间:2014-04-23 09:31:40

标签: php android

现在我正在开发一个需要连接到数据库的应用程序,我试图将android应用程序直接连接到MYSQL,但我失败了,很多人说我应该通过PHP来实现。所以在同一时间我尝试将此代码连接到PHP。

package com.climacon.androidapp;



import java.io.BufferedReader;
import java.io.InputStream;

import java.io.InputStreamReader;


import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

public class Phpmysql {
  public static JSONObject connections (String url) {
    InputStream is = null;
    String result = "";
    JSONObject jArray = null;

    // Download JSON data from URL
    try {
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("http://192.168.1.20/Project/");
        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());
    }

    try {

        jArray = new JSONObject(result);
    } catch (JSONException e) {
        Log.e("log_tag", "Error parsing data " + e.toString());
    }

    return jArray;
  }
}

我从另一个类调用此函数(connections())但它没有工作,它给我以下错误消息

Error in http connection android.os.NetworkOnMainThreadException
Error converting result java.lang.NullPointerException: lock == null
Error parsing data org.json.JSONException: End of input at character 0 of 

我加了

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

现在它正在使用ASYNC任务,但是当我尝试

NNode node = null;
node.set_temp(jObject.length());    
value4.setText(String.valueOf(tempprogress))

我收到以下错误

E/JSON Parser(3336): Error parsing data org.json.JSONException: Value <!DOCTYPE of type     java.lang.String cannot be converted to JSONObject
E/ActivityManager(714): App crashed! Process: com.climacon.androidapp
E/AndroidRuntime(3336): FATAL EXCEPTION: main
E/AndroidRuntime(3336): Process: com.climacon.androidapp, PID: 3336
E/AndroidRuntime(3336): java.lang.NullPointerException
E/AndroidRuntime(3336):     at   com.climacon.androidapp.climatemonitor$ConnectToPHP.onPostExecute(climatemonitor.java:83)
E/AndroidRuntime(3336):     at com.climacon.androidapp.climatemonitor$ConnectToPHP.onPostExecute(climatemonitor.java:1)
E/AndroidRuntime(3336):     at android.os.AsyncTask.finish(AsyncTask.java:632)
E/AndroidRuntime(3336):     at android.os.AsyncTask.access$600(AsyncTask.java:177)
E/AndroidRuntime(3336):     at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
E/AndroidRuntime(3336):     at android.os.Handler.dispatchMessage(Handler.java:102)
E/AndroidRuntime(3336):     at android.os.Looper.loop(Looper.java:157)
E/AndroidRuntime(3336):     at android.app.ActivityThread.main(ActivityThread.java:5872)
E/AndroidRuntime(3336):     at java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime(3336):     at java.lang.reflect.Method.invoke(Method.java:515)
E/AndroidRuntime(3336):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1069)
E/AndroidRuntime(3336):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:885)
E/AndroidRuntime(3336):     at dalvik.system.NativeStart.main(Native Method)

2 个答案:

答案 0 :(得分:0)

你必须在不同的主题而不是主要主题上运行。

class DownloadJson extends AsyncTask<String, Void, RSSFeed> {

    private Exception exception;

    protected DownloadJson doInBackground(String... urls) {
       // Get Json here
    }
}

或在onCreate()中添加:

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

使用以上作为临时解决方案。否则使用线程或asynctask。

答案 1 :(得分:0)

Error in http connection android.os.NetworkOnMainThreadException

以上异常表明您正在主线程上进行网络调用,您必须在asynctaskhandler中执行此操作。看看下面的课程:

class ConnectToPHP extends AsyncTask<String, String, String>
{
    @Override
    protected void onPreExecute()
    {
        // TODO Auto-generated method stub
        // show progress dialog here
        super.onPreExecute();
    }

    @Override
    protected String doInBackground(String... params)
    {
       // TODO Auto-generated method stub
       JSONObject jObject = Phpmysql.connections(params[0]);
       System.out.println(jObject.toString());
       // do your code here
       return null;
    }

    @Override
    protected void onPostExecute(String result)
    {
        // TODO Auto-generated method stub
        // dismiss progress dialog here
        super.onPostExecute(result);
    }

}

在以下asynctask活动中调用此onCreate()课程:

String my_url = "192.168.1.20/Project/index.php";
new ConnectToPHP.execute(my_url);