Android远程服务器和mySql应用程序无法正常工作。空指针异常

时间:2014-09-08 10:07:18

标签: php android mysql json remote-server

我正在尝试创建一个简单的应用程序,允许用户注册用户名和密码,然后使用该用户名和密码登录。我已经创建了一个Apache服务器和一个MySql数据库但是当我在手机上运行应用程序并尝试使用用户名和密码登录时,我已经手动添加到数据库中,需要永久尝试登录和然后最终崩溃。我使用PHP脚本来解析JSON数据。下面是我的java代码以及我的logcat我没有看到发布php脚本的重点,因为我不认为它们是问题,因为如果我尝试使用php脚本从我的计算机浏览器登录它的工作原理精细。请帮帮我。

MainActivity

package com.example.mysqltest;

import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

public class MainActivity extends Activity implements OnClickListener{

private EditText user, pass;
private Button mSubmit, mRegister;
private ImageView imageView;

 // Progress Dialog
private ProgressDialog pDialog;

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

//php login script location:

//localhost :
//testing on your device
//put your local ip instead,  on windows, run CMD > ipconfig
//or in mac's terminal type ifconfig and look for the ip under en0 or en1
// private static final String LOGIN_URL = "http://xxx.xxx.x.x:1234/webservice/login.php";

//testing on Emulator:
private static final String LOGIN_URL = "http://10.0.0.106:80/webservice/login.php";

//testing from a real server:
//private static final String LOGIN_URL = "http://www.yourdomain.com/webservice/login.php";

//JSON element ids from repsonse of php script:
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    //setup input fields
    user = (EditText)findViewById(R.id.username);
    pass = (EditText)findViewById(R.id.password);

    //setup buttons
    mSubmit = (Button)findViewById(R.id.login);
    mRegister = (Button)findViewById(R.id.register);

    imageView = (ImageView) findViewById(R.id.imageView1);


    //register listeners
    mSubmit.setOnClickListener(this);
    mRegister.setOnClickListener(this);

}

@Override
public void onClick(View v) {
    // TODO Auto-generated method stub
    switch (v.getId()) {
    case R.id.login:
            new AttemptLogin().execute();
        break;
    case R.id.register:
            Intent i = new Intent(this, Register.class);
            startActivity(i);
        break;

    default:
        break;
    }
}

class AttemptLogin extends AsyncTask<String, String, String> {

     /**
     * Before starting background thread Show Progress Dialog
     * */
    boolean failure = false;

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(MainActivity.this);
        pDialog.setMessage("Attempting login...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(true);
        pDialog.show();
    }

    @Override
    protected String doInBackground(String... args) {
        // TODO Auto-generated method stub
         // Check for success tag
        int success;
        String username = user.getText().toString();
        String password = pass.getText().toString();
        try {
            // Building Parameters
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("username", username));
            params.add(new BasicNameValuePair("password", password));

            Log.d("request!", "starting");
            // getting product details by making HTTP request
            JSONObject json = jsonParser.makeHttpRequest(
                   LOGIN_URL, "POST", params);

            // check your log for json response
            Log.d("Login attempt", json.toString());

            // json success tag
                success = json.getInt(TAG_SUCCESS);
                if (success == 1) {
                    Log.d("Login Successful!", json.toString());
                                    // save user data
                    SharedPreferences sp =  
PreferenceManager.getDefaultSharedPreferences(MainActivity.this);
                    Editor edit = sp.edit();
                    edit.putString("username", username);
                    edit.commit();

                Log.d("Login Successful!", json.toString());
                Intent i = new Intent(MainActivity.this, ReadComments.class);
                finish();
                startActivity(i);
                return json.getString(TAG_MESSAGE);
            }else{
                Log.d("Login Failure!", json.getString(TAG_MESSAGE));
                return json.getString(TAG_MESSAGE);

            }
        } 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 product deleted
        pDialog.dismiss();
        if (file_url != null){
            Toast.makeText(MainActivity.this, file_url, Toast.LENGTH_LONG).show();
        }

    }

}

}

JSON Parser

package com.example.mysqltest;

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() {

}


