我需要帮助格式化从数据库返回给我的一些信息。当用户在登录活动中填写用户名和密码并单击“提交”时,它将调用backgroundtask.java登录方法。此方法连接到数据库php文件并发送名称和pw,然后该文件还通过电子邮件搜索以查找与用户关联的狗ID和名称。归还狗id和狗的名字。我正在测试一个时,我目前得到以下输出。
I/response: Response{"6":"Tom","57":"Hank Hill","66":"Jordan","69":"LOL","status":200}
行和响应都会在log cat中打印出上面的信息,以证明他们确实收到了我要求的信息。我需要一种方法来保存数字和dogid以传递到使用customAdapater填充的homelistview活动。我试图在customAdapater中实现dogName,但我不得不将它注释掉,因为它导致了很多错误。我希望狗的名字显示在行中,以便用户知道哪只狗是哪个。
<?php
// For 4.3.0 <= PHP <= 5.4.0
if (!function_exists('http_response_code'))
{
function http_response_code($newcode = NULL)
{
static $code = 200;
if($newcode !== NULL)
{
header('X-PHP-Response-Code: '.$newcode, true, $newcode);
if(!headers_sent())
$code = $newcode;
}
return $code;
}
}
$servername = "xxxxxxxxx";
$username = "xxxxxxxxx";
$password = "xxxxxxxxx";
$dbname = "doggie_did";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
header("Content-type: application/json");
$response = array("message"=>"Something went wrong.","status"=>500);
// Check connection
if ($conn->connect_error) {
http_response_code(500);
echo json_encode(array("message"=>"Connection failed: " . $conn->connect_error,"status"=>500));
die("Connection failed: " . $conn->connect_error);
exit;
}
//assigns the posted values to variables
$inputJSON = file_get_contents('php://input');
$input = json_decode( $inputJSON, TRUE ); //convert JSON into array
$email = $_POST['email'];
$password = $_POST['password'];
//inserts the variables into a SQL query
$sql = "SELECT * FROM users WHERE email = '" . $email . "' AND password = '" . $password . "';";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$response = array("message"=>"Successfully logged in " . $row["fName"] . " " . $row["lName"] . "!","status"=>200);
http_response_code(200);
// NEW CODE ***************
$sql2 = "SELECT dog_id FROM relationships WHERE user_id = (SELECT user_id FROM users WHERE email = '" . $email . "')";
$result = $conn->query($sql2);
if ($result->num_rows > 0){
$dogArray = array();
while($row = $result->fetch_assoc()) {
$dog_id = $row["dog_id"];
$name = "-";
$sql3 = "SELECT name FROM dogs WHERE dog_id = '" . $dog_id . "'";
$result3 = $conn->query($sql3);
if ($result3->num_rows > 0){
while($row3 = $result3->fetch_assoc()) {
$name = $row3["name"];
}
}
$dogArray[$dog_id] = $name;
}
$dogArray["status"] = 200;
$response = $dogArray;
} else {
http_response_code(200);
$response = array("error"=>"No Dogs","status"=>403);
}
// END NEW CODE ********************
}
} else {
http_response_code(200);
$response = array("error"=>"Login Failed","status"=>403);
}
echo json_encode($response);
?>
------------ BackgroundTask.java ---------------------
public class BackgroundTask extends AsyncTask<String, Void, String> {
AlertDialog alertDialog;
Context ctx;
BackgroundTask(Context ctx)
{
this.ctx = ctx;
}
@Override
protected void onPreExecute() {
alertDialog = new AlertDialog.Builder(ctx).create();
alertDialog.setTitle("Login Information");
}
@Override
protected String doInBackground(String... params) {
String login_url = "http://willshare.com/doggie/Android/DatabaseLoginUserAndReturnDogInfo.php";
else if(method.equals("login"))
{
String email = params[1];
String password = params[2];
try {
URL url = new URL(login_url);
HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
OutputStream OS = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(OS, "UTF-8"));
String data = URLEncoder.encode("email", "UTF-8") +"="+URLEncoder.encode(email, "UTF-8")+"&"+
URLEncoder.encode("password", "UTF-8") +"="+URLEncoder.encode(password, "UTF-8");
bufferedWriter.write(data);
bufferedWriter.flush();
bufferedWriter.close();
OS.close();
InputStream IS = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(IS, "iso-8859-1"));
String response = "";
String line = "";
while ((line = bufferedReader.readLine())!=null)
{
response+= line;
Log.i("response", "Response" + response);
Log.i("line", "line" + line);
}
bufferedReader.close();
IS.close();
httpURLConnection.disconnect();
return response;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
@Override
protected void onPostExecute(String result) {
if(result.equals("Registration Success"))
{
Toast.makeText(ctx, result, Toast.LENGTH_LONG).show();
}
else
{
alertDialog.setMessage(result);
alertDialog.show();
}
}
}
---------------- Login.java --------------
public class LoginActivity extends AppCompatActivity {
EditText Email, Pwd;
String email, password;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
Email = (EditText)findViewById(R.id.EmailEditText);
Pwd = (EditText)findViewById(R.id.PasswordEditText);
}
/** Called when the user clicks the Login button */
public void sendHome(View view) {
email = Email.getText().toString();
password = Pwd.getText().toString();
String method = "login";
BackgroundTask backgroundTask = new BackgroundTask (this);
backgroundTask.execute(method, email, password);
finish();
Intent intent = new Intent(getApplicationContext(), HomeActivityListview.class);
startActivity(intent);
//if login failed make toast
}
/** Called when the user clicks the register button */
public void sendRegister(View view) {
Intent intent = new Intent(getApplicationContext(), RegistrationActivity.class);
startActivity(intent);
}
}
----------------- HomeListView.java ------------------
public class HomeActivityListview extends AppCompatActivity {
ListView lv;
Context context;
ArrayList dogName;
ArrayList dogID;
public static int [] dogImages={R.drawable.dogpic};
public static int [] dogNames={R.id.dogName};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home_activity_listview);
context=this;
lv=(ListView) findViewById(R.id.listView);
lv.setAdapter(new CustomAdapter(this, dogNames, dogImages));
}
public void sendProfile(View view) {
Intent intent = new Intent(getApplicationContext(), DogProfileActivity.class);
startActivity(intent);
}
public void NumberOne(View view) {
AlertDialog.Builder alertDlg = new AlertDialog.Builder(this);
alertDlg.setMessage("Confirm Dog went number one");
alertDlg.setCancelable(false);
alertDlg.setPositiveButton("Confirm", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//HomeActivity.super.onBackPressed();
}
});
alertDlg.setNegativeButton("Change", new DialogInterface.OnClickListener(){
@Override
public void onClick(DialogInterface dialog, int which) {
//HomeActivity.super.onBackPressed();
}
});
alertDlg.create().show();
}
public void NumberTwo(View view) {
AlertDialog.Builder alertDlg = new AlertDialog.Builder(this);
alertDlg.setMessage("Confirm Dog went number two");
alertDlg.setCancelable(false);
alertDlg.setPositiveButton("Confirm", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//HomeActivity.super.onBackPressed();
}
});
alertDlg.setNegativeButton("Change", new DialogInterface.OnClickListener(){
@Override
public void onClick(DialogInterface dialog, int which) {
//HomeActivity.super.onBackPressed();
}
});
alertDlg.create().show();
}
public void AddNewDog(View view) {
Intent intent = new Intent(getApplicationContext(), NewDogActivity.class);
startActivity(intent);
}
}
------------------ Customadapter.java -------------------
public class CustomAdapter extends BaseAdapter{
Context context;
int [] imageId;
int [] dogNamesId;
int [] dogId;
private static LayoutInflater inflater=null;
public CustomAdapter(HomeActivityListview homeActivityListview, int [] dogNames, int[] dogImages) {
// TODO Auto-generated constructor stub
context=homeActivityListview;
//dogNameId=dogNames;
//dogId=dogNum;
imageId=dogImages;
inflater = ( LayoutInflater )context.
getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return imageId.length;
//return dogNameId.length;
}
@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public class Holder
{
TextView name;
TextView timestamp1;
TextView timestamp2;
ImageView img;
ImageView img1;
ImageView img2;
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
Holder holder=new Holder();
View rowView;
rowView = inflater.inflate(R.layout.home_single_row, null);
holder.name=(TextView) rowView.findViewById(R.id.dogName);
holder.timestamp1=(TextView) rowView.findViewById(R.id.timestamp1);
holder.timestamp2=(TextView) rowView.findViewById(R.id.timestamp2);
holder.img=(ImageView) rowView.findViewById(R.id.dogimage);
holder.img1=(ImageView) rowView.findViewById(R.id.dog1num1);
holder.img2=(ImageView) rowView.findViewById(R.id.dog1num2);
//holder.name.setText(dogNames[position]);
holder.img.setImageResource(imageId[position]);
holder.img1.setImageResource(R.drawable.num1);
holder.img2.setImageResource(R.drawable.num2);
rowView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
});
return rowView;
}
}