gpt4 book ai didi

java - 通过category_name从PHP获取到Android

转载 作者:行者123 更新时间:2023-11-29 21:31:33 25 4
gpt4 key购买 nike

我一直在尝试通过类别名称获取表中的所有数据,如果我通过 tbl_menu 中的category_id 获取它,它就可以工作,但我决定将其更改为通过category_name(tbl_menu 中的命名类别)获取。但它无法获取,并且 logcat 也没有多大帮助。

这是我的类别表(tbl_category),它并不真正相关,因为它只是我添加产品时的表,并且这是它获取类别的地方。

enter image description here

这是我的产品表(tbl_menu),它应该通过类别列获取产品。

enter image description here

现在,我认为我的 api 是正确的,但我可能是错的,因为它应该在类别中获取。

按类别id获取菜单数据.php

<?php
include_once('../includes/connect_database.php');
include_once('../includes/variables.php');

if(isset($_GET['accesskey']) && isset($_GET['category'])) {
$access_key_received = $_GET['accesskey'];
$category = $_GET['category'];

if(isset($_GET['keyword'])){
$keyword = $_GET['keyword'];
}else{
$keyword = "";
}

if($access_key_received == $access_key){
if($keyword == ""){
// find menu by category id in menu table
$sql_query = "SELECT Menu_ID, Menu_name, Price, Menu_image
FROM tbl_menu
WHERE Category = ".$category."
ORDER BY Menu_ID DESC";
}else{
// find menu by category id and keyword in menu table
$sql_query = "SELECT Menu_ID, Menu_name, Price, Menu_image
FROM tbl_menu
WHERE Menu_name LIKE '%".$keyword."%' AND Category = ".$category."
ORDER BY Menu_ID DESC";
}

$result = $connect->query($sql_query) or die("Error : ".mysql_error());

$menus = array();
while($menu = $result->fetch_assoc()) {
$menus[] = array('Menu'=>$menu);
}

// create json output
$output = json_encode(array('data' => $menus));
}else{
die('accesskey is incorrect.');
}
} else {
die('accesskey and category are required.');
}

//Output the output.
echo $output;

include_once('../includes/close_database.php');
?>

当单击一个类别时,它会为下一个 Activity (ActivityMenuList.java) 提供一个 putextra。 CTRL+F 兴趣点 #3

ActivityCategoryList.java

package com.emman.motg;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.util.ArrayList;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.ActionBar;
import android.app.Activity;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.ProgressBar;
import android.widget.TextView;

public class ActivityCategoryList extends Activity {

GridView listCategory;
ProgressBar prgLoading;
TextView txtAlert;

// declare adapter object to create custom category list
AdapterCategoryList cla;

// create arraylist variables to store data from server
static ArrayList<Long> Category_ID = new ArrayList<Long>();
static ArrayList<String> Category_name = new ArrayList<String>();
static ArrayList<String> Category_image = new ArrayList<String>();

String CategoryAPI;
int IOConnect = 0;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.category_list);

ActionBar bar = getActionBar();
bar.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.header)));
bar.setDisplayHomeAsUpEnabled(true);
bar.setHomeButtonEnabled(true);
bar.setTitle("Category");

prgLoading = (ProgressBar) findViewById(R.id.prgLoading);
listCategory = (GridView) findViewById(R.id.listCategory);
txtAlert = (TextView) findViewById(R.id.txtAlert);

cla = new AdapterCategoryList(ActivityCategoryList.this);

// category API url
CategoryAPI = Constant.CategoryAPI+"?accesskey="+Constant.AccessKey;

// call asynctask class to request data from server
new getDataTask().execute();

// event listener to handle list when clicked
listCategory.setOnItemClickListener(new OnItemClickListener() {

public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long arg3) {
// TODO Auto-generated method stub
// go to menu page
Intent iMenuList = new Intent(ActivityCategoryList.this, ActivityMenuList.class);
iMenuList.putExtra("category_id", Category_ID.get(position));
iMenuList.putExtra("category", Category_name.get(position));//point of interest #3
startActivity(iMenuList);
overridePendingTransition(R.anim.open_next, R.anim.close_next);
}
});

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_category, menu);
return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
switch (item.getItemId()) {
case R.id.cart:
// refresh action
Intent iMyOrder = new Intent(ActivityCategoryList.this, ActivityCart.class);
startActivity(iMyOrder);
overridePendingTransition (R.anim.open_next, R.anim.close_next);
return true;

case R.id.refresh:
IOConnect = 0;
listCategory.invalidateViews();
clearData();
new getDataTask().execute();
return true;

case android.R.id.home:
// app icon in action bar clicked; go home
this.finish();
overridePendingTransition(R.anim.open_main, R.anim.close_next);
return true;

default:
return super.onOptionsItemSelected(item);
}
}

