来自JSON的Android Spinner

时间:2013-10-30 23:38:40

标签: android json android-spinner

在我的新Android应用中,我有一个来自JSON调用填充ListView的视图,该视图正常运行。但我现在需要的是Spinner填充与ListView相同的数据。

但是经过两天的努力,我无法做到。布局XML文件中的新Spinner ID为spinner2。如您在代码中所见,Spinner1填充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);
                }
            });

        }

    }

}

0 个答案:

没有答案