带有对象的Android微调器

时间:2014-03-27 22:40:06

标签: java android object

我有一个异步任务,用数据填充微调器。微调器数据来自列表中的对象。我的问题是当我为列表中的项目设置onclick监听器时,我也希望来自对象的id不仅仅是名称:

public class PortfolioGetAllLists extends AsyncTask<String, Void, String> {

    Context c;
    PortfolioGetAllBeers.OnArticleSelectedListener useThis;

    private ProgressDialog Dialog;

    public PortfolioGetAllLists (Context context, PortfolioGetAllBeers.OnArticleSelectedListener thisListener)
    {
        c = context;
        useThis = thisListener;
        Dialog = new ProgressDialog(c);
    }

    @Override
    protected String doInBackground(String... arg0) {
        // TODO Auto-generated method stub
        return readJSONFeed(arg0[0]);
    }

    protected void onPreExecute() {
        Dialog.setMessage("Getting Brewery List");

        Dialog.setTitle("Loading");
        Dialog.setCancelable(false);
        Dialog.show();
    }

    protected void onPostExecute(String result){
        //decode json here
        try{
            JSONArray jsonArray = new JSONArray(result);


            //acces listview
            final ListView lv = (ListView) ((Activity) c).findViewById(R.id.allYourBeersList);

            //make array list for beer
            final List<String> tasteList = new ArrayList<String>();


            tasteList.add("");
            for(int i = 0; i < jsonArray.length(); i++) {

                String bID = jsonArray.getJSONObject(i).getString("id");

                String beer = jsonArray.getJSONObject(i).getString("name");
                String rate = "na";
                String beerID = "na";


                //create object
                ShortBeerInfo tempTaste = new ShortBeerInfo(beer, rate, beerID, bID);

                //add to arraylist
                tasteList.add(beer);
            }


            // Selection of the spinner
            Spinner spinner = (Spinner) ((Activity) c).findViewById(R.id.portfolioSpinner2);

            // Application of the Array to the Spinner
            ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(c,   android.R.layout.simple_spinner_item,tasteList );
            spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // The drop down view
            spinner.setAdapter(spinnerArrayAdapter);

            //add on item selected
            final Spinner portfolioType = (Spinner) ((Activity) c).findViewById(R.id.portfolioSpinner2);
            portfolioType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {


                @Override
                public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {

                    String portfolioChoice = portfolioType.getSelectedItem().toString();

                    //Toast.makeText(((Activity) c).getApplicationContext(), portfolioChoice, Toast.LENGTH_LONG).show();

                    lv.setAdapter(null);

                    //get brewery beers
                    //get userID
                    //get user data
                    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(selectedItemView.getContext());
                    String userID = prefs.getString("userID", null);



                    try {

                        portfolioChoice = URLEncoder.encode(portfolioChoice, "UTF-8");
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }

                    //construct url
                    String url = "myURL";

                    Log.d("portfolio", url);
                    //async task goes here
                    //new PortfolioGetAllBeers(selectedItemView.getContext()).execute(url);

                    PortfolioGetAllBeers task = new PortfolioGetAllBeers(c);
                    task.setOnArticleSelectedListener(useThis);
                    task.execute(url);

                }



                @Override
                public void onNothingSelected(AdapterView<?> parentView) {
                    // do nothing
                }

            });



        }
        catch(Exception e){

        }

        Dialog.dismiss();

    }

    public String readJSONFeed(String URL) {
        StringBuilder stringBuilder = new StringBuilder();
        HttpClient httpClient = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(URL);
        try {
            HttpResponse response = httpClient.execute(httpGet);
            StatusLine statusLine = response.getStatusLine();
            int statusCode = statusLine.getStatusCode();
            if (statusCode == 200) {
                HttpEntity entity = response.getEntity();
                InputStream inputStream = entity.getContent();
                BufferedReader reader = new BufferedReader(
                        new InputStreamReader(inputStream));
                String line;
                while ((line = reader.readLine()) != null) {
                    stringBuilder.append(line);
                }
                inputStream.close();
            } else {
                Log.d("JSON", "Failed to download file");
            }
        } catch (Exception e) {
            Log.d("readJSONFeed", e.getLocalizedMessage());
        }
        return stringBuilder.toString();
    }

}

以下这一行是获取啤酒名称的行,但我不知道如何从设置listview名称的对象获取id:

String portfolioChoice = portfolioType.getSelectedItem().toString();

Update:

我已将上面的代码更改为包含自定义适配器:

public class PortfolioGetAllLists extends AsyncTask<String, Void, String> {

    Context c;
    PortfolioGetAllBeers.OnArticleSelectedListener useThis;

    private ProgressDialog Dialog;

    public PortfolioGetAllLists (Context context, PortfolioGetAllBeers.OnArticleSelectedListener thisListener)
    {
        c = context;
        useThis = thisListener;
        Dialog = new ProgressDialog(c);
    }

    @Override
    protected String doInBackground(String... arg0) {
        // TODO Auto-generated method stub
        return readJSONFeed(arg0[0]);
    }

    protected void onPreExecute() {
        Dialog.setMessage("Getting Brewery List");

        Dialog.setTitle("Loading");
        Dialog.setCancelable(false);
        Dialog.show();
    }

