gpt4 book ai didi

java - Android 旋转器与对象

转载 作者:行者123 更新时间:2023-12-02 06:00:42 25 4
gpt4 key购买 nike

我有一个异步任务,它用数据填充微调器。微调器数据来自列表中的对象。我的问题是,当我为列表中的项目设置 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();

更新:

我已将上面的代码更改为以下内容以合并自定义适配器:

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;
}
}

最佳答案

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

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

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

关于java - Android 旋转器与对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22700734/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com