从mysql json android中检索数据

Posted

技术标签:

【中文标题】从mysql json android中检索数据【英文标题】:Retrieve data from mysql json android 【发布时间】:2013-09-05 09:53:04 【问题描述】:

大家好,我的 android 应用程序有问题。我无法在 textView 上检索数据... 在我的应用程序中,我在它下面有一个 ListView 和一个 textView。我可以在 Listview 中获取数据,但我不能在 textview 中获取数据。

这是我的 java 类

public class X extends Activity 
 public static final String strURL = "url...";
  private ListView mainListViewNota ;
  private View layoutBtn;
  private Product[] Products ;
  private ArrayAdapter<Product> listAdapter ;
  private ArrayList<Product> ProductList = new ArrayList<Product>();
  /** Called when the activity is first created. */
  @Override
      public void onCreate(Bundle savedInstanceState) 
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_nota);

        // Find the ListView resource. 
        x = (ListView) findViewById( R.id.mainListViewNota );
        x = (View) findViewById(R.id.x);


    // when item is tapped, toggle checked properties of CheckBox and Product.
    x.setOnItemClickListener(new AdapterView.OnItemClickListener() 
      @Override
      public void onItemClick( AdapterView<?> parent, View item, int position, long id) 
        Product Product = listAdapter.getItem( position );
        modificaier(Product.getName(), Product.getPrice(), Product.getQuantity() );
        ProductViewHolder viewHolder = (ProductViewHolder) item.getTag();
      
    );


    refrechList();    
  

  /** Holds Product data. */
  private static class Product 
    private String name = "" ;
    private String price;
    private String quantity;


    public Product( String name, String price, String quantity ) 
        this.name = name ;
        this.price = price ;
        this.quantity = quantity ;
      

    public String getName() 
      return name;
    
    public void setName(String name) 
      this.name = name;
    

    public String getPrice()
        return price;
    

    public void setPrice()
        this.price = price;
    

    public String getQuantity()
        return quantity;
    
    public void setQuantity()
        this.quantity = quantity;
    

    public String toString() 
        return name +  price + quantity;
    

  

  /** Holds child views for one row. */
  private static class ProductViewHolder 

    private TextView tnName ;
    private TextView tnPrice;
    private TextView tnQuant;

    public ProductViewHolder( TextView tnName,  TextView tnPrice, TextView tnQuant ) 

      this.tnName = tnName ;
      this.tnPrice = tnPrice ;
      this.tnQuant = tnQuant ;
    

    public TextView gettnName() 
      return tnName;
    
    public void settnName(TextView tnName) 
      this.tnName = tnName;
      
    public TextView gettnPrice() 
        return tnPrice;
      
    public void settnPrice(TextView tnPrice) 
        this.tnPrice = tnPrice;
      
    public TextView gettnQuant() 
        return tnPrice;
      
    public void settnQuant(TextView tnQuant) 
        this.tnQuant = tnQuant;
      
  

  /** Custom adapter for displaying an array of Product objects. */
  private static class ProductArrayAdapter extends ArrayAdapter<Product> 

    private LayoutInflater inflater;

    public ProductArrayAdapter( Context context, List<Product> ProductList ) 
      super( context, R.layout.nota_spinner, R.id.rowTextView, ProductList );
      // Cache the LayoutInflate to avoid asking for a new one each time.
      inflater = LayoutInflater.from(context) ;
    

    @Override
    public View getView(int position, View convertView, ViewGroup parent) 
      // Product to display
      final Product Product = (Product) this.getItem( position ); 

      // The child views in each row.
      Button btnDel;
      Button btnAdd;
      TextView tnName ; 
      TextView tnPrice ; 
      TextView tnQuant ;

      // Create a new row view
      if ( convertView == null ) 
        convertView = inflater.inflate(R.layout.nota_spinner, null);

        // Find the child views.
        tnName = (TextView) convertView.findViewById( R.id.rowTextView );
        tnName.setTextColor(Color.parseColor("blue"));
        tnPrice = (TextView) convertView.findViewById( R.id.rowTextView2 );
        tnQuant = (TextView) convertView.findViewById( R.id.rowTextView3 );
        btnDel = (Button) convertView.findViewById( R.id.btnDel );
        btnAdd = (Button) convertView.findViewById( R.id.btnAdd );


        convertView.setTag( new ProductViewHolder(tnName,  tnPrice, tnQuant) );

      else 
        ProductViewHolder viewHolder = (ProductViewHolder) convertView.getTag();

        tnName = viewHolder.gettnName() ;
        tnPrice = viewHolder.gettnPrice() ;
        tnQuant = viewHolder.gettnQuant() ;

      


      tnName.setText( Product.getName() );
      tnPrice.setText( Product.getPrice());
      tnQuant.setText( Product.getQuantity() ); 

      return convertView;

    
  

  public Object onRetainNonConfigurationInstance() 
    return Products ;
  
  void refrechList()
      InputStream is = null;
        String result = "";
        ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
        nameValuePairs.add(new BasicNameValuePair("mode","afiseaza"));

        try

            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(strURL);
             httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity entity = response.getEntity();
            is = entity.getContent();

        catch(Exception e)
            Log.e("log_tag", "Error in http connection " + e.toString());
        


        try
            BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) 
                sb.append(line + "\n");
            
            is.close();
            result=sb.toString();
        catch(Exception e)
            Log.e("log_tag", "Error converting result " + e.toString());
        

            try

                JSONArray jArray = new JSONArray(result);
                for(int i=0;i<jArray.length();i++)
                    JSONObject json_data = jArray.getJSONObject(i); 
                   Product t=new Product(json_data.getString("den_produs").toString(),  
                                        json_data.getString("pr").toString() + " lei",
                                 "* " + json_data.getString("cant").toString() + " buc" );
                ProductList.add( t);
                

            catch(JSONException e)
                Log.e("log_tag", "Error parsing data " + e.toString());
            

  listAdapter = new ProductArrayAdapter(this, ProductList);
  mainListViewNota.setAdapter( listAdapter );   

  

  static void modificaier( String den, String pr, String cant)


        ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
        nameValuePairs.add(new BasicNameValuePair("mode","sterge"));
        nameValuePairs.add(new BasicNameValuePair("den",den));
        nameValuePairs.add(new BasicNameValuePair("pr",  pr));
        nameValuePairs.add(new BasicNameValuePair("cant",cant));

        try
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(strURL);
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity entity = response.getEntity();


        catch(Exception e)
            Log.e("log_tag", "Error in http connection " + e.toString());
        

  

  static void adauga( String den, String pr, String cant)


        ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
        nameValuePairs.add(new BasicNameValuePair("mode","adauga"));
        nameValuePairs.add(new BasicNameValuePair("den",den));
        nameValuePairs.add(new BasicNameValuePair("pr",  pr));
        nameValuePairs.add(new BasicNameValuePair("cant",cant));

        try
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(strURL);
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity entity = response.getEntity();


        catch(Exception e)
            Log.e("log_tag", "Error in http connection " + e.toString());
        



  static void sterge( )


        ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
        nameValuePairs.add(new BasicNameValuePair("mode","sterge"));


        try
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(strURL);
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity entity = response.getEntity();


        catch(Exception e)
            Log.e("log_tag", "Error in http connection " + e.toString());
        



  static void sterge_tot( )


        ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
        nameValuePairs.add(new BasicNameValuePair("mode","sterge_tot"));


        try
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(strURL);
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity entity = response.getEntity();


        catch(Exception e)
            Log.e("log_tag", "Error in http connection " + e.toString());
        





  static void afiseaza_total()
      InputStream is = null ;
      String result = "";


          HttpClient httpClient = new DefaultHttpClient();
          HttpPost httpPost = new HttpPost(strUrl);

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

            try 
            httpPost.setEntity(new UrlEncodedFormEntity(param));

            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();

            //read content
            is =  httpEntity.getContent();                  

             catch (Exception e) 

            Log.e("log_tag", "Error in http connection "+e.toString());
            
        try 
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            StringBuilder sb = new StringBuilder();
            String line = "";
            while((line=br.readLine())!=null)
            
               sb.append(line+"\n");
            
                is.close();
                result=sb.toString();               

                     catch (Exception e) 
                        // TODO: handle exception
                        Log.e("log_tag", "Error converting result "+e.toString());
                    

            
        protected void onPostExecute(Void v) 

            // ambil data dari Json database
            try 
                String result = "";
                JSONArray Jarray = new JSONArray(result);
                for(int i=0;i<Jarray.length();i++)
                
                JSONObject Jasonobject = null;
                TextView tvTotal = (TextView)findViewById(R.id.tvTotal);
                Jasonobject = Jarray.getJSONObject(i);

                //get an output on the screen

                String total = Jasonobject.getString("total");

                tvTotal.append("Total : " + total);

                

             catch (Exception e) 
                // TODO: handle exception
                Log.e("log_tag", "Error parsing data "+e.toString());
            
        

