给php和mysql连接android给出了错误

时间:2014-02-08 09:18:37

标签: php android mysql json error-handling

系统出错

的logcat

02-08 09:39:41.565: D/libEGL(1649): loaded /system/lib/egl/libEGL_genymotion.so
02-08 09:39:41.573: D/(1649): HostConnection::get() New Host Connection established 0xb83e1f58, tid 1649
02-08 09:39:41.609: D/libEGL(1649): loaded /system/lib/egl/libGLESv1_CM_genymotion.so
02-08 09:39:41.617: D/libEGL(1649): loaded /system/lib/egl/libGLESv2_genymotion.so
02-08 09:39:41.741: W/EGL_genymotion(1649): eglSurfaceAttrib not implemented
02-08 09:39:41.745: E/OpenGLRenderer(1649): Getting MAX_TEXTURE_SIZE from GradienCache
02-08 09:39:41.761: E/OpenGLRenderer(1649): Getting MAX_TEXTURE_SIZE from Caches::initConstraints()
02-08 09:39:41.761: D/OpenGLRenderer(1649): Enabling debug mode 0
02-08 09:39:41.765: W/ViewRootImpl(1649): Dropping event due to no window focus: KeyEvent { action=ACTION_DOWN, keyCode=KEYCODE_ALT_RIGHT, scanCode=100, metaState=META_ALT_ON|META_ALT_RIGHT_ON, flags=0x8, repeatCount=25570, eventTime=1610364, downTime=303014, deviceId=1, source=0x301 }
02-08 09:39:50.617: W/EGL_genymotion(1649): eglSurfaceAttrib not implemented
02-08 09:39:50.637: D/dalvikvm(1649): GC_FOR_ALLOC freed 191K, 2% free 16859K/17072K, paused 11ms, total 11ms
02-08 09:39:50.837: W/INbUFFERED Reader(1649): before  the buffered reader beguin
02-08 09:39:50.841: W/INbUFFERED Reader(1649): before  the Parsing beguin
02-08 09:39:50.845: E/JSON Parser(1649): Error parsing data org.json.JSONException: Value Array()Array( of type java.lang.String cannot be converted to JSONObject
02-08 09:39:50.849: W/dalvikvm(1649): threadid=16: thread exiting with uncaught exception (group=0xa4c10648)
02-08 09:39:50.849: E/AndroidRuntime(1649): FATAL EXCEPTION: AsyncTask #5
02-08 09:39:50.849: E/AndroidRuntime(1649): java.lang.RuntimeException: An error occured while executing doInBackground()
02-08 09:39:50.849: E/AndroidRuntime(1649):     at android.os.AsyncTask$3.done(AsyncTask.java:299)
02-08 09:39:50.849: E/AndroidRuntime(1649):     at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
02-08 09:39:50.849: E/AndroidRuntime(1649):     at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
02-08 09:39:50.849: E/AndroidRuntime(1649):     at java.util.concurrent.FutureTask.run(FutureTask.java:239)
02-08 09:39:50.849: E/AndroidRuntime(1649):     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
02-08 09:39:50.849: E/AndroidRuntime(1649):     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
02-08 09:39:50.849: E/AndroidRuntime(1649):     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
02-08 09:39:50.849: E/AndroidRuntime(1649):     at java.lang.Thread.run(Thread.java:841)
02-08 09:39:50.849: E/AndroidRuntime(1649): Caused by: java.lang.NullPointerException
02-08 09:39:50.849: E/AndroidRuntime(1649):     at pack.coderzheaven.AndroidPHPConnectionDemo$CheckLogin.doInBackground(AndroidPHPConnectionDemo.java:126)
02-08 09:39:50.849: E/AndroidRuntime(1649):     at pack.coderzheaven.AndroidPHPConnectionDemo$CheckLogin.doInBackground(AndroidPHPConnectionDemo.java:1)
02-08 09:39:50.849: E/AndroidRuntime(1649):     at android.os.AsyncTask$2.call(AsyncTask.java:287)
02-08 09:39:50.849: E/AndroidRuntime(1649):     at java.util.concurrent.FutureTask.run(FutureTask.java:234)
02-08 09:39:50.849: E/AndroidRuntime(1649):     ... 4 more
02-08 09:39:52.021: E/WindowManager(1649): Activity pack.coderzheaven.AndroidPHPConnectionDemo has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{52e427e0 V.E..... R......D 0,0-1026,288} that was originally added here
02-08 09:39:52.021: E/WindowManager(1649): android.view.WindowLeaked: Activity pack.coderzheaven.AndroidPHPConnectionDemo has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{52e427e0 V.E..... R......D 0,0-1026,288} that was originally added here
02-08 09:39:52.021: E/WindowManager(1649):  at android.view.ViewRootImpl.<init>(ViewRootImpl.java:345)
02-08 09:39:52.021: E/WindowManager(1649):  at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:239)
02-08 09:39:52.021: E/WindowManager(1649):  at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
02-08 09:39:52.021: E/WindowManager(1649):  at android.app.Dialog.show(Dialog.java:281)
02-08 09:39:52.021: E/WindowManager(1649):  at pack.coderzheaven.AndroidPHPConnectionDemo$CheckLogin.onPreExecute(AndroidPHPConnectionDemo.java:97)
02-08 09:39:52.021: E/WindowManager(1649):  at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:586)
02-08 09:39:52.021: E/WindowManager(1649):  at android.os.AsyncTask.execute(AsyncTask.java:534)
02-08 09:39:52.021: E/WindowManager(1649):  at pack.coderzheaven.AndroidPHPConnectionDemo$1.onClick(AndroidPHPConnectionDemo.java:74)
02-08 09:39:52.021: E/WindowManager(1649):  at android.view.View.performClick(View.java:4240)
02-08 09:39:52.021: E/WindowManager(1649):  at android.view.View$PerformClick.run(View.java:17721)
02-08 09:39:52.021: E/WindowManager(1649):  at android.os.Handler.handleCallback(Handler.java:730)
02-08 09:39:52.021: E/WindowManager(1649):  at android.os.Handler.dispatchMessage(Handler.java:92)
02-08 09:39:52.021: E/WindowManager(1649):  at android.os.Looper.loop(Looper.java:137)
02-08 09:39:52.021: E/WindowManager(1649):  at android.app.ActivityThread.main(ActivityThread.java:5103)
02-08 09:39:52.021: E/WindowManager(1649):  at java.lang.reflect.Method.invokeNative(Native Method)
02-08 09:39:52.021: E/WindowManager(1649):  at java.lang.reflect.Method.invoke(Method.java:525)
02-08 09:39:52.021: E/WindowManager(1649):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
02-08 09:39:52.021: E/WindowManager(1649):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
02-08 09:39:52.021: E/WindowManager(1649):  at dalvik.system.NativeStart.main(Native Method)
02-08 09:39:52.349: I/Process(1649): Sending signal. PID: 1649 SIG: 9

