2016-09-30 45 views
-1

,當我登錄我的應用程序脫機做的是崩潰......並顯示錯誤
Attempt to invoke virtual method 'java.lang.String org.json.JSONObject.getString(java.lang.String)' on a null object reference的Android工作室離線登錄註冊

在網上它工作正常沒有問題,但在離線導致崩潰並不給其中問題,請幫我在這

public class MainActivity extends AppCompatActivity { 

      **// Initializing variables** 
      EditText login; 
      EditText password; 

      String statusRes; 
      String id; 
      String projectName; 
      String loginValue; 
      String stockPoint; 
      JSONObject myRespObject = null; 

      public static final String Passkey = "passKey"; 

      @Override 
      public void onCreate(Bundle savedInstanceState) { 
       super.onCreate(savedInstanceState); 
       setTitle("LOGIN"); 
       setContentView(R.layout.login); 
       login = (EditText) findViewById(R.id.loginname); 
       password = (EditText) findViewById(R.id.Password);  
       final Button saveme = (Button) findViewById(R.id.save);  
       **SharedPreferences sharedpreferences = getSharedPreferences(AppConstants.MyPREFERENCES, Context.MODE_PRIVATE); 
       saveme.setOnClickListener(new Button.OnClickListener() { 
        public URL url; 
        public void onClick(android.view.View v) { 
         if (!CheckNetwork.isInternetAvailable(MainActivity.this){ 
          if (!validate()) { 
           onLoginFailed(); 
           return; 
          } 
SharedPreferences prefs = getSharedPreferences(AppConstants.MyPREFERENCES, Context.MODE_PRIVATE); 
String loginValue = prefs.getString(AppConstants.LOGIN_VALUE, ""); 
String Passkey = prefs.getString(AppConstants.PASS_KEY, ""); 
String Internet = prefs.getString("Internet", "false"); 
String projectName = prefs.getString(AppConstants.PROJECT_NAME, ""); 
String stockPoint = prefs.getString(String.valueOf(AppConstants.STOCK_POINT),""); 
String id = prefs.getString(AppConstants.ID, ""); 
Intent profactivity = new Intent(MainActivity.this, View.class); 
           profactivity.putExtra("Internet", false); 
           profactivity.putExtra("loginValue", loginValue); 
           profactivity.putExtra("id", id); 
       profactivity.putExtra("projectName", projectName); 
           profactivity.putExtra("stockPoint", stockPoint); 
           startActivity(profactivity); 
**Toast.makeText(MainActivity.this, "Offline Login ", Toast.LENGTH_SHORT).show(); 
           finish(); 
          } 

****上面的代碼,這throughing錯誤**

 try { 
final String loginValue = URLEncoder.encode(login.getText().toString(), "UTF-8"); 
final String passValue = URLEncoder.encode(password.getText().toString(), "UTF-8"); 
    try { 
     new Thread(new Runnable() { 
        **//Thread to stop network calls on the UI thread** 
            public void run() { 
             //Request the HTML 
             ArrayList<String> list = null; 
             try { 
String loginValue = URLEncoder.encode(login.getText().toString(), "UTF-8"); 
String passValue = URLEncoder.encode(password.getText().toString(), "UTF-8"); 
String ROOT_URL = getResources().getString(R.string.ROOT_URL) + "/api/v1/user/signIn?loginName=" + loginValue + "&password=" + passValue; 
    Log.i("httpget", "#####@@@@@@#####" + ROOT_URL); 
     HttpClient client = new DefaultHttpClient(); 
     HttpGet request = new HttpGet(ROOT_URL); 
     HttpResponse response = client.execute(request); 
    if (response.getStatusLine().getStatusCode() == 200) { 
    String server_response = EntityUtils.toString(response.getEntity()); 
    myRespObject = new JSONObject(server_response); 
     //Do something with the response 
    //Toast.makeText(getBaseContext(),server_response,Toast.LENGTH_LONG).show(); 
    statusRes = myRespObject.getString("status"); 
       JSONObject respObject = myRespObject.getJSONObject("response"); 
      id = respObject.getString("_id"); 
    AppConstants._ID = id; 
    projectName = respObject.getString("projectName"); 
      Actors actor = new Actors(); 
       list = new ArrayList<>(); 
      JSONArray jsonArray = respObject.getJSONArray("stockPoint"); 
    Intent i = getIntent(); 
     Serializable subject = i.getSerializableExtra("stockPoint"); 
     if (jsonArray != null) { 
    int len = jsonArray.length(); 
      for (int k = 0; k < len; k++) 
       list.add(jsonArray.get(k).toString()); 
               } 
      actor.setStockPoint(list); 
    AppConstants.STOCK_POINT = stockPoint; 
     stockPoint = respObject.getString("stockPoint"); 
              } 
     } catch (UnsupportedEncodingException e) { 
              e.printStackTrace(); 
             } catch (IOException e) { 
              e.printStackTrace(); 
             } catch (JSONException e) { 
              e.printStackTrace(); 
             } 
         final ArrayList<String> finalList = list; 
             runOnUiThread(new Runnable() { 

      @Override 
     public void run() { 
      try { 
      statusRes = myRespObject.getString("status"); 
               } catch (JSONException e) { 
                e.printStackTrace(); 
               } 
    if (statusRes.equalsIgnoreCase("success")) {  
    SharedPreferences sharedpreferences = getSharedPreferences(AppConstants.MyPREFERENCES, Context.MODE_PRIVATE); 
    SharedPreferences.Editor editor = sharedpreferences.edit(); 
      editor.putString(AppConstants.LOGIN_VALUE, loginValue); 
     editor.putString(AppConstants.PASS_KEY, passValue); 
     editor.putString("Internet", "true"); 
     editor.putString(AppConstants.ID, id); 
    editor.putString(AppConstants.PROJECT_NAME, projectName); 
    editor.putString(String.valueOf(AppConstants.STOCK_POINT), String.valueOf(stockPoint)); 
    editor.commit(); 
    **//Here move to next screen or home screen** 
    Intent profactivity = new Intent(MainActivity.this, View.class);            profactivity.putExtra("Internet", true);             profactivity.putExtra("loginValue", loginValue);             profactivity.putExtra("id", id); 
                profactivity.putExtra("projectName", projectName); 
                profactivity.putExtra("stockPoint", finalList); 
    startActivity(profactivity); 
                Toast.makeText(MainActivity.this, "Login Successfully", Toast.LENGTH_LONG).show(); 
    finish(); 
    } else if (statusRes.equalsIgnoreCase("failed")) { 
      if (!validate()) { 
      onLoginFailed(); 
     return; 
     } 
     } 
     } 
}); 
    } 

}).start(); 

    //return data; 
} catch (Exception e) { 
Log.i("httpget", "#####@@@@@@#####Error1 -->" + e.getStackTrace()); 
           **Toast.makeText(getBaseContext(), "ERROR : " + e.getMessage(), Toast.LENGTH_LONG).show();** 
          } 

         } catch (UnsupportedEncodingException ex) { 

          finish(); 
         } 
        } 
       }); 
      } 
      public boolean validate() { 
       boolean valid = true; 

       String email = login.getText().toString(); 
       String passwor = password.getText().toString(); 

       if (email.isEmpty() || email.length() < 2 || email.length() > 10) { 
        login.setError("enter valid username"); 
        valid = false; 
       } else { 
        login.setError("Invalid username"); 
       } 

    if (passwor.isEmpty() || passwor.length() < 2 || passwor.length() > 10) { 
        password.setError("enter valid password"); 
        valid = false; 
       } else { 
        password.setError("Invalid password"); 
       } 

       return valid; 
      } 
      public void onLoginFailed() { 
       **Toast.makeText(getBaseContext(), "Invalid login", Toast.LENGTH_LONG).show();** 

      } 
       } 
-------------------------------------------------------------------------------- 
+0

對不起,我試圖張貼在一個清晰的方式......其實發生了什麼是上面給出的三個部分是代碼,當我試圖在離線登錄它不工作它崩潰請幫助我 – manu

+0

您的JSON對象是空的,你試圖從它得到一個字符串(像這樣'statusRes = myRespObject.getString(「status」)')。你的代碼是不可讀的,如果你可以格式化它將會很好。 –

+0

抱歉,你現在可以試試這個,但是在離線狀態下,api將無法工作,該怎麼辦? – manu

回答

1

您提到的錯誤說明您在以下行中有錯誤。

projectName = respObject.getString(「projectName」);

responseObject」是null,因此你得到NullPointerException

+0

projectName反映正常,在離線狀態下它並不是所有的登錄狀態..登錄後projectname會反映正確..謝謝 – manu