我目前正在创建一个允许用户使用 Web API 登录的应用程序。在检查API的响应时,我没有收到任何错误。
{"error":0,"data":[{"id":"2","driver_name":"Test Driver","driver_lat":"","driver_long":"","driver_mobile_no":"9164618545","driver_password":"202cb962ac59075b964b07152d234b70","driver_token":"bef1032495ef4b2c891795fce1fa16c2","driver_image":"","is_active":"1","on_duty":"0","t_drivers":"0","created_at":"2017-07-04 06:38:22","last_activity_at":"2017-07-04 09:19:08"}],"msg":"Login Successfully."}
但是在使用该应用程序时,它不会转到主活动。 这是登录类:-
public class login extends AppCompatActivity {
private Button login1;
Session session;
private ConstraintLayout mRootLayout;
boolean doubleBackToExitPressedOnce = false;
boolean status = false;
EditText mEdtEmail , mEdtPassword ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Fabric.with(this, new Answers(), new Crashlytics());
setContentView(R.layout.activity_login);
login1 = (Button) findViewById(R.id.button);
mEdtEmail = (EditText) findViewById(R.id.phone_number);
mEdtPassword = (EditText) findViewById(R.id.password);
session = new Session(login.this);
if (session.isLoggedIn()) {
// User is already logged in. Take him to main activity
Intent intent = new Intent(login.this, MainActivity.class);
startActivity(intent);
finish();
}
// sign_in();
login1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String mobile = mEdtEmail.getText().toString().trim();
String password = mEdtPassword.getText().toString().trim();
status = checkInternetConnection();
if (status) {
if (mobile.length() == 0) {
mEdtEmail.setError("Required");
} else if (mobile.length() < 10) {
mEdtEmail.setError("Mobile no must be 10 char. long");
} else if (password.length() == 0) {
mEdtPassword.setError("Required");
} else {
new UserLoginTask(mobile, password, login.this).execute();
}
}
else
{
Snackbar.make(mRootLayout, "You don't have Internet connection!", Snackbar.LENGTH_LONG).show();
// Toast.makeText(getApplicationContext(), "You don't have Internet connection", Toast.LENGTH_LONG).show();
}
}
});
}
private class UserLoginTask extends AsyncTask<String, Void, String> {
private String mUserName;
private String mPassword;
String msg ;
ProgressDialog progressDialog;
Boolean loginStatus = false;
private Activity activity;
public static final String MyPREFERENCES = "MyPrefs" ;
SharedPreferences sharedpreferences;
UserLoginTask(String userName, String password, Activity activity) {
mUserName = userName;
mPassword = password;
this.activity = activity;
}
@Override
protected void onPreExecute() {
progressDialog= ProgressDialog.show(login.this, "Loading. . .","Please Wait. . .", true);
Toast.makeText(login.this,"toast 1",Toast.LENGTH_SHORT).show();
super.onPreExecute();
}
@Override
protected String doInBackground(String... params) {
try {
String result= WebService.postHttpResponse(mUserName, mPassword, activity);
JSONObject jsonObject = new JSONObject(result);
// Log.d("Json Array", "doInBackground: "+jsonObject);
String status = jsonObject.optString("error");
// msg = jsonObject.optString("msg");
// Toast.makeText(login.this,"toast 2",Toast.LENGTH_SHORT).show();
if(status.equals("0")){
loginStatus = true ;
session.setLogin(true);
JSONArray jsonarray = jsonObject.getJSONArray("data");
JSONObject jsonObject1=jsonarray.getJSONObject(0);
status = jsonObject1.getString("msg");
Log.e("DRIVER NAME -----" ,jsonObject1.getString("driver_name"));
Driver driver = new Driver();
driver.setId(jsonObject1.getString("id"));
driver.setDriver_name(jsonObject1.getString("driver_name"));
driver.setDriver_lat(jsonObject1.getString("driver_lat"));
driver.setDriver_long(jsonObject1.getString("driver_long"));
driver.setDriver_mobile_no(jsonObject1.getString("driver_mobile_no"));
driver.setDriver_token(jsonObject1.getString("driver_token"));
driver.setCreated_at(jsonObject1.getString("created_at"));
driver.setLast_activity_at(jsonObject1.getString("last_activity_at"));
sharedpreferences = activity.getSharedPreferences("MY" , Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString("driver_name",jsonObject1.getString("driver_name"));
editor.putString("driver_mobile_no", jsonObject1.getString("driver_mobile_no"));
editor.putString("id", jsonObject1.getString("id"));
editor.putString("driver_token", jsonObject1.getString("driver_token"));
editor.putString("driver_image", jsonObject1.getString("driver_image"));
editor.putString("current_order_no", "");
editor.commit();
startActivity(intent);
activity.startActivity(new Intent(activity, MainActivity.class).putExtra("driver_obj" , driver));
overridePendingTransition(R.anim.right_in, R.anim.left_out);
finish();
}
else {
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return msg ;
}
@Override
protected void onPostExecute(String msg) {
super.onPostExecute(msg);
progressDialog.dismiss();
Toast.makeText(activity , msg , Toast.LENGTH_LONG).show();
}
}
/*public void sign_in(){
login1=(Button)findViewById(R.id.button);
login1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(login.this,"Welcome!", Toast.LENGTH_SHORT).show();
startActivity(intent);
}
});
}*/
@Override
public void onBackPressed() {
if (doubleBackToExitPressedOnce){
super.onBackPressed();
return;
}
this.doubleBackToExitPressedOnce = true ;
Toast.makeText(this , "Please click BACK again to exit" , Toast.LENGTH_SHORT).show();
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
doubleBackToExitPressedOnce = false ;
}
}, 2000);
/*Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish();
System.exit(0);*/
}
public boolean checkInternetConnection()
{
ConnectivityManager connectivity = (ConnectivityManager)getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity != null)
{
NetworkInfo[] inf = connectivity.getAllNetworkInfo();
if (inf != null)
for (int i = 0; i < inf.length; i++)
if (inf[i].getState() == NetworkInfo.State.CONNECTED)
{
return true;
}
}
return false;
}
}
请帮忙! 谢谢!!
编辑1:非常感谢!我已经得到了解决方案。这是我的一个非常小的错误!
您的jsonObject1.getString("msg");
没有任何msg
{"error":0,"data":[{"id":"2",.....}],"msg":"Login Successfully."}
// ` ^^^^^ part of jsonObject`
|_____________|
| first json object which has no msg key/value pair
|________________|
| jsonarray
|_______________________________________________________________|
|
JSONObject jsonObject = new JSONObject(result);
// response object
String status = jsonObject.optString("error");
// response json contains error , so far so good
..
..
JSONArray jsonarray = jsonObject.getJSONArray("data");
// get the jsonarray
JSONObject jsonObject1=jsonarray.getJSONObject(0);
// get first object
status = jsonObject1.getString("msg");
// there is no msg string in jsonObject1 hence error
所以使用
jsonObject.optString("msg");
注意:显然您要启动两次MainActivity
,因此请从后台线程上运行doInBackground
中删除一个,因此don't do this
Intent intent = new Intent("oodi_design.driver4.Activity.MainActivity");
startActivity(intent);
activity.startActivity(new Intent(activity, MainActivity.class).putExtra("driver_obj" , driver));
从onPostExecute
开始您的活动
在这里,您从服务器获得JSONObject
响应。
此对象包含三个值:
error
data
msg
error
包含integer
格式的错误代码。
data
包含包含驱动程序详细信息的JSONArray
。
msg
包含String
格式的消息。
所以你需要写
JSONObject jsonObject = new JSONObject(result);
int code = jsonObject.getString("error");
if (code == 0) {
JSONArray jsonarray = jsonObject.getJSONArray("data");
JSONObject data = jsonarray.getJSONObject(0);
String msg = jsonObject.getString("msg");
driver = new Driver();
...
}
并将其从doInBackground
方法中删除
Intent intent = new Intent("oodi_design.driver4.Activity.MainActivity");
startActivity(intent);
activity.startActivity(new Intent(activity, MainActivity.class).putExtra("driver_obj" , driver));
overridePendingTransition(R.anim.right_in, R.anim.left_out);
finish();
并在显示Toast
后onPostExecute
方法中编写此代码
...
activity.startActivity(new Intent(activity, MainActivity.class).putExtra("driver_obj" , driver));
overridePendingTransition(R.anim.right_in, R.anim.left_out);
finish();
...
您需要在UserLoginTask
ProgressDialog
喜欢之后声明Driver
...
ProgressDialog progressDialog;
Driver driver;
从你附加的JSONObject
来看,似乎JSONObject
包含two
字符串(error
和msg
(和一个名为data
的JSONArray
。
因此,您必须按如下方式解析此 JSON 数据:
.........
..............
String result = WebService.postHttpResponse(mUserName, mPassword, activity);
JSONObject jsonObject = new JSONObject(result);
// ERROR & STATUS
String status = jsonObject.optString("error");
String msg = jsonObject.optString("msg");
// DATA
JSONArray jsonArrayData = jsonObject.getJSONArray("data");
// First DATA JSONObject
JSONObject jsonObject1 = jsonArrayData.getJSONObject(0);
........
..............
要启动MainActivity
,请在onPostExecute()
中使用以下代码:
@Override
protected void onPostExecute() {
Intent intent = new Intent(login.this, MainActivity.class);
intent.putExtra("driver_obj" , driver); // driver should be declared as global in `UserLoginTask` class.
activity.startActivity(intent);
overridePendingTransition(R.anim.right_in, R.anim.left_out);
finish();
}
希望这会有所帮助~