2014-02-13 3 views
0

У меня есть приложение для Android, которое срабатывает при каждом нажатии кнопки «Вход»; Я продолжаю получать исключение Null Pointer в моем JSONParser. Я действительно надеюсь, что ты сможешь помочь.NullPointerException в Android JSONParser

Вот мой UserFunctions.java:

package com.example.sabre9.library; 

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

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

import android.content.Context; 

public class UserFunctions { 

    private JSONParser jsonParser; 

    // Testing in localhost using wamp or xampp 
    // use http://10.0.2.2/ to connect to your localhost ie http://localhost/ 
    private static String loginURL = "http://10.0.2.2/Sabre1/"; 
    //private static String registerURL = "http://10.0.2.2/Sabre1/"; 

    private static String login_tag = "login"; 
    //private static String register_tag = "register"; 

    // constructor 
    public UserFunctions(){ 
     jsonParser = new JSONParser(); 
    } 

    /** 
    * function make Login Request 
    * @param email 
    * @param password 
    * */ 
    public JSONObject loginUser(String email, String password){ 
     // Building Parameters 
     List<NameValuePair> params = new ArrayList<NameValuePair>(); 
     params.add(new BasicNameValuePair("tag", login_tag)); 
     params.add(new BasicNameValuePair("email", email)); 
     params.add(new BasicNameValuePair("password", password)); 
     JSONObject json = jsonParser.makeHttpRequest(loginURL, "POST", params); 
     // return json 
     // Log.e("JSON", json.toString()); 
     return json; 
    } 

    /** 
    * function make Register Request 
    * @param name 
    * @param email 
    * @param password 
    * */ 
    /* 
    public JSONObject registerUser(String name, String email, String password){ 
     // Building Parameters 
     List<NameValuePair> params = new ArrayList<NameValuePair>(); 
     params.add(new BasicNameValuePair("tag", register_tag)); 
     params.add(new BasicNameValuePair("name", name)); 
     params.add(new BasicNameValuePair("email", email)); 
     params.add(new BasicNameValuePair("password", password)); 


     //getting JSON Object 
     JSONObject json = jsonParser.makeHttpRequest(registerURL, "POST", params); 
     // return json 
     return json; 
    }*/ 

    /** 
    * Function get Login status 
    **/ 
    public boolean isUserLoggedIn(Context context){ 
     DatabaseHandler db = new DatabaseHandler(context); 
     int count = db.getRowCount(); 
     if(count > 0){ 
      // user logged in 
      return true; 
     } 
     return false; 
    } 

    /** 
    * Function to logout user 
    * Reset Database 
    * */ 
    public boolean logoutUser(Context context){ 
     DatabaseHandler db = new DatabaseHandler(context); 
     db.resetTables(); 
     return true; 
    } 
} 

JSONParser.java:

package com.example.sabre9.library; 
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 == "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; 

     } 
} 

А вот мои ошибки LogCat:

02-13 03:15:01.921: E/Buffer Error(1263): Error converting result java.lang.NullPointerException: lock == null 
02-13 03:15:01.931: E/JSON Parser(1263): Error parsing data org.json.JSONException: End of input at character 0 of 
02-13 03:15:02.891: E/Buffer Error(1263): Error converting result java.lang.NullPointerException: lock == null 
02-13 03:15:02.891: E/JSON Parser(1263): Error parsing data org.json.JSONException: End of input at character 0 of 

Edit: Мой LoginActivity.java:

package com.example.sabre9; 

import org.json.JSONException; 
import org.json.JSONObject; 

import android.app.Activity; 
import android.content.Intent; 
import android.os.AsyncTask; 
import android.os.Bundle; 
import android.view.View; 
import android.widget.Button; 
import android.widget.EditText; 
import android.widget.TextView; 

import com.example.sabre9.library.DatabaseHandler; 
import com.example.sabre9.library.UserFunctions; 

public class LoginActivity extends Activity { 
    Button btnLogin; 
    //Button btnLinkToRegister; 
    EditText inputEmail; 
    EditText inputPassword; 
    TextView loginErrorMsg; 

    // JSON Response node names 
    private static String KEY_SUCCESS = "success"; 
    //private static String KEY_ERROR = "error"; 
    //private static String KEY_ERROR_MSG = "error_msg"; 
    private static String KEY_UID = "uid"; 
    private static String KEY_NAME = "name"; 
    private static String KEY_EMAIL = "email"; 
    private static String KEY_CREATED_AT = "created_at"; 