这是我的 php 文件

<?php  
    mysql_connect("localhost","root","");
    mysql_select_db("retailer");     
    $mode  =$_REQUEST ['mode'] ;  
    switch($mode )  
    
        case "afiseaza":  
                $sql=mysql_query("SELECT ... it's ok");                                     
                while($row=mysql_fetch_assoc($sql))
                $output[]=$row;
                print(json_encode($output));
                break;  
        case "sterge": 
                $request = ("delete from ... ok);               
                mysql_query($request);
                mysql_query($query);
                break;
        case "adauga": 
                $query = "INSERT INTO ... ok); ";
                mysql_query($query);
                mysql_query($boo);
                break;
        case "sterge_tot": 
                $query = "delete from ... ok";
                mysql_query($query);
                break;

        case "afiseaza_total": ---- >  THIS IT'S NOT WORKING
                $sqlString = "SELECT *, SUM( p.price * o.quantity ) As total 
                            FROM o, u, p
                            WHERE u.id = o.id
                            AND p.cod_p = o.cod_p
                            AND u.id = (SELECT MAX( id ) FROM u ) 
                            GROUP BY u.id ";
                $rs = mysql_query($sqlString);

                if($rs)
                while($objRs = mysql_fetch_assoc($rs))
                  $output[] = $objRs;
                
               echo json_encode($output);
                       
                break;
        default:             
 

      mysql_close();   
?>

我不知道有什么问题。有什么建议吗?!

【问题讨论】:

【参考方案1】:

您的静态 void afiseaza_total() 不包含 a

nameValuePairs.add(new BasicNameValuePair("mode","afiseaza_total"));

【讨论】:

现在有了,还是不行... void afiseaza_total() InputStream is = null;字符串结果 = ""; ArrayList nameValuePairs = new ArrayList(); nameValuePairs.add(new BasicNameValuePair("mode","afiseaza_total"));试试 ... 确保在 httppost.setEntity(new UrlEncodedFormEntity(...)); 处使用正确的数组列表;

以上是关于从mysql json android中检索数据的主要内容,如果未能解决你的问题,请参考以下文章

Android:如何让我检索到的(来自 mysql)JSON 解析数据添加到 ListView 每分钟刷新一次

Android应用程序解码来自PHP MySql数据库的JSON响应,没有特殊字符

从 GET 方法中的 JSON 解析在 android 中检索数据

从 mysql 检索 json 数据并获取值作为对象

通过 JSON 将数据从 android 发送到服务器

android 从 MySql 数据库中检索 blob 图像