gpt4 book ai didi

php - 如何通过 Android 将参数发布到 PHP 后检索 json 数组

转载 作者:搜寻专家 更新时间:2023-11-01 09:40:55 26 4
gpt4 key购买 nike

这是我的 JAVA 类,我有 SendPHP() AsyncTask 将我选择的日期发布到 PHP 和另一个 RequestTask() AsyncTask 来检索我的 JSON 数组

    public class CustomerPage extends Fragment {
private FragmentActivity activity;
private RecyclerView rv;
private LinearLayoutManager layoutManager;
private AlertDialog alertDialog;
private List<Customer> customers;
private RequestTask task;
private CustomerAdapter adapter;
private String url ="http://eac.asia/eacsales/Newstar/get_customer.php";
private String TAG_STATUS = "status";
private String TAG_CUSTOMER = "customers";
private Calendar calendar;
private int year,month,day;
private TextView tvDate;
private ImageView imgSearch;
private String output;
String strDay , strMonth,strYear;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
activity = (FragmentActivity) getActivity();
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.customer_page,container,false);
rv = (RecyclerView) v.findViewById(R.id.rvCustomer);
tvDate = (TextView)v.findViewById(R.id.dateView);
imgSearch = (ImageView)v.findViewById(R.id.img_search);
layoutManager = new LinearLayoutManager(getActivity());
calendar = Calendar.getInstance();
year = calendar.get(Calendar.YEAR);
month = calendar.get(Calendar.MONTH);
day = calendar.get(Calendar.DAY_OF_MONTH);

rv.setLayoutManager(layoutManager);
rv.setItemAnimator(new DefaultItemAnimator());

tvDate.setOnClickListener(new View.OnClickListener() {
@SuppressWarnings("deprecation")
@Override
public void onClick(View v) {
DialogFragment dialogFragment = new DateFragment();
dialogFragment.show(getActivity().getSupportFragmentManager(), "DatePicker");
}
});

return v;
}

@Override
public void onResume() {
super.onResume();
}

private void sendRequest() {
if (enableNetwork()) {
task = new RequestTask();
task.execute(url);
} else {
showAlertDialog("No Internet Connection");
}
}
public void showAlertDialog(String message) {
alertDialog = new AlertDialog.Builder(getActivity()).create();
alertDialog.setMessage(message);
alertDialog.setCancelable(false);

alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.show();
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
}

private class RequestTask extends AsyncTask<String, Void, List<Customer>> {

@Override
protected void onPreExecute() {
super.onPreExecute();
}

@Override
protected List<Customer> doInBackground(String... urls) {
try {
JSONObject jsonObject = getJsonObject(urls[0]);
Log.d("All data: ", jsonObject.toString());

if (jsonObject != null) {
boolean status = jsonObject.getBoolean(TAG_STATUS);
Log.d("Status: ", String.valueOf(status));

if (status) {
customers = CustomerJsonReader.getHome(jsonObject.getJSONArray(TAG_CUSTOMER));
} else {

}

}else {
showAlertDialog("Connection Problem");
}
URL url = new URL("http://eac.asia/eacsales/Newstar/get_customer.php");
URLConnection con = url.openConnection();
con.setDoOutput(true);
BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;

// Read Server Response
while((line = reader.readLine()) != null)
{
// Append server response in string
sb.append(line + "\n");
}
Log.d("Return Post",sb.toString());
} catch (Exception e) {
e.printStackTrace();
}
return customers;
}
/**
* It returns jsonObject for the specified url.
*
* @param url
* @return JSONObject
*/
public JSONObject getJsonObject(String url) {
JSONObject jsonObject = null;
try {
jsonObject = GetJSONObject.getJSONObject(url);
} catch (Exception e) {
}
return jsonObject;
}

@Override
protected void onPostExecute(List<Customer> result) {
super.onPostExecute(result);

customers = result;
if (customers != null && customers.size() != 0) {
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
adapter = new CustomerAdapter(getActivity(), customers);
rv.setAdapter(adapter);
}
});
}else{
Toast.makeText(getActivity(), "No Product found", Toast.LENGTH_SHORT).show();
}
}
}
public boolean enableNetwork() {

ConnectivityManager connectivityManager = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivityManager != null) {
NetworkInfo netInfo = connectivityManager.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnected()
&& netInfo.isConnectedOrConnecting()
&& netInfo.isAvailable()) {
return true;
}
}
return false;
}
class DateFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener {

@NonNull
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final Calendar calendar = Calendar.getInstance();
int yy = calendar.get(Calendar.YEAR);
int mm = calendar.get(Calendar.MONTH);
int dd = calendar.get(Calendar.DAY_OF_MONTH);
DatePickerDialog dp = new DatePickerDialog(getActivity(), AlertDialog.THEME_HOLO_LIGHT,this,yy,mm,dd);
return dp;

}

@Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
populateSetDate(year,monthOfYear+1,dayOfMonth);
}

public void populateSetDate(int year, int month, int day) {
tvDate.setText(month + "/" + day + "/" + year);
strDay = String.valueOf(day);
strMonth = String.valueOf(month);
strYear = String.valueOf(year);
new SendPHPRequest(getActivity()).execute(strDay,strMonth,strYear);
}
}

class SendPHPRequest extends AsyncTask<String, Void, String> {
private Context context;

public SendPHPRequest(Context context){
this.context = context;
}
@SuppressWarnings("deprecation")
@Override
protected String doInBackground(String... params) {

String day = params[0];
String month = params[1];
String year = params[2];
StringBuilder sb = null;

System.out.println("*** doInBackground ** day " + day + " month :" + month +"year :"+year);
try {
String data = URLEncoder.encode("day", "UTF-8")
+ "=" + URLEncoder.encode(day, "UTF-8");
data += "&" + URLEncoder.encode("month", "UTF-8") + "="
+ URLEncoder.encode(month, "UTF-8");
data += "&" + URLEncoder.encode("year", "UTF-8") + "="
+ URLEncoder.encode(year, "UTF-8");

URL url = new URL("http://eac.asia/eacsales/Newstar/get_customer.php");
URLConnection con = url.openConnection();
con.setDoOutput(true);

OutputStreamWriter wr = new OutputStreamWriter(con.getOutputStream());
wr.write(String.valueOf(data));
wr.flush();

BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
sb = new StringBuilder();
String line = null;

// Read Server Response
while((line = reader.readLine()) != null)
{
// Append server response in string
sb.append(line + "\n");
}
//noinspection ResourceType


} catch (UnsupportedEncodingException uee) {
System.out.println("An Exception given because of UrlEncodedFormEntity argument :" + uee);
uee.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}

@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
sendRequest();
}
}

这是我的 PHP 代码,用于从 Android 获取日期并根据日期从数据库中选择结果,然后将结果显示到 JSON 对象中

    <?php
$con = mysql_connect("localhost","eac_sale_database","a123456Z","eac_sale_database");
$db = mysql_select_db("eac_sale_database");

$response = array();

$day = urldecode($_POST['day']);
$month = urldecode($_POST['month']);
$year = urldecode($_POST['year']);

$result = mysql_query("SELECT * FROM customer WHERE day_visit = '$day' AND month_visit = '$month' AND year_visit = '$year'")or die(mysql_error());

if(mysql_num_rows($result)> 0){
$response["customers"] = array();
while($row = mysql_fetch_array($result)){
$product = array();
$product["custNo"] = $row["no"];
$product["custName"] = $row["name"];
$product["netSales"] = $row["net_sales"];
$product["dayVisit"] = $row["day_visit"];
$product["monthVisit"] = $row["month_visit"];
$product["yearVisit"] = $row["year_visit"];
$product["dateVisit"] = $row["date_visit"];
array_push($response["customers"], $product);
}
$response["status"] = "true";
header('Content-Type: application/json');
header('Vary: User-Agent');

echo json_encode($response);

}
else{
$response["status"] = "false";
echo json_encode($response);
}

?>

但是,我在 android 日志中的输出显示“status”=“false”。我很确定我的日期参数已经发布到 PHP,但它无法执行查询和输出。有解决办法吗?请帮忙。

This is the date in my database

DATA Sent get the JSONobject but it should be displayed in RequestTask()

最佳答案

问题出在你的 php 端:

  1. $con = mysql_connect("localhost","eac_sale_database","a123456Z");

这里只需要3个参数,因为你已经写好了

$db = mysql_select_db("eac_sale_database");
  1. 这样做:

    $day = urldecode($_GET['day']);<br/>
    $month = urldecode($_GET['month']);<br/>
    $year = urldecode($_GET['year']);

使用 postman 验证您的代码并确保您的用户名和密码正确,因为您的用户名和数据库名称不应该相同。

我试过你的代码在我这边创建了一个数据库和 php 文件,我得到了一个像这样的 json 对象:

