Android studio离线登录注册

时间:2016-09-30 09:46:54

标签: java android json eclipse import

当我进行离线登录时,我的应用程序正在崩溃...并显示错误
Attempt to invoke virtual method 'java.lang.String org.json.JSONObject.getString(java.lang.String)' on a null object reference

在网上它工作正常没有问题,但在离线状态下崩溃根本没有给出问题的地方请帮助我

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

****对于上面的代码,这里是通过错误**

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

            }
              }
--------------------------------------------------------------------------------

1 个答案:

答案 0 :(得分:1)

您提到的错误表示您在以下行中有错误。

projectName = respObject.getString(&#34; projectName&#34;);

&#34; responseObject&#34;是null,因此您获得NullPointerException