2016-04-27 2 views
1

Привет, у меня есть это приложение, которое позволяет пользователям регистрироваться в базе данных локального хоста php. 1 ошибка, которую я получаюРегистрация пользователя PHP с Android Studio

«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(); 

} 

} 

, как представляется, проблема на линии 'JSONObject JSONObject = новый JSONObject (сын);'

журнал ошибок

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) 
+0

Разместить свои журналы. –

+0

ok @DevendraSingh – user3041543

+0

Вы правы до 'String method = params [0];', но после того, как вы попытаетесь получить значения для индексов, которые не имеют. поскольку вы передаете в AsynckTask только '. передать список значений ключей. и попробовать. –

ответ

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","[email protected]"); 
new BackgroundTask(url).execute(hashMapValues); 
Смежные вопросы