{"customers":[{"custNo":"1","custName":"Rushi","netSales":"30000","dayVisit":"5","monthVisit":"7","yearVisit":"2016","dateVisit":"2016-10-05 10:24:33"}],"status":"true"}

为什么插入数据库和从数据库中获取相同的文件?你必须为两者创建不同的文件。另外,你为什么不在 doInBackground 中返回?我认为如果您请求与在 sendPHP 中请求的方式相同,您的 requestTask 将正常工作,因为这是您的 php 查询正在执行的操作。您在 RequestTask 中的请求不包含任何要搜索的参数。您需要进一步了解 php。

我的 PHP。如果请求的 url 是这样的,它返回对应于特定日期的行:: http://localhost/stacktest/get_customer.php?day=5&month=7&year=2016 并返回所有详细信息,如果请求的 URL 是这样的: http://localhost/stacktest/get_customer.php 希望你明白我在说什么。您需要更改 php 端的 sql 查询和 android 端的请求。

<?php
$con = mysql_connect("localhost","root","");
$db = mysql_select_db("stacktest");

$response = array();
print_r($_GET);
if(isset($_GET['day']))
{
$day = urldecode($_GET['day']);
$month = urldecode($_GET['month']);
$year = urldecode($_GET['year']);

$result = mysql_query("SELECT * FROM customer WHERE day_visit = '$day' AND month_visit = '$month' AND year_visit = '$year'")or die(mysql_error());

if(mysql_num_rows($result)> 0){
$response["customers"] = array();
while($row = mysql_fetch_array($result)){
$product = array();
$product["custNo"] = $row["no"];
$product["custName"] = $row["name"];
$product["netSales"] = $row["net_sales"];
$product["dayVisit"] = $row["day_visit"];
$product["monthVisit"] = $row["month_visit"];
$product["yearVisit"] = $row["year_visit"];
$product["dateVisit"] = $row["date_visit"];
array_push($response["customers"], $product);
}
$response["status"] = "true";
header('Content-Type: application/json');
header('Vary: User-Agent');

echo json_encode($response);

}
else{
$response["status"] = "false";
echo json_encode($response);
}
}
else{
$result = mysql_query("SELECT * FROM customer ")or die(mysql_error());

if(mysql_num_rows($result)> 0){
$response["customers"] = array();
while($row = mysql_fetch_array($result)){
$product = array();
$product["custNo"] = $row["no"];
$product["custName"] = $row["name"];
$product["netSales"] = $row["net_sales"];
$product["dayVisit"] = $row["day_visit"];
$product["monthVisit"] = $row["month_visit"];
$product["yearVisit"] = $row["year_visit"];
$product["dateVisit"] = $row["date_visit"];
array_push($response["customers"], $product);
}
$response["status"] = "true";
header('Content-Type: application/json');
header('Vary: User-Agent');

echo json_encode($response);
}
}
?>

如果您只想显示与给定日期对应的数据,请执行以下操作:

class SendPHPRequest extends AsyncTask<String, Void, String> {
...
...
...
protected String doInBackground(String... params) {
...
...
return sb.toString();
}
protected void onPostExecute(String result) {
RequestTask(result);
}

只在RequestTask中做json解析。否则就不需要 RequestTask。

保持你的 php 为:

<?php
$con = mysql_connect("localhost","root","");
$db = mysql_select_db("stacktest");

$response = array();

$day = urldecode($_GET['day']);
$month = urldecode($_GET['month']);
$year = urldecode($_GET['year']);

$result = mysql_query("SELECT * FROM customer WHERE day_visit = '$day' AND month_visit = '$month' AND year_visit = '$year'")or die(mysql_error());

if(mysql_num_rows($result)> 0){
$response["customers"] = array();
while($row = mysql_fetch_array($result)){
$product = array();
$product["custNo"] = $row["no"];
$product["custName"] = $row["name"];
$product["netSales"] = $row["net_sales"];
$product["dayVisit"] = $row["day_visit"];
$product["monthVisit"] = $row["month_visit"];
$product["yearVisit"] = $row["year_visit"];
$product["dateVisit"] = $row["date_visit"];
array_push($response["customers"], $product);
}
$response["status"] = "true";
header('Content-Type: application/json');
header('Vary: User-Agent');

echo json_encode($response);

}
else{
$response["status"] = "false";
echo json_encode($response);
}

?>

关于php - 如何通过 Android 将参数发布到 PHP 后检索 json 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39886753/

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