使用Android Studio注册用户PHP

时间:2016-04-27 17:27:42

标签: java php android

您好我有这个应用程序,允许用户注册到PHP本地主机数据库。我得到的1个错误是

' java.lang.NullPointerException:尝试调用虚方法' int java.lang.String.length()'在空对象引用'

我不知道这意味着什么,任何人都可以帮我解决问题。

我崩溃的代码

public class BackgroundTask extends AsyncTask<String, Void, String> {

String register_url = "https://10.123.1.15/Fitnessplus/register.php";
String login_url = "https://10.123.1.15/Fitnessplus/login.php";

Context ctx;
Activity activity;
ProgressDialog progressDialog;
AlertDialog.Builder builder;

public BackgroundTask(Context ctx) {

    this.ctx = ctx;
    activity = (Activity) ctx;
}

@Override
protected void onPreExecute() {
    builder = new AlertDialog.Builder(activity);
    progressDialog = new ProgressDialog(ctx);
    progressDialog.setTitle("Please wait");
    progressDialog.setMessage("Connecting to server");
    progressDialog.setIndeterminate(true);
    progressDialog.setCancelable(false);
    progressDialog.show();
}
@Override
protected String doInBackground(String... params) {
    String method = params[0];

    if (method.equals("register"))
    {
        try {
            URL url = new URL(register_url);

            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setDoInput(true);
            OutputStream outputStream = httpURLConnection.getOutputStream();
            BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
            String name = params[1];
            String email = params[2];
            String password = params[3];
            String data = URLEncoder.encode("name", "UTF-8") + "=" + URLEncoder.encode(name, "UTF-8") + "&" +
                    URLEncoder.encode("email", "UTF-8") + "=" + URLEncoder.encode(email, "UTF-8") + "&" +
                    URLEncoder.encode("password", "UTF-8") + "=" + URLEncoder.encode(password, "UTF-8");

            bufferedWriter.write(data);
            bufferedWriter.flush();
            bufferedWriter.close();
            outputStream.close();
            InputStream inputStream = httpURLConnection.getInputStream();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            StringBuilder stringBuilder = new StringBuilder();
            String line = "";
            while ((line = bufferedReader.readLine()) != null) {
                stringBuilder.append(line + "\n");
            }
            httpURLConnection.disconnect();
            Thread.sleep(5000);

            return stringBuilder.toString().trim();


        } catch (MalformedURLException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        } catch (InterruptedException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }

    }
    else if (method.equals("login"))
         {
try {
    URL url = new URL(login_url);
    HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
    httpURLConnection.setRequestMethod("POST");
    httpURLConnection.setDoOutput(true);
    httpURLConnection.setDoInput(true);
    OutputStream outputStream = httpURLConnection.getOutputStream();
    BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
    String email,password;
    email = params[1];
    password = params[2];
    String data = URLEncoder.encode("email", "UTF-8") + "=" + URLEncoder.encode(email, "UTF-8") + "&" +
            URLEncoder.encode("password", "UTF-8") + "=" + URLEncoder.encode(password, "UTF-8");

    bufferedWriter.write(data);
    bufferedWriter.flush();
    bufferedWriter.close();
    outputStream.close();

    InputStream inputStream = httpURLConnection.getInputStream();
    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
    StringBuilder stringBuilder = new StringBuilder();
    String line = "";
    while ((line = bufferedReader.readLine()) != null) {
        stringBuilder.append(line + "\n");


    }
    httpURLConnection.disconnect();
    Thread.sleep(5000);
    return stringBuilder.toString().trim();

} catch (MalformedURLException e) {
    e.printStackTrace();
} catch (ProtocolException e) {
    e.printStackTrace();
} catch (UnsupportedEncodingException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
} catch (InterruptedException e) {
    e.printStackTrace();
}
         }
    return null;
}

@Override
protected void onProgressUpdate(Void... values) {
    super.onProgressUpdate(values);
}

@Override
protected void onPostExecute(String json) {

    try {

        progressDialog.dismiss();
        JSONObject jsonObject = new JSONObject(json);
        JSONArray jsonArray = jsonObject.getJSONArray("server_response");
        JSONObject JO = jsonArray.getJSONObject(0);
        String code = JO.getString("code");
        String message = JO.getString("message");
        if (code.equals("reg_true"))
        {
            showDialog("Registration Success", message, code);
        }
        else if(code.equals("reg_false"));
        {
            showDialog("Registration failed", message, code);
        }

        if (code.equals("login_true"))
        {
            Intent intent = new Intent(activity,MainActivity.class);
            intent.putExtra("message",message);
            activity.startActivity(intent);
          }
        else if(code.equals("login_false"))
        {
            showDialog("Login Error",message,code);
        }

    } catch (JSONException e1) {
        e1.printStackTrace();
    }
}

public void showDialog(String title, String message, String code)
{
    builder.setTitle(title);

    if(code.equals("reg_true")|| code.equals("reg_false"))
    {
        builder.setMessage(message);
        builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                activity.finish();
            }
        });

        AlertDialog alertDialog = builder.create();
        alertDialog.show();

    }

    else if (code.equals("login_false")) {
        builder.setMessage(message);
        builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                EditText email,password;
                email = (EditText) activity.findViewById(R.id.email);
                password = (EditText) activity.findViewById(R.id.password);
                email.setText("");
                password.setText("");
                dialog.dismiss();
            }
    });


}

    AlertDialog alertDialog = builder.create();
    alertDialog.show();

}

}

