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

标签 php android mysql 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;
    }

        }

这是所有类别:LogCat

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

最佳答案

您的代码相当困惑 - 可能是在您为使事情正常工作所做的所有不同尝试之后 - 但我认为主要问题区域在 doInBackground()onPostExecute().

花了一分钟时间清理代码后,一切都工作正常,这意味着您已经快成功了。我主要简化了JSON解析逻辑;也就是说,您不需要 Map,您应该做的就是将每个类别添加到稍后输入微调器适配器的列表中。请参阅下面的代码 fragment - 如果您发现以前拥有的任何变量现在丢失了,这可能意味着我删除了它们,因为它们不再需要了。

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 线程上运行,因此无需在 Handler 上发布 Runnable。这里直接触摸view就可以了。唯一的其他更改是向适配器提供 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);
}

关于php - 无法将 JSON 数据正确加载到 Spinner 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17080471/

相关文章:

php - 如何允许用户根据一定数量的列选择他们想要保留的重复元素(MySQL PHP)

javascript - PHP 中的表单自动刷新 DIV 标记不起作用

php - 如何从我的 ajax php 函数中获取 html 和 javascript?

c# - "GenerateJavaStubs"任务失败

java - 打开相机拍摄照片或画廊选择图像后,应用程序语言(语言环境)自动重置为默认值

c# - MySql Connection 未使用 .net MySql Connector 关闭

PHP 错误 : Warning: Cannot modify header information - headers already sent by

android - Android SDK 23 中的 Non Scroll RecyclerView 滚动问题

MySQL 查询 - 选择邮政编码匹配

Mysql 无法在 Mac OSX 上启动?