这是将与数据库连接并将响应作为json返回到android系统的php文件

我认为错误是在php文件中,但我不知道如何解决它。

所以如果有人能帮助我,我会很感激。

check.php

<?php

require_once('db_config.php'); 


// array for JSON response
$response = array();




  if(isset($_GET['pid'])){


     $pid = $_GET['pid'];   



     $query_search = "select * from members where id = '".$pid."'";  

     $query_exec = mysql_query($query_search) or die(mysql_error());

   if (mysql_num_rows($query_exec)>0) 
   {
        $result = mysql_fetch_array($query_exec);

        $person = array();
        $response["pid"]=$result["id"];
        $person["username"]=$result["user_name"];
        $person["password"]=$result["password"];


    //echo $person[0];
   print_r($response);

   // success
        $response["success"] = 1;

   // user node
        $response["person"] = array();

        array_push($response["person"], $person);

   // echoing JSON response
        echo json_encode($response);

    }
    else
    {


    print_r($response);

//  echo $response[0];
   // no user found
            $response["success"] = 0;
            $response["message"] = "No User found";

  print_r($response);       
//          echo $response["person"];
   // echo no users JSON
           echo json_encode($response);
    }
}
else 
{
    // required field is missing
    $response["success"] = 0;
    $response["message"] = "Required field(s) are missing";

    // echoing JSON response
    echo json_encode($response);
}    
?>

JSONParser.java

package pack.coderzheaven;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

public class JSONParser {

    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";