// clear arraylist variables before used
void clearData(){
Category_ID.clear();
Category_name.clear();
Category_image.clear();
}

// asynctask class to handle parsing json in background
public class getDataTask extends AsyncTask<Void, Void, Void>{

// show progressbar first
getDataTask(){
if(!prgLoading.isShown()){
prgLoading.setVisibility(0);
txtAlert.setVisibility(8);
}
}

@Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
// parse json data from server in background
parseJSONData();
return null;
}

@Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
// when finish parsing, hide progressbar
prgLoading.setVisibility(8);

// if internet connection and data available show data on list
// otherwise, show alert text
if((Category_ID.size() > 0) && (IOConnect == 0)){
listCategory.setVisibility(0);
listCategory.setAdapter(cla);
}else{
txtAlert.setVisibility(0);
}
}
}

// method to parse json data from server
public void parseJSONData(){

clearData();

try {
// request data from Category API
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 15000);
HttpConnectionParams.setSoTimeout(client.getParams(), 15000);
HttpUriRequest request = new HttpGet(CategoryAPI);
HttpResponse response = client.execute(request);
InputStream atomInputStream = response.getEntity().getContent();
BufferedReader in = new BufferedReader(new InputStreamReader(atomInputStream));

String line;
String str = "";
while ((line = in.readLine()) != null){
str += line;
}

// parse json data and store into arraylist variables
JSONObject json = new JSONObject(str);
JSONArray data = json.getJSONArray("data");

for (int i = 0; i < data.length(); i++) {
JSONObject object = data.getJSONObject(i);

JSONObject category = object.getJSONObject("Category");

Category_ID.add(Long.parseLong(category.getString("Category_ID")));
Category_name.add(category.getString("Category_name"));
// Category_image.add(category.getString("Category_image"));
Log.d("Category name", Category_name.get(i));

}


} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
IOConnect = 1;
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

@Override
protected void onDestroy() {
// TODO Auto-generated method stub
//cla.imageLoader.clearCache();
listCategory.setAdapter(null);
super.onDestroy();
}


@Override
public void onConfigurationChanged(final Configuration newConfig)
{
// Ignore orientation change to keep activity from restarting
super.onConfigurationChanged(newConfig);
}

@Override
public void onBackPressed() {
// TODO Auto-generated method stub
super.onBackPressed();
finish();
overridePendingTransition(R.anim.open_main, R.anim.close_next);
}

}

在此 Activity 中,兴趣点 #1 获取额外内容并将其放入变量中

ActivityMenuList.java

package com.emman.motg;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.util.ArrayList;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.ActionBar;
import android.app.Activity;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

public class ActivityMenuList extends Activity {

ListView listMenu;
ProgressBar prgLoading;
//TextView txtTitle;
EditText edtKeyword;
ImageButton btnSearch;
TextView txtAlert;

// declare static variable to store tax and currency symbol
static double Tax;
static String Currency;

// declare adapter object to create custom menu list
AdapterMenuList mla;

// create arraylist variables to store data from server
static ArrayList<Long> Menu_ID = new ArrayList<Long>();
static ArrayList<String> Menu_name = new ArrayList<String>();
static ArrayList<Double> Menu_price = new ArrayList<Double>();
static ArrayList<String> Menu_image = new ArrayList<String>();

String MenuAPI;
String TaxCurrencyAPI;
int IOConnect = 0;
long Category_ID;
String Category_name;
String Keyword;

// create price format
DecimalFormat formatData = new DecimalFormat("#.##");


@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.menu_list);

ActionBar bar = getActionBar();
bar.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.header)));
bar.setTitle("Product");
bar.setDisplayHomeAsUpEnabled(true);
bar.setHomeButtonEnabled(true);
prgLoading = (ProgressBar) findViewById(R.id.prgLoading);
listMenu = (ListView) findViewById(R.id.listMenu);
edtKeyword = (EditText) findViewById(R.id.edtKeyword);
btnSearch = (ImageButton) findViewById(R.id.btnSearch);
txtAlert = (TextView) findViewById(R.id.txtAlert);

