我試圖使用json進行登錄。我的php返回這個結果:如何修復Android工作室中的登錄錯誤
[{"name":"cynthia","password":"123456"},{"name":"John","password":"123456"}]
這些是mySQL中的數據。
,我想利用這個結果在機器人工作室的比較,但我發現它不工作。它總是去到else語句。
public class LoginActivity extends AppCompatActivity {
public EditText username;
public EditText password;
private ArrayList<String> usernameList = new ArrayList<String>();
private ArrayList<String> passwordList = new ArrayList<String>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
username = (EditText) findViewById(R.id.username);
password = (EditText) findViewById(R.id.password);
}
public void Login2(View view) {
if (username.getText().length() == 0 || password.getText().length() == 0) {
openDialog(view);
} else {
new AsyncRetrieve().execute();
if(usernameList.contains(username)&&passwordList.contains(password)){
successLogin();
}else{
openDialog(view);
}
}
}
public void openDialog(View view) {
new AlertDialog.Builder(this)
.setTitle(R.string.login_dialog_title)
.setMessage(R.string.login_dialog_msg)
.show();
}
public void successLogin() {
Intent intent = new Intent();
intent.setClass(this, HomePageActivity.class);
startActivity(intent);
}
private class AsyncRetrieve extends AsyncTask<Void, Void, String> {
@Override
protected String doInBackground(Void... params) {
return getVideoList();
}
private String getVideoList() {
try {
URL url = new URL("http://localhost/soften/login_check1.php");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
InputStream in = new BufferedInputStream(conn.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String response = reader.readLine();
//set the response from server as json array
JSONArray userArray = new JSONArray(response);
usernameList.clear();
passwordList.clear();
Log.d("username", "value = " + userArray.length());
for (int i = 0; i < userArray.length(); i++) {
Log.d("i", "i = " + i);
//get json object from the json array
JSONObject json = userArray.getJSONObject(i);
Log.d("json", "" + json.length());
//add object to the list for grid view
usernameList.add(json.getString("name"));
passwordList.add(json.getString("password"));
}
return null;
} catch (Exception ex) {
return ex.toString();
}
}
}
}
這似乎是一個非常不安全的方法,除非你保護你的端點。將所有用戶的詳細信息從數據庫下載到手機進行登錄似乎是一種矯枉過正的行爲。 –