    protected void onPostExecute(String result){
        //decode json here
        try{
            JSONArray jsonArray = new JSONArray(result);


            //acces listview
            final ListView lv = (ListView) ((Activity) c).findViewById(R.id.allYourBeersList);

            //make array list for beer
            final List<ShortBeerInfo> tasteList = new ArrayList<ShortBeerInfo>();


            //tasteList.add("");
            for(int i = 0; i < jsonArray.length(); i++) {

                String bID = jsonArray.getJSONObject(i).getString("id");

                String beer = jsonArray.getJSONObject(i).getString("name");
                String rate = "na";
                String beerID = "na";


                //create object
                ShortBeerInfo tempTaste = new ShortBeerInfo(beer, rate, beerID, bID);

                //add to arraylist
                tasteList.add(tempTaste);
            }


            // Selection of the spinner
            Spinner spinner = (Spinner) ((Activity) c).findViewById(R.id.portfolioSpinner2);

            // Application of the Array to the Spinner
            ShortBeerInfoAdapter<ShortBeerInfo> spinnerArrayAdapter = new ArrayAdapter<ShortBeerInfo>(c,   android.R.layout.simple_spinner_item,tasteList );
            spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // The drop down view
            spinner.setAdapter(spinnerArrayAdapter);

            //add on item selected
            final Spinner portfolioType = (Spinner) ((Activity) c).findViewById(R.id.portfolioSpinner2);
            portfolioType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {


                @Override
                public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {

                    String portfolioChoice = portfolioType.getSelectedItem().toString();


                    //Toast.makeText(((Activity) c).getApplicationContext(), portfolioChoice, Toast.LENGTH_LONG).show();

                    lv.setAdapter(null);

                    //get brewery beers
                    //get userID
                    //get user data
                    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(selectedItemView.getContext());
                    String userID = prefs.getString("userID", null);



                    try {

                        portfolioChoice = URLEncoder.encode(portfolioChoice, "UTF-8");
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }

                    //construct url
                    String url = "myURL";    
                    Log.d("portfolio", url);
                    //async task goes here
                    //new PortfolioGetAllBeers(selectedItemView.getContext()).execute(url);

                    PortfolioGetAllBeers task = new PortfolioGetAllBeers(c);
                    task.setOnArticleSelectedListener(useThis);
                    task.execute(url);

                }



                @Override
                public void onNothingSelected(AdapterView<?> parentView) {
                    // do nothing
                }

            });



        }
        catch(Exception e){

        }

        Dialog.dismiss();

    }

    public String readJSONFeed(String URL) {
        StringBuilder stringBuilder = new StringBuilder();
        HttpClient httpClient = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(URL);
        try {
            HttpResponse response = httpClient.execute(httpGet);
            StatusLine statusLine = response.getStatusLine();
            int statusCode = statusLine.getStatusCode();
            if (statusCode == 200) {
                HttpEntity entity = response.getEntity();
                InputStream inputStream = entity.getContent();
                BufferedReader reader = new BufferedReader(
                        new InputStreamReader(inputStream));
                String line;
                while ((line = reader.readLine()) != null) {
                    stringBuilder.append(line);
                }
                inputStream.close();
            } else {
                Log.d("JSON", "Failed to download file");
            }
        } catch (Exception e) {
            Log.d("readJSONFeed", e.getLocalizedMessage());
        }
        return stringBuilder.toString();
    }

}

但在这一行:

    ShortBeerInfoAdapter<ShortBeerInfo> spinnerArrayAdapter = new ArrayAdapter<ShortBeerInfo>(c,   android.R.layout.simple_spinner_item,tasteList );

我的shortbeerinfoadapter没有类型参数

我的短啤酒信息适配器是:

public class ShortBeerInfoAdapter extends ArrayAdapter<ShortBeerInfo> {

    Context context;
    int layoutResourceId;
    List<ShortBeerInfo> data = null;

    public ShortBeerInfoAdapter(Context context, int layoutResourceId, List<ShortBeerInfo> data) {
        super(context, layoutResourceId, data);
        this.layoutResourceId = layoutResourceId;
        this.context = context;
        this.data = data;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View row = convertView;
        beerHolder holder = null;

        if(row == null)
        {
            LayoutInflater inflater = ((Activity)context).getLayoutInflater();
            row = inflater.inflate(layoutResourceId, parent, false);

            holder = new beerHolder();
            holder.txtBeer = (TextView)row.findViewById(R.id.breweryName);
            holder.txtRate = (TextView)row.findViewById(R.id.breweryRate);
            holder.txtBar = (RatingBar) row.findViewById(R.id.starbar);

            row.setTag(holder);
        }
        else
        {
            holder = (beerHolder)row.getTag();
        }

        ShortBeerInfo beer = data.get(position);
        holder.txtBeer.setText(beer.beer);
        holder.txtRate.setText(beer.rate + " out of 5.00 Stars");

        holder.numHolder= Float.parseFloat(beer.rate);

        holder.txtBar.setNumStars(5);
        holder.txtBar.setRating(holder.numHolder);

        return row;
    }

    static class beerHolder
    {
        TextView txtBeer;
        TextView txtRate;
        RatingBar txtBar;
        Float numHolder;
    }
}

1 个答案:

答案 0 :(得分:2)

您有ShortBeerInfo,其中包含名称和ID。您获取啤酒名称,将其添加到字符串列表中,然后从该列表中创建ArrayAdapter。 ArrayAdapter仅包含名称。

要获取ID,您需要一个ShortBeerInfo类型的自定义数组适配器。您需要在适配器中重写OnCreateView,以便为仅包含啤酒名称的列表项创建View对象。 (或者您可能希望显示的任何其他啤酒信息)

然后在你的选择监听器中,getSelectedItem将返回一个ShortBeerInfo,其中包含所选啤酒的ID。