    private class MyAsyncTask extends AsyncTask<String, Void, JSONObject> { 

     protected JSONObject doInBackground(String... params) { 
       UserFunctions userFunction = new UserFunctions(); 
       if (params.length != 2) 
         return null; 
       JSONObject json = userFunction.loginUser(params[0], params[1]); 
       return json; 
     } 

     protected void onPostExecute(JSONObject json) { 
       try { 
      if (json != null && json.getString(KEY_SUCCESS) != null) { 
       loginErrorMsg.setText(""); 
       String res = json.getString(KEY_SUCCESS); 
       if(Integer.parseInt(res) == 1){ 
        // user successfully logged in 
        // Store user details in SQLite Database 
        DatabaseHandler db = new DatabaseHandler(getApplicationContext()); 
        JSONObject json_user = json.getJSONObject("user"); 

        // Clear all previous From in database 
        UserFunctions userFunction = new UserFunctions(); 
        userFunction.logoutUser(getApplicationContext()); 
        db.addUser(json_user.getString(KEY_NAME), json_user.getString(KEY_EMAIL), json.getString(KEY_UID), json_user.getString(KEY_CREATED_AT));       

        // Launch Main Screen 
        Intent main = new Intent(getApplicationContext(), MainActivity.class); 

        // Close all views before launching Dashboard 
        main.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
        startActivity(main); 

        // Close Login Screen 
        finish(); 
       }else{ 
        // Error in login 
        loginErrorMsg.setText("Incorrect username/password"); 
       } 
      } 
     } catch (JSONException e) { 
      e.printStackTrace(); 
     } 
     } 
} 

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

     // Importing all assets like buttons, text fields 
     inputEmail = (EditText) findViewById(R.id.loginEmail); 
     inputPassword = (EditText) findViewById(R.id.loginPassword); 
     btnLogin = (Button) findViewById(R.id.btnLogin); 
     //btnLinkToRegister = (Button) findViewById(R.id.btnLinkToRegisterScreen); 
     loginErrorMsg = (TextView) findViewById(R.id.login_error); 

     // Login button Click Event 
     btnLogin.setOnClickListener(new View.OnClickListener() { 

      public void onClick(View view) { 
       String email = inputEmail.getText().toString(); 
       String password = inputPassword.getText().toString();     
       new MyAsyncTask().execute(email, password); 
      } 

     }); 

     //Link to Register Screen 
     /*btnLinkToRegister.setOnClickListener(new View.OnClickListener() { 

      public void onClick(View view) { 
       Intent i = new Intent(getApplicationContext(), 
         RegisterActivity.class); 
       startActivity(i); 
       finish(); 
      } 
     });*/ 
    } 
} 
+2

Если бы вы могли сказать нам, где происходит исключение, это было бы здорово. –

+0

Когда вы получаете исключение, попробуйте использовать «Log.e (tag, message, throwable)», чтобы получить трассировку стека исключений, написанных в LogCat. – PaF

+0

Если бы я действительно мог сказать, я бы это сделал. Дело в том, что я не могу. Эти записи являются единственными в моем logcat. –

ответ

1

Происходит java.lang.NullPointerException: lock == null> = Android 3.0, потому что в главном (UI) потоке не разрешено сетевое взаимодействие, если не переопределено с помощью политики StrictMode. Попробуйте:

StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); 
StrictMode.setThreadPolicy(policy); 

Обратите внимание, что в результате httpClient.execute(httpPost); зависнет систему довольно плохой, как она ожидает ответа. (Вместо этого вы можете сделать это в AsyncTask, чтобы он не блокировал основной поток.) ​​Надеюсь, это поможет.

+0

** StrictMode ** может использовать только для сетевой оперативной ошибки. Это не правильный путь. Потому что вы не можете использовать его в своем живом приложении. Он может просто избежать ошибки, связанной с сетью. – Piyush

+0

Я отредактировал свое сообщение, чтобы включить код для моего входа в систему. Любая идея о том, куда лучше всего вставить код, который вы предоставили? Здесь также указывается моя AsyncTask. –

0

Я исправил эту ошибку. Кажется, что из-за очень смущающего мозгового пердуна я забыл включить в свой файл манифеста необходимые интернет-разрешения. Кроме того, я немного изменил свои php-файлы. Спасибо за ответы в любом случае :)