// menu API url
MenuAPI = Constant.MenuAPI+"?accesskey="+Constant.AccessKey+"&category=";
// tax and currency API url
TaxCurrencyAPI = Constant.TaxCurrencyAPI+"?accesskey="+Constant.AccessKey;

// get category id and category name that sent from previous page
Intent iGet = getIntent();
Category_ID = iGet.getLongExtra("category_id",0);
Category_name = iGet.getStringExtra("category");//point of interest #1
MenuAPI += Category_name;

// set category name to textview
// txtTitle.setText(Category_name);

mla = new AdapterMenuList(ActivityMenuList.this);

// call asynctask class to request tax and currency data from server
new getTaxCurrency().execute();

// event listener to handle search button when clicked
btnSearch.setOnClickListener(new OnClickListener() {

public void onClick(View arg0) {
// TODO Auto-generated method stub
// get keyword and send it to server
try {
Keyword = URLEncoder.encode(edtKeyword.getText().toString(), "utf-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
MenuAPI += "&keyword="+Keyword;
IOConnect = 0;
listMenu.invalidateViews();
clearData();
new getDataTask().execute();
}
});

// event listener to handle list when clicked
listMenu.setOnItemClickListener(new OnItemClickListener() {

public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long arg3) {
// TODO Auto-generated method stub
// go to menu detail page
Intent iDetail = new Intent(ActivityMenuList.this, ActivityMenuDetail.class);
iDetail.putExtra("menu_id", Menu_ID.get(position));
startActivity(iDetail);
overridePendingTransition(R.anim.open_next, R.anim.close_next);
}
});

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_category, menu);

// final SearchView searchView = (SearchView) menu.findItem(R.id.search).getActionView();
// searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
//
// @Override
// public boolean onQueryTextChange(String newText) {
// return true;
// }
//
// @Override
// public boolean onQueryTextSubmit(String query) {
// try {
// Keyword = URLEncoder.encode(query.toString(), "utf-8");
// } catch (UnsupportedEncodingException e) {
// e.printStackTrace();
// }
//
// MenuAPI += "&keyword="+Keyword;
// IOConnect = 0;
// listMenu.invalidateViews();
// clearData();
// new getDataTask().execute();
//
// return true;
// }
// });
//
// searchView.addOnAttachStateChangeListener(new OnAttachStateChangeListener() {
//
// @Override
// public void onViewDetachedFromWindow(View arg0) {
// IOConnect = 0;
// listMenu.invalidateViews();
// clearData();
// new getDataTask().execute();
// }
//
// @Override
// public void onViewAttachedToWindow(View arg0) {
// // search was opened
// }
// });

return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
switch (item.getItemId()) {
case R.id.cart:
// refresh action
Intent iMyOrder = new Intent(ActivityMenuList.this, ActivityCart.class);
startActivity(iMyOrder);
overridePendingTransition (R.anim.open_next, R.anim.close_next);
return true;

case R.id.refresh:
IOConnect = 0;
listMenu.invalidateViews();
clearData();
new getDataTask().execute();
return true;

case android.R.id.home:
// app icon in action bar clicked; go home
this.finish();
overridePendingTransition(R.anim.open_main, R.anim.close_next);
return true;

default:
return super.onOptionsItemSelected(item);
}
}

// asynctask class to handle parsing json in background
public class getTaxCurrency extends AsyncTask<Void, Void, Void>{

// show progressbar first
getTaxCurrency(){
if(!prgLoading.isShown()){
prgLoading.setVisibility(0);
txtAlert.setVisibility(8);
}
}

@Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
// parse json data from server in background
parseJSONDataTax();
return null;
}

@Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
// when finish parsing, hide progressbar
prgLoading.setVisibility(8);
// if internet connection and data available request menu data from server
// otherwise, show alert text
if((Currency != null) && IOConnect == 0){
new getDataTask().execute();
}else{
txtAlert.setVisibility(0);
}
}
}

