无法正确地将JSON数据加载到Spinner中

时间:2013-06-13 06:21:15

标签: php android mysql spinner

我已经尝试了大约2周的时间来尝试将ArrayList加载到微调器。从下面代码中注释掉的尝试中可以看出,我没有太多运气。我在代码中留下了评论,告诉你我已经尝试了数百种方法来做到这一点。我可以将数据传递给微调器,但它没有正确显示。我试图获取密钥:来自hashmap的数据,将arraylist加载到spinner,从arraylist获取对象等等。我不是很擅长Java / Android但是VB很优秀。我一直在用Android努力奋斗。我希望在这个问题上得到一些帮助。先感谢您。再次感谢。

我尝试上传图片,但我的代表是1.所以,这是我得到的:

THIS IS THE RESPONSE:
{"category":"Accessories"}
{"category":"Battery Packs"}
{"category":"Hunting Lights"}
{"category":"Other"}




 import java.util.ArrayList;
    import java.util.HashMap;

import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.SyncStateContract.Constants;
import android.util.Log;
import android.view.Menu;
import android.widget.ArrayAdapter;
import android.widget.Spinner;

public class Shop extends Activity {
    //PHP to get catagories
    public static String url_to_send = "http://xxx.xxx.xxx.xxx/load_catagories.php";
    //TAG to send to PHP to retrieve catagories
    private static final String TAG_CATAGORIES= "catagories";
    private static final String TAG_CATAGORY= "catagory";
    //Success tag
    private static final String TAG_SUCCESS = "success";
    //Dialog
    ProgressDialog pDialog;
    //JSON Parser
    JSONParser jParser = new JSONParser();
    JSONArray catagories = null;
    Spinner MySpinner;
    ArrayList<HashMap<String, String>> catagoryList;
    List<String> items;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shop);
        MySpinner = (Spinner)findViewById(R.id.spinner1);

        // Hashmap for ListView
        catagoryList = new ArrayList<HashMap<String, String>>();

        new LoadAllProducts().execute();
    }
    String theCatagory;
    class LoadAllProducts extends AsyncTask<String, String, String> {

        /**
         * Before starting background thread Show Progress Dialog
         * */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(Shop.this);
            pDialog.setMessage("Loading Catagories. Please wait...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(false);
            pDialog.show();
        }

        /**
         * getting All products from url
         * */
        protected String doInBackground(String... args) {
            // Building Parameters
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            // getting JSON string from URL
            JSONObject json = jParser.makeHttpRequest(url_to_send, "GET", params);

            // Check your log cat for JSON reponse
            Log.d("All Catagories: ", json.toString());

            try {
                // Checking for SUCCESS TAG
                int success = json.getInt(TAG_SUCCESS);

                if (success == 1) {
                    // products found
                    // Getting Array of Products
                    catagories = json.getJSONArray(TAG_CATAGORIES);

                    // looping through All Products
                    items = new ArrayList<String>();
                    for (int i = 0; i < catagories.length(); i++) {
                        JSONObject c = catagories.getJSONObject(i);
                        items.add(catagories.getString(i));

                        // Storing each json item in variable
                        theCatagory = c.getString(TAG_CATAGORY);


                        // creating new HashMap
                        HashMap<String, String> map = new HashMap<String, String>();

                        // adding each child node to HashMap key => value
                        map.put(TAG_CATAGORY, theCatagory);
                        // adding HashList to ArrayList
                        catagoryList.add(map);



                    }

                } else {
                    // no products found
                    // Launch Add New product Activity

                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

            return null;
        }

        /**
         * After completing background task Dismiss the progress dialog
         * **/
        protected void onPostExecute(String file_url) {
            // dismiss the dialog after getting all products
            pDialog.dismiss();
            // updating UI from Background Thread
            runOnUiThread(new Runnable() {
                public void run() {
                    /**
                     * Updating parsed JSON data into ListView
                     * */
                //  ListAdapter adapter = new SimpleAdapter(MainActivity.this, productsList,R.layout.list_item, new String[] { TAG_PID,TAG_NAME},new int[] { R.id.pid, R.id.name });
                    //setListAdapter(adapter);
                    //ListAdapter adapter=new LazyAdapter(Shop.this, catagoryList);
                    //list.setAdapter(adapter);
                    //setListAdapter(adapter);

                    //String[] myData = {};
              //  myData = catagoryList.toArray(new String[catagoryList.size()]);
    // SimpleAdapter adapter = new SimpleAdapter(Shop.this, catagoryList,R.layout.list_item, new String[] { TAG_CATAGORY},new int[] { theCatagory });
                    // MySpinner.setAdapter(adapter);



    //ArrayAdapter<String> adapter = new ArrayAdapter<String> (Shop.this, android.R.layout.simple_spinner_item, catagoryList);       
                  //  MySpinner.setAdapter(adapter);

                    //ArrayList<String> list=new ArrayList<String>();
                //for(int i=0;i<catagories.length();i++)
                    //{

                        //try {
                        //list.add(catagories.getString(i));
                        //} catch (JSONException e) {
                        // TODO Auto-generated catch block
                        //  e.printStackTrace();
                        //}

                        //  }

        String [] anArrayOfStrings = new String[theCatagory.length()];
                            items.toArray(anArrayOfStrings);




                            ArrayAdapter<String>spinnerMenu = new ArrayAdapter<String(Shop.this,android.R.layout.simple_list_item_1,anArrayOfStrings);
        MySpinner.setAdapter(spinnerMenu);








                }

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

        }

以下是所有Catagories:LogCat

06-13 10:50:59.120: D/All Catagories:(5329): {"success":1,"catagories":[{"catagory":"Accessories"},{"catagory":"Battery Packs"},{"catagory":"Hunting Lights"}]}

1 个答案:

答案 0 :(得分:1)

您的代码相当混乱 - 可能是在您为使事情正常工作而进行的所有不同尝试之后 - 但我认为主要问题区域位于doInBackground()onPostExecute()

花了一分钟来清理你的代码后,一切都变得很好,这意味着你几乎就在那里。我主要简化了JSON解析逻辑;即你不需要Map,你应该做的只是将每个类别添加到一个列表中,该列表稍后将被输入到微调器适配器中。请参阅下面的代码片段 - 如果您发现以前的任何变量现在都丢失了,这可能意味着我删除了它们,因为它们不再需要了。

List<String> items = new ArrayList<String>();

/**
 * getting All products from url
 * */
protected String doInBackground(String... args) {
    try {
        // Building Parameters
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        // getting JSON string from URL
        JSONObject json = jParser.makeHttpRequest(url_to_send, "GET", params);

        // Check your log cat for JSON reponse
        Log.d("All Catagories: ", json.toString());

        // Checking for SUCCESS TAG
        int success = json.getInt(TAG_SUCCESS);

        if (success == 1) {
            // products found
            // Getting Array of Products
            JSONArray catagories = json.getJSONArray(TAG_CATAGORIES);

            // looping through All Products
            for (int i = 0; i < catagories.length(); i++) {
                JSONObject c = catagories.getJSONObject(i);

                // Storing each json item in variable
                String category = c.getString(TAG_CATAGORY);

                items.add(category);
            }

        } else {
            // no products found
            // Launch Add New product Activity

        }
    } catch (JSONException e) {
        e.printStackTrace();
    }

    return null;
}

然后onPostExecute(),我从中删除了所有注释行。此外,此方法已在UI线程上运行,因此无需在Runnable上发布Handler。可以直接在这里触摸视图。唯一的另一个变化是将items(我们填充了doInBackground()中的类别)提供给适配器。

/**
 * After completing background task Dismiss the progress dialog
 * **/
protected void onPostExecute(String file_url) {
    // dismiss the dialog after getting all products
    pDialog.dismiss();

    ArrayAdapter<String> spinnerMenu = new ArrayAdapter<String>(Shop.this, android.R.layout.simple_list_item_1, items);
    MySpinner.setAdapter(spinnerMenu);
}