Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
279 views
in Technique[技术] by (71.8m points)

Cannot connect to PHP using android application

Now I was developing an application which requires connection to a database, I tried to connect the android application directly to MYSQL but I failed and alot of people said that I should do it through PHP. So in the mean time I am trying this code to connect to a 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 + "
");
        }
        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;
  }
}

And I call this function (connections()) from another class but it doesn't work and it gives me the following error message

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 

and I added

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

Now it is working using the ASYNC task but when i try

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

i get the following error

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)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Error in http connection android.os.NetworkOnMainThreadException

Above exception state that you are doing network calling on main thread, you have to do it in asynctask or handler. Have a look at below class:

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);
    }

}

Call this asynctask class in onCreate() of activity like below:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...