gpt4 book ai didi

java - 没有值从 php 返回到 android 应用程序

转载 作者:行者123 更新时间:2023-11-29 06:18:25 24 4
gpt4 key购买 nike

我已经尝试了 Stack Overflow 中关于如何将 php 值检索到 android 应用程序的许多方法,但没有成功。我不知道这里出了什么问题。有人可以帮我解决问题吗?或者至少是一个链接/提示?

首先,我调用 addInformation(name, weather, date2, status, first1[1], last1[1]);//将数据插入 MySQL 通过 php。

然后showList();//显示来自 php 的 lastID

最后显示出来 Toast.makeText(getApplicationContext(),"aa"+lastID,Toast.LENGTH_LONG).show();

    addInformation(name, weather, date2, status, first1[1], last1[1]);
showList();
Toast.makeText(getApplicationContext(),lastID,Toast.LENGTH_LONG).show();

我将 lastID 声明为全局。

这是我的 addInformation 函数

  public void addInformation(final String name, final String weather, final String date2, final String status, final String timeIn, final String timeOut) {
class AddInfo extends AsyncTask<String, Void, String> {
ProgressDialog loading;

@Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(WorkDetailsTable.this, "Please Wait", null, true, true);
}

@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
Toast.makeText(getApplicationContext(),s, Toast.LENGTH_LONG).show();

}

@Override
protected String doInBackground(String... params) {

HashMap<String, String> data = new HashMap<String, String>();
data.put(Config.KEY_USER_NAME, name);
data.put(Config.KEY_WEATHER, weather);
data.put(Config.KEY_DATE, date2);
data.put(Config.KEY_STATUS, status);
data.put(Config.KEY_TIMEIN, timeIn);
data.put(Config.KEY_TIMEOUT, timeOut);
RequestHandler rh = new RequestHandler();
String result = rh.sendPostRequest(Config.ADD_INFORMATION, data);
return result;
}
}
AddInfo ru = new AddInfo();
ru.execute(name, weather, date2, status, timeIn, timeOut);
}

addInformation.php

<?php 
require_once('dbConnect.php');
if($_SERVER['REQUEST_METHOD']=='POST'){

$response = array();

//Getting values

$name = $_POST['name'];
$weather = $_POST['weather'];
$date = $_POST['date'];
$status = $_POST['status'];
$timeIn = $_POST['timeIn'];
$timeOut = $_POST['timeOut'];


//Creating an sql query
$sql = "INSERT INTO information(name, weather, date, status, time_in, time_out) VALUES ('$name','$weather','$date', '$status', '$timeIn', '$timeOut')";

//Importing our db connection script
require_once('dbConnect.php');

//Executing query to database
if(mysqli_query($con,$sql)){
echo 'Information Added Successfully';
$insertId= mysqli_insert_id($con);
$response["lastId"]=$insertId;
echo json_encode($response);
}else{
echo 'Could Not Add Information';
}

//Closing the database
mysqli_close($con);
}
?> // I get Information Added Successfully follow by the latest ID

接下来,转到 showList() 以获取 latestID 使用相同的 php 脚本

  public void showList() {
class GetLastID extends AsyncTask<Void, Void, String> {
private ProgressDialog progressDialog = new ProgressDialog(WorkDetailsTable.this);
InputStream inputStream = null;
String result = "";

protected void onPreExecute() {
progressDialog.setMessage("Downloading your data...");
progressDialog.show();
progressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
public void onCancel(DialogInterface arg0) {
GetLastID.this.cancel(true);
}
});
}

@Override
protected String doInBackground(Void... params) {
String url_select = "http://192.168.107.115/Android/CRUD/addInformation.php"; // same php in addInformation, get the latestID and return to android app

ArrayList<NameValuePair> param = new ArrayList<NameValuePair>();

try {
// Set up HTTP post

// HttpClient is more then less deprecated. Need to change to URLConnection
HttpClient httpClient = new DefaultHttpClient();

HttpPost httpPost = new HttpPost(url_select);
httpPost.setEntity(new UrlEncodedFormEntity(param));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();

// Read content & Log
inputStream = httpEntity.getContent();
} catch (UnsupportedEncodingException e1) {
Toast.makeText(getApplicationContext(), "ERROR", Toast.LENGTH_LONG).show();
//Log.e("UnsupportedEncodingException", e1.toString());
//e1.printStackTrace();
} catch (ClientProtocolException e2) {
Toast.makeText(getApplicationContext(), "ERROR 1", Toast.LENGTH_LONG).show();
//Log.e("ClientProtocolException", e2.toString());
// e2.printStackTrace();
} catch (IllegalStateException e3) {
Toast.makeText(getApplicationContext(), "ERROR 2", Toast.LENGTH_LONG).show();
// Log.e("IllegalStateException", e3.toString());
// e3.printStackTrace();
} catch (IOException e4) {
Toast.makeText(getApplicationContext(), "ERROR 3", Toast.LENGTH_LONG).show();
// Log.e("IOException", e4.toString());
//e4.printStackTrace();
}
// Convert response to string using String Builder
try {
BufferedReader bReader = new BufferedReader(new InputStreamReader(inputStream, "utf-8"), 8);
StringBuilder sBuilder = new StringBuilder();

String line = null;
while ((line = bReader.readLine()) != null) {
sBuilder.append(line + "\n");
}

inputStream.close();
result = sBuilder.toString();
JSONObject resultObject = new JSONObject(result);
lastID = resultObject.getString("lastId"); // get the latestID from php
Log.e("TAG",lastID);

} catch (Exception e) {
Log.e("TAG", "A");
}
return result;
}
}
}

