2016-02-05 96 views
0

我一直试图通过类别名称获取我表格中的所有数据,如果我通过tbl_menu中的category_id获取它,但它决定将其更改为通过category_name(named类别在tbl_menu)。但它不提取和logcat没有太大的帮助。通过category_name从PHP中获取到Android

这是我的类别表(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'); 
?> 

当点击一个类别,它提供了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获取它时。我对这篇长文章感到非常抱歉,但我只想尽可能多地获取信息,以便获得帮助,因为我的智慧在这里结束。如果您需要更多信息,请与我们联系。谢谢。

回答

1
$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"; 
+0

哇,我怎么能错过。非常感谢你!!! – user827391012