// method to parse json data from server
public void parseJSONDataTax(){
try {
// request data from tax and currency API
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 15000);
HttpConnectionParams.setSoTimeout(client.getParams(), 15000);
HttpUriRequest request = new HttpGet(TaxCurrencyAPI);
HttpResponse response = client.execute(request);
InputStream atomInputStream = response.getEntity().getContent();

BufferedReader in = new BufferedReader(new InputStreamReader(atomInputStream));

String line;
String str = "";
while ((line = in.readLine()) != null){
str += line;
}


// parse json data and store into tax and currency variables
JSONObject json = new JSONObject(str);
JSONArray data = json.getJSONArray("data"); // this is the "items: [ ] part

JSONObject object_tax = data.getJSONObject(0);
JSONObject tax = object_tax.getJSONObject("tax_n_currency");

Tax = Double.parseDouble(tax.getString("Value"));

JSONObject object_currency = data.getJSONObject(1);
JSONObject currency = object_currency.getJSONObject("tax_n_currency");

Currency = currency.getString("Value");


} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
IOConnect = 1;
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

// clear arraylist variables before used
void clearData(){
Menu_ID.clear();
Menu_name.clear();
Menu_price.clear();
Menu_image.clear();
}

// asynctask class to handle parsing json in background
public class getDataTask extends AsyncTask<Void, Void, Void>{

// show progressbar first
getDataTask(){
if(!prgLoading.isShown()){
prgLoading.setVisibility(0);
txtAlert.setVisibility(8);
}
}

@Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
// parse json data from server in background
parseJSONData();
return null;
}

@Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
// when finish parsing, hide progressbar
prgLoading.setVisibility(8);

// if data available show data on list
// otherwise, show alert text
if(Menu_ID.size() > 0){
listMenu.setVisibility(0);
listMenu.setAdapter(mla);
}else{
txtAlert.setVisibility(0);
}

}
}

// method to parse json data from server
public void parseJSONData(){

clearData();

try {
// request data from menu API
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 15000);
HttpConnectionParams.setSoTimeout(client.getParams(), 15000);
HttpUriRequest request = new HttpGet(MenuAPI);
HttpResponse response = client.execute(request);
InputStream atomInputStream = response.getEntity().getContent();

BufferedReader in = new BufferedReader(new InputStreamReader(atomInputStream));

String line;
String str = "";
while ((line = in.readLine()) != null){
str += line;
}

// parse json data and store into arraylist variables
JSONObject json = new JSONObject(str);//point of interest #2
JSONArray data = json.getJSONArray("data"); // this is the "items: [ ] part

for (int i = 0; i < data.length(); i++) {
JSONObject object = data.getJSONObject(i);

JSONObject menu = object.getJSONObject("Menu");

Menu_ID.add(Long.parseLong(menu.getString("Menu_ID")));
Menu_name.add(menu.getString("Menu_name"));
Menu_price.add(Double.valueOf(formatData.format(menu.getDouble("Price"))));
Menu_image.add(menu.getString("Menu_image"));

}


} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}


@Override
protected void onDestroy() {
// TODO Auto-generated method stub
//mla.imageLoader.clearCache();
listMenu.setAdapter(null);
super.onDestroy();
}


@Override
public void onConfigurationChanged(final Configuration newConfig)
{
// Ignore orientation change to keep activity from restarting
super.onConfigurationChanged(newConfig);
}

@Override
public void onBackPressed() {
// TODO Auto-generated method stub
super.onBackPressed();
finish();
overridePendingTransition(R.anim.open_main, R.anim.close_next);
}


}

最后,logcat 显示的唯一信息是兴趣点 #2 中的 JSONException: Value of type java.lang.String无法转换为 JSONObject,我不知道它为什么这样做但是当我通过category_id获取它时它肯定没有显示。我对这篇长帖子感到非常抱歉,但我只是想获得尽可能多的信息以尝试获得帮助,因为我在这里束手无策。如果您需要更多信息,请与我们联系。谢谢。

最佳答案

$sql_query = "SELECT Menu_ID, Menu_name, Price, Menu_image 
FROM tbl_menu
WHERE Category = ".$category."
ORDER BY Menu_ID DESC";

您可以尝试更改为:

$sql_query = "SELECT Menu_ID, Menu_name, Price, Menu_image 
FROM tbl_menu
WHERE Category = '".$category."'
ORDER BY Menu_ID DESC";

关于java - 通过category_name从PHP获取到Android,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35215662/

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