我已经在我的应用程序上设置了一个登录屏幕(现在就是这样)。它有一个用户名和密码字段以及一个登录按钮。当用户输入他们的详细信息并按下登录时,它会检查用户是否存在于我的 MySQL 数据库中并且详细信息是否正确,然后显示一条 Toast 消息,如果是,则显示“成功”,如果不存在或存在则显示“无效...”是与服务器的错误连接,然后显示“连接错误”。
我不断收到连接错误消息,我不知道为什么。我已经在 php 文件中测试了数据库连接,它工作正常,对数据库的查询也是如此,所以我假设问题出在我的 android 代码中。
这是您的整个代码块(隐藏了我的域)
package uk.co.mypackage.mypackagename;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;
import android.os.Bundle;
import android.app.Activity;
import android.content.SharedPreferences;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity implements OnClickListener{
EditText etUser, etPass;
Button bLogin;
//Create String variables that have input assigned to them
String username, password;
//Create an HTTPClient as form container
HttpClient httpClient;
//User HTTP Post method
HttpPost httppost;
//Create an array list for the input data to be sent
ArrayList<NameValuePair> nameValuePairs;
//Create an HTTP Response and HTTP Entity
HttpResponse response;
HttpEntity entity;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initialise();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
private void initialise() {
etUser = (EditText) findViewById(R.id.etUser);
etPass = (EditText) findViewById(R.id.etPass);
bLogin = (Button) findViewById(R.id.bSubmit);
//Now to set an OnClickListener
bLogin.setOnClickListener(this);
}
@Override
public void onClick(View v) {
//Create New default HTTPClient
httpClient = new DefaultHttpClient();
//Create new HTTP POST with URL to PHP file as parameter
httppost = new HttpPost("http://www.mydomain.co.uk/android_api/index.php");
//Assign input text to string
username = etUser.getText().toString();
password = etPass.getText().toString();
try{
//Create New Array List
nameValuePairs = new ArrayList<NameValuePair>();
//Place them in an array list
nameValuePairs.add(new BasicNameValuePair("username", username));
nameValuePairs.add(new BasicNameValuePair("password", password));
//Add array list to HTTP POST
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
//assign executed form container to response
response = httpClient.execute(httppost);
//check status code, need to check status code 200
if(response.getStatusLine().getStatusCode()== 200){
//assign response entity to http entity
entity = response.getEntity();
//check if entity is not null
if(entity != null){
//Create new input stream with received data assigned
InputStream instream = entity.getContent();
//Create new JSON object. assign converted data as parameter
JSONObject jsonResponse = new JSONObject(convertStreamToString(instream));
//assign JSON responses to local string
String retUser = jsonResponse.getString("user");//MySQL table field
String retPass = jsonResponse.getString("pass");//MySQL table field
//Validate login
if(username.equals(retUser)&& password.equals(retPass)){
//Create a new shared preference by getting the preference
SharedPreferences sp = getSharedPreferences("logindetails", 0);
//Edit the shared preferences
SharedPreferences.Editor spedit = sp.edit();
//Put the login details as string
spedit.putString("user", username);
spedit.putString("pass", password);//May not need to store password
//close the editor
spedit.commit();
//Display a Toast saying login was a success
Toast.makeText(getBaseContext(), "SUCCESS!", Toast.LENGTH_SHORT).show();
} else {
//Display a Toast status saying it failed
Toast.makeText(getBaseContext(), "Invalid Login Details", Toast.LENGTH_SHORT).show();
}
}
}
} catch(Exception e){
e.printStackTrace();
//Display Toast when there is a connection error
Toast.makeText(getBaseContext(), "Connection Error", Toast.LENGTH_SHORT).show();
}
} //End OnClick()
private static String convertStreamToString(InputStream is) {
/*
* To convert the InputStream to String we use the BufferedReader.readLine()
* method. We iterate until the BufferedReader return null which means
* there's no more data to read. Each line will appended to a StringBuilder
* and returned as String.
*/
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}//End ConvertStreamToString
}