Android studio离线登录注册
Posted
技术标签:
【中文标题】Android studio离线登录注册【英文标题】:Android studio offline login registration 【发布时间】:2017-02-08 20:30:24 【问题描述】:当我离线登录时,我的应用程序崩溃了...并显示错误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();**
--------------------------------------------------------------------------------
【问题讨论】:
对不起,我试图以清晰的方式发布不信...实际上发生的事情是上面给出的三个部分是我尝试离线登录时的代码它不起作用它正在崩溃请帮帮我 您的 JSON 对象为空,您正试图从中获取字符串(类似于statusRes = myRespObject.getString("status")
)。你的代码不可读,如果你能格式化它会很好。
对不起,你现在可以试试这个吗,哈哈,但是在离线 api 将无法工作,如何做到这一点
离线时,API 将无法工作,因为您的应用无法连接到服务器以验证凭据,因此服务器没有返回任何 JSON 数据进行解析,而将 myRespObject
保留为空值。应用程序崩溃,因为您试图从 myRespObject
获取状态,该状态为空 (Attempt to invoke virtual method ... null object reference
)。
k..我怎样才能阻止这种崩溃你能帮我吗?
【参考方案1】:
您提到的错误表明您在下一行有错误。
projectName = respObject.getString("projectName");
“responseObject
”是null
,因此你得到NullPointerException
。
【讨论】:
项目名称反映正常,离线时根本没有登录。登录后项目名称将反映正确..谢谢以上是关于Android studio离线登录注册的主要内容,如果未能解决你的问题,请参考以下文章
Android Studio-基于SQLLITE实现登录注册功能
Android Studio 实现登录注册-源代码 (连接MySql数据库)
如何在Android Studio上利用云数据库Mysql实现在线登录注册?
Android Studio实现QQ的注册登录和好友列表界面的跳转