0

我已经尝试了大约 2 周来尝试将 ArrayList 加载到微调器。从以下代码中注释掉的尝试中可以看出,我运气不佳。我在代码中留下了注释来告诉你我已经尝试了数百种方法来做到这一点。我可以将数据发送到微调器,但它没有正确显示。我试图获取密钥:从 hashmap 中获取数据,将 arraylist 加载到微调器,从 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"}]}
4

1 回答 1

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 线程上运行,因此无需RunnableHandler. 可以直接在这里触摸视图。唯一的其他更改是向适配器提供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);
}
于 2013-06-13T19:28:20.980 回答