在线上似乎存在问题&#39; JSONObject jsonObject = new JSONObject(son);&#39;

错误日志

04-27 19:25:32.070 7181-7181/com.example.kieranbroom.fitnessproject E/AndroidRuntime: FATAL EXCEPTION: main
                                                                             Process: com.example.kieranbroom.fitnessproject, PID: 7181
                                                                                  java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.String.length()' on a null object reference
                                                                                      at org.json.JSONTokener.nextCleanInternal(JSONTokener.java:116)
                                                                                      at org.json.JSONTokener.nextValue(JSONTokener.java:94)
                                                                                      at org.json.JSONObject.<init>(JSONObject.java:156)
                                                                                      at org.json.JSONObject.<init>(JSONObject.java:173)
                                                                                      at com.example.kieranbroom.fitnessproject.BackgroundTask.onPostExecute(BackgroundTask.java:167)
                                                                                      at com.example.kieranbroom.fitnessproject.BackgroundTask.onPostExecute(BackgroundTask.java:30)
                                                                                      at android.os.AsyncTask.finish(AsyncTask.java:651)
                                                                                      at android.os.AsyncTask.-wrap1(AsyncTask.java)
                                                                                      at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:668)
                                                                                      at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                      at android.os.Looper.loop(Looper.java:148)
                                                                                      at android.app.ActivityThread.main(ActivityThread.java:5417)
                                                                                      at java.lang.reflect.Method.invoke(Native Method)
                                                                                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                                                                                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

1 个答案:

答案 0 :(得分:0)

我正在使用此类从服务器发送和接收数据。

public class ServerConnector {
public final static int GET = 1;
public final static int POST = 2;

public ServerConnector() {

}

public String makeServiceCall(String requestURL, int TYPE) {
    return this.makeServiceCall(requestURL, TYPE, null);
}

public String makeServiceCall(String requestURL, int TYPE, HashMap<String, String> postDataParams) {

    String response = "";
    try {
        URL url;
        url = new URL(requestURL);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setReadTimeout(15000);
        conn.setConnectTimeout(15000);
        if (TYPE == POST) {
            conn.setRequestMethod("POST");
            conn.setDoInput(true);
            conn.setDoOutput(true);
            if (postDataParams != null) {
                OutputStream os = conn.getOutputStream();
                BufferedWriter writer = new BufferedWriter(
                        new OutputStreamWriter(os, "UTF-8"));
                writer.write(getPostDataString(postDataParams));
                writer.flush();
                writer.close();
                os.close();
            }
            int responseCode = conn.getResponseCode();
            if (responseCode == HttpsURLConnection.HTTP_OK) {
                String line;
                BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                while ((line = br.readLine()) != null) {
                    response += line;
                }
            } else {
                response = "";
            }
        } else if (TYPE == GET) {
            conn.setRequestMethod("GET");
            conn.setDoInput(true);
            conn.setDoOutput(true);
            if (postDataParams != null) {
                OutputStream os = conn.getOutputStream();
                BufferedWriter writer = new BufferedWriter(
                        new OutputStreamWriter(os, "UTF-8"));
                writer.write(getPostDataString(postDataParams));
                writer.flush();
                writer.close();
                os.close();
            }
            int responseCode = conn.getResponseCode();
            if (responseCode == HttpsURLConnection.HTTP_OK) {
                String line;
                BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                while ((line = br.readLine()) != null) {
                    response += line;
                    //Log.d("ServerUtility", line);
                }
            } else {
                response ="";

            }

        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    return response;

}

private String getPostDataString(HashMap<String, String> params) throws UnsupportedEncodingException {
    StringBuilder result = new StringBuilder();
    boolean first = true;
    for (Map.Entry<String, String> entry : params.entrySet()) {
        if (first)
            first = false;
        else
            result.append("&");

        result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
        result.append("=");
        result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
    }

    return result.toString();
}


}

keyValuePairList传递给BackgroundTask

public class BackgroundTask extends AsyncTask<HashMap<String, String>, Void, String>{
    .
    .
    .
@Override
    protected String doInBackground(HashMap<String, String>... params) {


    ServerConnector serverConnector = new ServerConnector();
    String response=    serverConnector.makeServiceCall(url, ServerConnector.POST, params[0]);
 return response;
    }

现在打电话

HashMap<String, String> hashMapValues = new HashMap<>();
hashMapValues.add("mail","abcd@gmail.com");
new BackgroundTask(url).execute(hashMapValues);