1

在我的新 Android 应用程序中,我有一个ListView从 JSON 调用填充的视图,它正在工作。但我现在需要的是一个SpinnerListView.

但是经过两天的尝试,我无法做到。其布局 XML 文件中的新Spinnerid 是spinner2. 如您在代码中所见,Spinner1从 a 填充。String[]

public class HiScreen extends ListActivity {

    String[] spinnerValues = { "1","2","3"};

    // Progress Dialog
    private ProgressDialog pDialog;

    // Creating JSON Parser object
    JSONParser jParser = new JSONParser();

    ArrayList<HashMap<String, String>> newsList;

    // url to get all products list
    private static String url_all_news = "";

    // JSON Node names
    private static final String TAG_SUCCESS = "success";
    private static final String TAG_NEWS = "news";
    private static final String TAG_ID = "id";
    private static final String TAG_HEADER = "header";
    private static final String TAG_BODY = "body";
    private static final String TAG_TIME = "time";

    // products JSONArray
    JSONArray news = null;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.all_news);

        Spinner mySpinner = (Spinner) findViewById(R.id.spinner1);
        mySpinner.setAdapter(new MyAdapter(this, R.layout.custom_spinner,
            spinnerValues));

        Spinner s = (Spinner) findViewById( R.id.spinner2 );

        String user,server_url;

        Bundle extras = getIntent().getExtras();
        // Obtenemos datos enviados en el intent.
        if (extras != null) {
            user  = extras.getString("user");//usuario
            server_url = extras.getString("server");
            url_all_news = server_url+"android_get_all_news.php";
        } else {
            user="error";
        }

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

        // Loading products in Background Thread
        new LoadAllProducts().execute();

        // Get listview
        ListView lv = getListView();

        // on seleting single product
        // launching Edit Product Screen
        ;

    }

    public class MyAdapter extends ArrayAdapter<String> {

        public MyAdapter(Context ctx, int txtViewResourceId, String[] objects) {
            super(ctx, txtViewResourceId, objects);
        }

        @Override
        public View getDropDownView(int position, View cnvtView, ViewGroup prnt) {
            return getCustomView(position, cnvtView, prnt);
        }

        @Override
        public View getView(int pos, View cnvtView, ViewGroup prnt) {
            return getCustomView(pos, cnvtView, prnt);
        }

        public View getCustomView(int position, View convertView,
            ViewGroup parent) {
            LayoutInflater inflater = getLayoutInflater();
            View mySpinner = inflater.inflate(R.layout.custom_spinner, parent,
                false);
            TextView main_text = (TextView) mySpinner                   .findViewById(R.id.text_main_seen);
            main_text.setText(spinnerValues[position]);

            TextView subSpinner = (TextView) mySpinner
                .findViewById(R.id.sub_text_seen);
            subSpinner.setText(spinnerSubs[position]);

            ImageView left_icon = (ImageView) mySpinner
                .findViewById(R.id.left_pic);
            left_icon.setImageResource(total_images[position]);

            return mySpinner;
        }
    }


    // Response from Edit Product Activity
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // if result code 100
        if (resultCode == 100) {
            // if result code 100 is received 
            // means user edited/deleted product
            // reload this screen again
            Intent intent = getIntent();
            finish();
            startActivity(intent);
        }

    }

    /**
     * Background Async Task to Load all product by making HTTP Request
     * */
    class LoadAllProducts extends AsyncTask<String, String, String> {

        /**
        * Before starting background thread Show Progress Dialog
        * */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(HiScreen.this);
            pDialog.setMessage("Loading News. Bitte warten...");
            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_all_news, "GET", params);

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

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

                if (success == 1) {
                    // products found
                    // Getting Array of Products
                    news = json.getJSONArray(TAG_NEWS);
                    String[] datos = new String[news.length()];
                    // looping through All Products
                    for (int i = 0; i < news.length(); i++) {
                        JSONObject c = news.getJSONObject(i);


                        // Storing each json item in variable
                        datos[i] = c.getString(TAG_HEADER);                 

                        String id = c.getString(TAG_ID);
                        String header = c.getString(TAG_HEADER);
                        String body = c.getString(TAG_BODY);
                        String time = c.getString(TAG_TIME);

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

                        // adding each child node to HashMap key => value
                        map.put(TAG_ID, id);
                        map.put(TAG_HEADER, header);
                        map.put(TAG_BODY, body);
                        map.put(TAG_TIME, time);

                        // adding HashList to ArrayList
                        newsList.add(map);

                    }
                } else {
                    // no products found
                    // Launch Add New product Activity
                    Intent i = new Intent(getApplicationContext(),
                        HiScreen.class);
                    // Closing all previous activities
                    i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    startActivity(i);
                }
            } 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(
                        HiScreen.this, newsList,
                        R.layout.list_item, new String[] { TAG_ID,
                            TAG_HEADER,TAG_BODY,TAG_TIME},
                        new int[] { R.id.pid, R.id.name,R.id.body,R.id.time });
                    // updating listview
                    setListAdapter(adapter);
                }
            });

        }

    }

}
4

1 回答 1

0

您可以从 json 创建 String Array 或 ArrayList,之后您可以将其添加到数组适配器中,这样您就可以轻松地将数据添加到 spinner。

于 2013-10-31T05:40:06.907 回答