我想 Toast 会显示最新的 ID,但它会显示 null。

已编辑

添加信息()

   @Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
showList();

显示列表()

  public void showList() {
class GetLastID extends AsyncTask<Void, Void, String> {
private ProgressDialog progressDialog = new ProgressDialog(WorkDetailsTable.this);
InputStream inputStream = null;
String result = "";
ProgressDialog loading;

protected void onPreExecute() {
progressDialog.setMessage("Downloading your data...");
progressDialog.show();
progressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
public void onCancel(DialogInterface arg0) {
GetLastID.this.cancel(true);
}
});
}

@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
Toast.makeText(getApplicationContext(),"aa"+lastID,Toast.LENGTH_LONG).show();
}

最佳答案

更新php代码

//Executing query to database
if(mysqli_query($con,$sql)){
// echo 'Information Added Successfully'; // Remove this line
$insertId= mysqli_insert_id($con);
$response["lastId"]=$insertId;
echo json_encode($response);
}else{
echo 'Could Not Add Information';
}

并使用这个类

public class AddInfo extends AsyncTask<String, Void, ContentValues> {

private final Context context;
private final ProgressDialog loading;

public AddInfo(Context context) {
this.context = context;
}

private ContentValues handleActionSend(String name, String weather, String date2, String status, String timeIn, String timeOut) {
ContentValues retour = new ContentValues();
retour.put("success", false);

try {
HttpPost post = new HttpPost(Config.ADD_INFORMATION);
post.addHeader("Accept", "application/json");
List<NameValuePair> postParams = new ArrayList<NameValuePair>();
postParams.add(new BasicNameValuePair(Config.KEY_USER_NAME, name));
postParams.add(new BasicNameValuePair(Config.KEY_WEATHER, weather));
postParams.add(new BasicNameValuePair(Config.KEY_DATE, date2));
postParams.add(new BasicNameValuePair(Config.KEY_STATUS, status));
postParams.add(new BasicNameValuePair(Config.KEY_TIMEIN, timeIn));
postParams.add(new BasicNameValuePair(Config.KEY_TIMEOUT, timeOut));

post.setEntity(new UrlEncodedFormEntity(postParams, HTTP.UTF_8));
HttpClient client = new DefaultHttpClient();

HttpResponse response = client.execute(post);

BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

StringBuilder result = new StringBuilder();
String line;
while ((line = rd.readLine()) != null) {
result.append(line);
}

JSONObject json = new JSONObject(result.toString());

retour.put("success", true);
retour.put("lastId", json.getInt("lastId"));
} catch (MalformedURLException e) {
retour.put("message", "MalformedURLException Error: " + e.getLocalizedMessage());
} catch (UnsupportedEncodingException e) {
retour.put("message", "UnsupportedEncodingException Error: " + e.getLocalizedMessage());
} catch (IOException e) {
retour.put("message", "IOException Error: " + e.getLocalizedMessage());
} catch (Exception e) {
retour.put("message", "Exception Error: " + e.getLocalizedMessage());
}
return retour;
}


@Override
protected ContentValues doInBackground(String... args) {
loading = ProgressDialog.show(context, "Please Wait", null, true, true);
return handleActionSend(args[0], args[1], args[2], args[3], args[4], args[5]);
}

@Override
protected void onPostExecute(ContentValues contentValues) {
super.onPostExecute(contentValues);
loading.dismiss();
String message;
if(contentValues.getAsBoolean("success")) {
message = "Inserted successfully: "+ contentValues.getAsInt("lastId");
} else {
message = "An error has occured!\n"+ contentValues.getAsString("message");
}
Toast.makeText(context, message, Toast.LENGTH_LONG).show();
}
}

然后调用它

public void addInformation(final String name, final String weather, final String date2, final String status, final String timeIn, final String timeOut) {
AddInfo ru = new AddInfo(this);
ru.execute(name, weather, date2, status, timeIn, timeOut);
}

关于java - 没有值从 php 返回到 android 应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34608039/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com