public JSONObject getJSONFromUrl(final String url) {

    // Making HTTP request
    try {
        // Construct the client and the HTTP request.
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);

        // Execute the POST request and store the response locally.
        HttpResponse httpResponse = httpClient.execute(httpPost);
        // Extract data from the response.
        HttpEntity httpEntity = httpResponse.getEntity();
        // Open an inputStream with the data content.
        is = httpEntity.getContent();

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

    try {
        // Create a BufferedReader to parse through the inputStream.
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                is, "iso-8859-1"), 8);
        // Declare a string builder to help with the parsing.
        StringBuilder sb = new StringBuilder();
        // Declare a string to store the JSON object data in string form.
        String line = null;

        // Build the string until null.
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }

        // Close the input stream.
        is.close();
        // Convert the string builder data to an actual string.
        json = sb.toString();
    } catch (Exception e) {
        Log.e("Buffer Error", "Error converting result " + e.toString());
    }

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

    // Return the JSON Object.
    return jObj;

}


// 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 == "POST"){
            // request method is POST
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);
            httpPost.setEntity(new UrlEncodedFormEntity(params));

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

        }else 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 {
        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();
        json = sb.toString();
    } catch (Exception e) {
        Log.e("Buffer Error", "Error converting result " + e.toString());
    }

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

    // return JSON String
    return jObj;

}
}

注册和登录活动有同样的问题,所以我没有看到添加注册活动的重点。如果你真的需要我添加php脚本,我将是她的

logcat的

    09-08 11:45:02.765: I/Process(22450): Sending signal. PID: 22450 SIG: 9
09-08 11:45:47.730: D/libEGL(23410): loaded /system/lib/egl/libEGL_mali.so
09-08 11:45:47.735: D/libEGL(23410): loaded /system/lib/egl/libGLESv1_CM_mali.so
09-08 11:45:47.740: D/libEGL(23410): loaded /system/lib/egl/libGLESv2_mali.so
09-08 11:45:47.745: E/(23410): Device driver API match
09-08 11:45:47.745: E/(23410): Device driver API version: 23
09-08 11:45:47.745: E/(23410): User space API version: 23 
09-08 11:45:47.745: E/(23410): mali: REVISION=Linux-r3p2-01rel3 BUILD_DATE=Wed Oct  9 21:05:57   
KST 2013 
09-08 11:45:47.830: D/OpenGLRenderer(23410): Enabling debug mode 0
09-08 11:45:47.895: W/IInputConnectionWrapper(23410): showStatusIcon on inactive InputConnection
09-08 11:46:03.700: D/ProgressBar(23410): setProgress = 0
09-08 11:46:03.700: D/ProgressBar(23410): setProgress = 0, fromUser = false
09-08 11:46:03.700: D/ProgressBar(23410): mProgress = 0mIndeterminate = false, mMin = 0, mMax =   
10000
09-08 11:46:03.755: D/dalvikvm(23410): GC_FOR_ALLOC freed 282K, 14% free 9800K/11316K, paused 
23ms, total 29ms
09-08 11:46:03.755: I/dalvikvm-heap(23410): Grow heap (frag case) to 11.844MB for 1127536-byte 
allocation
09-08 11:46:03.775: D/dalvikvm(23410): GC_FOR_ALLOC freed 14K, 13% free 10887K/12420K, paused  
21ms, total 21ms
09-08 11:46:03.815: D/request!(23410): starting
09-08 11:46:03.855: D/ProgressBar(23410): updateDrawableBounds: left = 0
09-08 11:46:03.855: D/ProgressBar(23410): updateDrawableBounds: top = 0
09-08 11:46:03.855: D/ProgressBar(23410): updateDrawableBounds: right = 96
09-08 11:46:03.855: D/ProgressBar(23410): updateDrawableBounds: bottom = 96
09-08 11:48:22.855: D/dalvikvm(23410): GC_FOR_ALLOC freed 440K, 14% free 10959K/12628K, paused 
30ms, total 30ms
09-08 11:49:13.445: W/System.err(23410): org.apache.http.conn.HttpHostConnectException: 
Connection to http://10.0.0.106:80 refused
09-08 11:49:13.450: W/System.err(23410):    at  