    // constructor
    public JSONParser() {

    }

    // function get json from url
    // by making HTTP POST or GET mehtod
    public JSONObject makeHttpRequest(String url, String method,
            List<NameValuePair> params) {

        // Making HTTP request
        try {

            // check for request method


            if (method == "GET") {
                // request method is GET
                DefaultHttpClient httpClient = new DefaultHttpClient();
                String paramString = URLEncodedUtils.format(params, "utf-8");
                url += "?" + paramString;
                HttpGet httpGet = new HttpGet(url);

                HttpResponse httpResponse = httpClient.execute(httpGet);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();
            }

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {

            Log.w("INbUFFERED Reader", "before  the buffered reader beguin");
            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();

            json = sb.toString().substring(0, sb.toString().length() - 1);
            json = sb.toString();
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }

        // try parse the string to a JSON object
        try {
            Log.w("INbUFFERED Reader", "before  the Parsing beguin");
            jObj = new JSONObject(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

        // return JSON String
        return jObj;

    }
}

AndroidPHPConnectionDemo.java

package pack.coderzheaven;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class AndroidPHPConnectionDemo extends Activity {
    Button b;
    EditText et, pass;
    String Username, Password;
    TextView tv;
    HttpPost httppost;
    StringBuffer buffer;
    HttpResponse response;
    HttpClient httpclient;
    List<NameValuePair> nameValuePairs;

    String pid;

    // Progress Dialog
    private ProgressDialog pDialog;

    // JSON parser class
    JSONParser jsonParser = new JSONParser();


    private static final String url_check_login = "http://10.0.3.2/check.php";

    // JSON Node names
    private static final String TAG_SUCCESS = "success";
    private static final String TAG_PERSON = "person";
    private static final String TAG_PID = "pid";
    private static final String TAG_NAME = "username";
    private static final String TAG_pass = "password";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        b = (Button) findViewById(R.id.Button01);
        et = (EditText) findViewById(R.id.username);
        pass = (EditText) findViewById(R.id.password);
        tv = (TextView) findViewById(R.id.tv);

        b.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {

                // Getting complete person details in background thread
                new CheckLogin().execute();

            }
        });
    }

    /**
     * Background Async Task to Get complete person details
     * */
    class CheckLogin extends AsyncTask<String, String, String> {

        JSONArray productObj;

        /**
         * Before starting background thread Show Progress Dialog
         * */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(AndroidPHPConnectionDemo.this);
            pDialog.setMessage("Loading person details. Please wait...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();
        }

        /**
         * Getting person details in background thread
         * */

        @Override
        protected String doInBackground(String... arg0) {

            // updating UI from Background Thread

            // Check for success tag
            int success;
            try {
                // Building Parameters
                List<NameValuePair> params = new ArrayList<NameValuePair>();
                params.add(new BasicNameValuePair("pid", pid));

                // getting person details by making HTTP request
                // Note that person details url will use GET request
                JSONObject json = jsonParser.makeHttpRequest(url_check_login,
                        "GET", params);

//Log.e("JsonObject", json.toString());
// check your log for json response
// Log.d("Single person Details", json.toString());

                // json success tag
                success = json.getInt(TAG_SUCCESS);
                if (success == 1) {
                    // successfully received person details
                    productObj = json.getJSONArray(TAG_PERSON); // JSON Array

                }

                else {
                    // product with pid not found
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

            return null;
        }

        /**
         * After completing background task Dismiss the progress dialog
         * **/
        protected void onPostExecute(String file_url) {
            // dismiss the dialog once got all details
            if (productObj != null) {
                try {
                    // get first product object from JSON Array
                    JSONObject person = productObj.getJSONObject(0);

                    et.setText(person.getString(TAG_NAME));
                    pass.setText(person.getString(TAG_pass));

                    Log.e("success in login", "SUCCESS IN LOGIN");

                } catch (Exception e) {

                    e.printStackTrace();
                }

            }

            pDialog.dismiss();
        }
    }

}

1 个答案:

答案 0 :(得分:0)

Print_r输出将在JSON数据之前附加,因此结果将是不正确的JSON字符串。

只需删除print_r或将其更改为

error_log(print_r($ response,true));

将调试信息发送到服务器错误日志而不是客户端。