我一直試圖通過類別名稱獲取我表格中的所有數據,如果我通過tbl_menu中的category_id獲取它,但它決定將其更改爲通過category_name(named類別在tbl_menu)。但它不提取和logcat沒有太大的幫助。通過category_name從PHP中獲取到Android
這是我的類別表(tbl_category),它不是真正相關的,因爲它只是一個表,當我添加產品,這是它獲取類別的地方。
這是我的產品(tbl_menu)表這是它應該通過獲取列類產品。
現在,我想我的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');
?>
當點擊一個類別,它提供了putextra到下一個活動(ActivityMenuList.java)。感興趣#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);
}
}
在本活動中,感興趣的#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顯示的唯一信息是#JSONException: Value of type java.lang.String cannot be converted to JSONObject
,我不知道它爲什麼這樣做,但它肯定不是顯示當我通過category_id獲取它時。我對這篇長文章感到非常抱歉,但我只想盡可能多地獲取信息,以便獲得幫助,因爲我的智慧在這裏結束。如果您需要更多信息,請與我們聯繫。謝謝。
哇,我怎麼能錯過。非常感謝你!!! – user827391012