09-08 11:49:13.450: W/System.err(23410):    at  
org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
09-08 11:49:13.450: W/System.err(23410):    at  
org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
09-08 11:49:13.450: W/System.err(23410):    at 
org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
09-08 11:49:13.455: W/System.err(23410):    at  
org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:670)
09-08 11:49:13.455: W/System.err(23410):    at 
org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:509)
09-08 11:49:13.455: W/System.err(23410):    at 
org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
09-08 11:49:13.455: W/System.err(23410):    at 
com.example.mysqltest.JSONParser.makeHttpRequest(JSONParser.java:110)
09-08 11:49:13.460: W/System.err(23410):    at 
com.example.mysqltest.MainActivity$AttemptLogin.doInBackground(MainActivity.java:133)
09-08 11:49:13.460: W/System.err(23410):    at 
com.example.mysqltest.MainActivity$AttemptLogin.doInBackground(MainActivity.java:1)
09-08 11:49:13.460: W/System.err(23410):    at android.os.AsyncTask$2.call(AsyncTask.java:287)
09-08 11:49:13.460: W/System.err(23410):    at 
java.util.concurrent.FutureTask.run(FutureTask.java:234)
09-08 11:49:13.460: W/System.err(23410):    at   
android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
09-08 11:49:13.460: W/System.err(23410):    at    
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
09-08 11:49:13.460: W/System.err(23410):    at 
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
09-08 11:49:13.460: W/System.err(23410):    at java.lang.Thread.run(Thread.java:841)
09-08 11:49:13.465: W/System.err(23410): Caused by: java.net.ConnectException: failed to connect   
to /10.0.0.106 (port 80): connect failed: ETIMEDOUT (Connection timed out)
09-08 11:49:13.470: W/System.err(23410):    at libcore.io.IoBridge.connect(IoBridge.java:114)
09-08 11:49:13.470: W/System.err(23410):    at   
java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
09-08 11:49:13.470: W/System.err(23410):    at 
java.net.PlainSocketImpl.connect(PlainSocketImpl.java:459)
09-08 11:49:13.470: W/System.err(23410):    at java.net.Socket.connect(Socket.java:842)
09-08 11:49:13.475: W/System.err(23410):    at 
org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:119)
09-08 11:49:13.475: W/System.err(23410):    at 
09-08 11:49:13.475: W/System.err(23410):    ... 15 more
09-08 11:49:13.475: W/System.err(23410): Caused by: libcore.io.ErrnoException: connect failed:    
ETIMEDOUT (Connection timed out)
09-08 11:49:13.475: W/System.err(23410):    at libcore.io.Posix.connect(Native Method)
09-08 11:49:13.475: W/System.err(23410):    at 
libcore.io.BlockGuardOs.connect(BlockGuardOs.java:85)
09-08 11:49:13.480: W/System.err(23410):    at 
libcore.io.IoBridge.connectErrno(IoBridge.java:127)
09-08 11:49:13.480: W/System.err(23410):    at libcore.io.IoBridge.connect(IoBridge.java:112)
09-08 11:49:13.480: W/System.err(23410):    ... 20 more
09-08 11:49:13.480: E/Buffer Error(23410): Error converting result 
java.lang.NullPointerException:    
lock == null
09-08 11:49:13.480: E/JSON Parser(23410): Error parsing data org.json.JSONException: End of input 
at   
character 0 of 
09-08 11:49:13.480: W/dalvikvm(23410): threadid=11: thread exiting with uncaught exception  
(group=0x41c26700)
09-08 11:49:13.490: E/AndroidRuntime(23410): FATAL EXCEPTION: AsyncTask #1
09-08 11:49:13.490: E/AndroidRuntime(23410): java.lang.RuntimeException: An error occured while   
executing doInBackground()
09-08 11:49:13.490: E/AndroidRuntime(23410):    at 
android.os.AsyncTask$3.done(AsyncTask.java:299)
09-08 11:49:13.490: E/AndroidRuntime(23410):    at   
java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
09-08 11:49:13.490: E/AndroidRuntime(23410):    at 
java.util.concurrent.FutureTask.setException(FutureTask.java:219)
09-08 11:49:13.490: E/AndroidRuntime(23410):    at 
java.util.concurrent.FutureTask.run(FutureTask.java:239)
09-08 11:49:13.490: E/AndroidRuntime(23410):    at   
android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
09-08 11:49:13.490: E/AndroidRuntime(23410):    at 
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
09-08 11:49:13.490: E/AndroidRuntime(23410):    at 
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
09-08 11:49:13.490: E/AndroidRuntime(23410):    at java.lang.Thread.run(Thread.java:841)
09-08 11:49:13.490: E/AndroidRuntime(23410): Caused by: java.lang.NullPointerException
09-08 11:49:13.490: E/AndroidRuntime(23410):    at 
com.example.mysqltest.MainActivity$AttemptLogin.doInBackground(MainActivity.java:137)
09-08 11:49:13.490: E/AndroidRuntime(23410):    at 
com.example.mysqltest.MainActivity$AttemptLogin.doInBackground(MainActivity.java:1)
09-08 11:49:13.490: E/AndroidRuntime(23410):    at 
android.os.AsyncTask$2.call(AsyncTask.java:287)
09-08 11:49:13.490: E/AndroidRuntime(23410):    at   
java.util.concurrent.FutureTask.run(FutureTask.java:234)
09-08 11:49:13.490: E/AndroidRuntime(23410):    ... 4 more
09-08 11:49:22.300: I/Choreographer(23410): Skipped 508 frames!  The application may be doing too   
much work on its main thread.
09-08 11:49:22.500: W/IInputConnectionWrapper(23410): showStatusIcon on inactive InputConnection
09-08 11:49:22.650: E/WindowManager(23410): Activity com.example.mysqltest.MainActivity has 
leaked  
window com.android.internal.policy.impl.PhoneWindow$DecorView{426fbb68 V.E..... R......D 0,0- 
684,192}   
that was originally added here
09-08 11:49:22.650: E/WindowManager(23410): android.view.WindowLeaked: Activity 
com.example.mysqltest.MainActivity has leaked window    
com.android.internal.policy.impl.PhoneWindow$DecorView{426fbb68 V.E..... R......D 0,0-684,192}   
that   
was originally added here
09-08 11:49:22.650: E/WindowManager(23410):     at android.view.ViewRootImpl.<init>  
(ViewRootImpl.java:452)
09-08 11:49:22.650: E/WindowManager(23410):     at 
android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:258)
09-08 11:49:22.650: E/WindowManager(23410):     at   
android.view.WindowManagerImpl.addView(WindowManagerImpl.java:73)
09-08 11:49:22.650: E/WindowManager(23410):     at android.app.Dialog.show(Dialog.java:287)
09-08 11:49:22.650: E/WindowManager(23410):     at 
com.example.mysqltest.MainActivity$AttemptLogin.onPreExecute(MainActivity.java:115)
09-08 11:49:22.650: E/WindowManager(23410):     at   
android.os.AsyncTask.executeOnExecutor(AsyncTask.java:586)
09-08 11:49:22.650: E/WindowManager(23410):     at 
android.os.AsyncTask.execute(AsyncTask.java:534)
09-08 11:49:22.650: E/WindowManager(23410):     at 
com.example.mysqltest.MainActivity.onClick(MainActivity.java:89)
09-08 11:49:22.650: E/WindowManager(23410):     at android.view.View.performClick(View.java:4475)
09-08 11:49:22.650: E/WindowManager(23410):     at    
android.view.View$PerformClick.run(View.java:18786)
09-08 11:49:22.650: E/WindowManager(23410):     at  
android.os.Handler.handleCallback(Handler.java:730)
09-08 11:49:22.650: E/WindowManager(23410):     at    
android.os.Handler.dispatchMessage(Handler.java:92)
09-08 11:49:22.650: E/WindowManager(23410):     at android.os.Looper.loop(Looper.java:176)
09-08 11:49:22.650: E/WindowManager(23410):     at 
android.app.ActivityThread.main(ActivityThread.java:5419)
09-08 11:49:22.650: E/WindowManager(23410):     at java.lang.reflect.Method.invokeNative(Native    
Method)
09-08 11:49:22.650: E/WindowManager(23410):     at   
java.lang.reflect.Method.invoke(Method.java:525)
09-08 11:49:22.650: E/WindowManager(23410):     at 
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1046)
09-08 11:49:22.650: E/WindowManager(23410):     at     
com.android.internal.os.ZygoteInit.main(ZygoteInit.java:862)
09-08 11:49:22.650: E/WindowManager(23410):     at dalvik.system.NativeStart.main(Native Method)

0 个答案:

没有答案