【发布时间】:2014-09-23 15:13:08
【问题描述】:
自从我上次尝试申请以来已经太久了,在我的一生中,我自己似乎无法得到答案。我需要让用户在登录时在我的应用程序中输入密码和用户名,我想通过在 PHP Myadmin 中搜索数据库来做到这一点。
我的代码已经达到了(我认为)应该接近完成的水平,但逻辑却让我无法理解。
我需要计算 if 语句来比较用户通过 JSONArray 输入到数据库的用户名和密码,此外,如果代码无论如何都不起作用,将不胜感激:)
if 语句标有 ----> 我知道我需要某种形式的 for 循环来筛选和比较值,但这是我从未处理过的事情。
这是我的登录屏幕的代码:
public class HomeScreen extends Activity implements OnClickListener {
private ProgressDialog m_ProgressDialog = null;
EditText editText1;
EditText editText2;
String clear1;
String user;
String password;
URL url;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home_screen);
View loginBTN = findViewById(R.id.button1);
loginBTN.setOnClickListener(this);
editText1=(EditText)findViewById(R.id.editText1);
editText2=(EditText)findViewById(R.id.editText2);
clear1 ="";
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.home_screen, menu);
return true;
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.button1:
user = editText1.getText().toString();
password = editText2.getText().toString();
if ( editText1 != null && editText1.length() != 0 && editText2 != null && editText2.length() != 0){
getData();
m_ProgressDialog = ProgressDialog.show(HomeScreen.this,
"Please wait...", "Checking Details...", true);
m_ProgressDialog.setCancelable(true);
if(testData()) {
Intent i = new Intent(this, Afterlog.class);
startActivity(i);
}
else{
Toast.makeText(HomeScreen.this, "The username and password did not match any in our database...", Toast.LENGTH_SHORT).show();
}
}
else {
Toast.makeText(HomeScreen.this, "Please enter a user name AND a password...", Toast.LENGTH_SHORT).show();
}
break;
}
}
private static String readAll(Reader rd) throws IOException {
StringBuilder sb = new StringBuilder();
int cp;
while ((cp = rd.read()) != -1) {
sb.append((char) cp);
}
return sb.toString();
}
public static JSONArray readJsonFromUrl(String url) throws IOException, JSONException {
InputStream is = new URL(url).openStream();
try {
BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
String jsonText = readAll(rd);
JSONArray json = new JSONArray(jsonText);
return json;
} finally {
is.close();
}
}
public void getData() {
try{
json = readJsonFromUrl("http://localhost/indextest.php?function=getdata");
Thread.sleep(1000);
} catch (Exception e) {
Log.e("BACKGROUND_PROC", e.getMessage());
}
}
public boolean testData() {
getData();
user = editText1.getText().toString();
password = editText2.getText().toString();
for (int i = 0; i < json.length(); i++) {
JSONObject currentObject = json.getJSONObject(i);
if (currentObject.getString("username", "").equals(user) && currentObject.getString("password", "").equals(password))
return true;
}
return false;
}
【问题讨论】:
-
我在你的其他question上给了你一个答案,请回复我
标签: java android json getjson arrays