我有一个有多个微调器的有趣片段。第一个微调器,根据选择的内容将数据加载到第二个微调器中。它看起来像这样:
当片段首次加载时,第一个微调器是“全部”,它用所有啤酒填充listView。现在这是唯一一个listView我可以点击项目而不强迫关闭。我的投资组合的代码是:
public class Portfolio extends Fragment implements PortfolioGetAllBeers.OnArticleSelectedListener {
String beerId = "";
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
//set layout here
final View theLayout = inflater.inflate(R.layout.activity_portfolio, container, false);
setHasOptionsMenu(true);
getActivity().setTitle("Portfolio");
//get user information
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
String userName = prefs.getString("userName", null);
String userID = prefs.getString("userID", null);
final Spinner portfolioType = (Spinner) theLayout.findViewById(R.id.portfolioSpinner);
portfolioType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
String portfolioChoice = portfolioType.getSelectedItem().toString();
Log.d("portfolio", portfolioChoice);
if( portfolioChoice.equals("All")){
//todo: clear second spinner
LinearLayout ll = (LinearLayout) theLayout.findViewById(R.id.addSpinnerLayout);
ll.removeAllViews();
//get userID
//get user data
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(selectedItemView.getContext());
String userID = prefs.getString("userID", null);
//construct url
String url = "myURL1";
//async task goes here
PortfolioGetAllBeers task = new PortfolioGetAllBeers(getActivity());
task.setOnArticleSelectedListener(Portfolio.this);
task.execute(url);
}
else if (portfolioChoice.equals("Brewery")){
LinearLayout ll = (LinearLayout) theLayout.findViewById(R.id.addSpinnerLayout);
ll.removeAllViews();
LayoutInflater inflater = (LayoutInflater)selectedItemView.getContext().getSystemService(selectedItemView.getContext().LAYOUT_INFLATER_SERVICE);
View v = inflater.inflate(R.layout.addspinner_layout, null); // inflate addspinner
Spinner sp = (Spinner) v.findViewById(R.id.portfolioSpinner2); //portfolioSpinner2
ll.addView(v); // add the view to the linear layout
//todo: get breweries and fill spinner
//get userID
//get user data
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(selectedItemView.getContext());
String userID = prefs.getString("userID", null);
//construct url
String url = ""myurl2;
//async task goes here
PortfolioGetAllBeers task = new PortfolioGetAllBeers(getActivity());
task.setOnArticleSelectedListener(Portfolio.this);
task.execute(url);
}
else if (portfolioChoice.equals("Style")){
LinearLayout ll = (LinearLayout) theLayout.findViewById(R.id.addSpinnerLayout);
ll.removeAllViews();
LayoutInflater inflater = (LayoutInflater)selectedItemView.getContext().getSystemService(selectedItemView.getContext().LAYOUT_INFLATER_SERVICE);
View v = inflater.inflate(R.layout.addspinner_layout, null); // inflate addspinner
Spinner sp = (Spinner) v.findViewById(R.id.portfolioSpinner2); //portfolioSpinner2
ll.addView(v); // add the view to the linear layout
//get userID
//get user data
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(selectedItemView.getContext());
String userID = prefs.getString("userID", null);
//construct url
String url = "myurl3";
//todo: async task goes here
new PortfolioGetAllStyles(selectedItemView.getContext()).execute(url);
}
else if (portfolioChoice.equals("Rating")){
LinearLayout ll = (LinearLayout) theLayout.findViewById(R.id.addSpinnerLayout);
ll.removeAllViews();
LayoutInflater inflater = (LayoutInflater)selectedItemView.getContext().getSystemService(selectedItemView.getContext().LAYOUT_INFLATER_SERVICE);
View v = inflater.inflate(R.layout.addspinner_layout, null); // inflate addspinner
Spinner sp = (Spinner) v.findViewById(R.id.portfolioSpinner2); //portfolioSpinner2
ll.addView(v); // add the view to the linear layout
//get userID
//get user data
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(selectedItemView.getContext());
String userID = prefs.getString("userID", null);
//make array
//make array list for beer
final List<String> tasteList = new ArrayList<String>();
tasteList.add("1");
tasteList.add("2");
tasteList.add("3");
tasteList.add("4");
tasteList.add("5");
// Selection of the spinner
Spinner spinner = (Spinner) theLayout.findViewById(R.id.portfolioSpinner2);
// Application of the Array to the Spinner
ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(selectedItemView.getContext(), android.R.layout.simple_spinner_item,tasteList );
spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // The drop down view
spinner.setAdapter(spinnerArrayAdapter);
//todo: add on select for spinner 2
//add on item selected
final Spinner portfolioType = (Spinner) theLayout.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();
final ListView lv = (ListView) theLayout.findViewById(R.id.allYourBeersList);
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 = "myurl4;
Log.d("portfolio" , url);
//async task goes here
new PortfolioGetAllBeers(selectedItemView.getContext()).execute(url);
}
@Override
public void onNothingSelected(AdapterView<?> parentView) {
// do nothing
}
});
}
}
@Override
public void onNothingSelected(AdapterView<?> parentView) {
// do nothing
}
});
// Inflate the layout for this fragment
return theLayout;
}
@Override
public void onArticleSelected(String bID, String brewery){
//code to execute on click
Fragment Fragment_one;
FragmentManager man= getFragmentManager();
FragmentTransaction tran = man.beginTransaction();
Fragment_one = new BeerPage();
final Bundle bundle = new Bundle();
bundle.putString("beerIDSent", bID);
bundle.putString("breweryIDSent", brewery);
Fragment_one.setArguments(bundle);
tran.replace(R.id.main, Fragment_one);//tran.
tran.addToBackStack(null);
tran.commit();
}
}
如果微调器全部在第一次加载时,它将从上面运行这部分代码:
if( portfolioChoice.equals("All")){
//todo: clear second spinner
LinearLayout ll = (LinearLayout) theLayout.findViewById(R.id.addSpinnerLayout);
ll.removeAllViews();
//get userID
//get user data
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(selectedItemView.getContext());
String userID = prefs.getString("userID", null);
//construct url
String url = "myURL1";
//async task goes here
PortfolioGetAllBeers task = new PortfolioGetAllBeers(getActivity());
task.setOnArticleSelectedListener(Portfolio.this);
task.execute(url);
}
调用此异步任务来加载listview:
public class PortfolioGetAllBeers extends AsyncTask<String, Void, String> {
Context c;
private ProgressDialog Dialog;
public PortfolioGetAllBeers (Context context)
{
c = context;
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 beers");
Dialog.setTitle("Loading");
Dialog.setCancelable(false);
Dialog.show();
}
//***************************code for on click
OnArticleSelectedListener listener;
public interface OnArticleSelectedListener{
public void onArticleSelected(String myString , String brewery);
}
public void setOnArticleSelectedListener(OnArticleSelectedListener listener){
this.listener = listener;
}
//*****************************end code for onClick
protected void onPostExecute(String result){
//decode json here
try{
JSONArray jsonArray = new JSONArray(result);
//acces listview
ListView lv = (ListView) ((Activity) c).findViewById(R.id.allYourBeersList);
//make array list for beer
final List<ShortBeerInfo> tasteList = new ArrayList<ShortBeerInfo>();
for(int i = 0; i < jsonArray.length(); i++) {
String beer = jsonArray.getJSONObject(i).getString("beer");
String rate = jsonArray.getJSONObject(i).getString("rate");
String beerID = jsonArray.getJSONObject(i).getString("id");
String bID = jsonArray.getJSONObject(i).getString("breweryID");
//create object
ShortBeerInfo tempTaste = new ShortBeerInfo(beer, rate, beerID, bID);
//add to arraylist
tasteList.add(tempTaste);
}
//add items to listview
ShortBeerInfoAdapter adapter1 = new ShortBeerInfoAdapter(c ,R.layout.brewer_stats_listview, tasteList);
lv.setAdapter(adapter1);
//set up clicks
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
ShortBeerInfo o=(ShortBeerInfo)arg0.getItemAtPosition(arg2);
String tempID = o.id;
String tempBrewID = o.brewery;
//todo: go to beer page
listener.onArticleSelected(tempID, tempBrewID);
}
});
}
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();
}
}
当这加载带有项目的列表视图时,onclicks可以通过界面正常工作。当第二个微调器将数据加载到列表视图中时,我无法为其他选项执行界面操作。
例如,如果您在第一个微调器中选择样式,在第二个微调器中选择一个选项,如上面发布的图片所示。它在上面的Portfolio中的代码中运行if语句:
else if (portfolioChoice.equals("Style")){
LinearLayout ll = (LinearLayout) theLayout.findViewById(R.id.addSpinnerLayout);
ll.removeAllViews();
LayoutInflater inflater = (LayoutInflater)selectedItemView.getContext().getSystemService(selectedItemView.getContext().LAYOUT_INFLATER_SERVICE);
View v = inflater.inflate(R.layout.addspinner_layout, null); // inflate addspinner
Spinner sp = (Spinner) v.findViewById(R.id.portfolioSpinner2); //portfolioSpinner2
ll.addView(v); // add the view to the linear layout
//get userID
//get user data
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(selectedItemView.getContext());
String userID = prefs.getString("userID", null);
//construct url
String url = "myurl3";
//todo: async task goes here
new PortfolioGetAllStyles(selectedItemView.getContext()).execute(url);
}
当PortfolioGetAllStyles asyc任务执行时,我不知道如何设置onclick到界面。 PortfolioGetAllStyles的代码是:
public class PortfolioGetAllStyles extends AsyncTask<String, Void, String> {
Context c;
private ProgressDialog Dialog;
public PortfolioGetAllStyles (Context context)
{
c = context;
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>();
for(int i = 0; i < jsonArray.length(); i++) {
String beer = jsonArray.getJSONObject(i).getString("style");
String bID = jsonArray.getJSONObject(i).getString("breweryID");
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 = "http://beerportfolio.com/app_getAllYourBeersStyle.php?u=" + userID + "&b=" + portfolioChoice;
Log.d("portfolio", url);
//async task goes here
new PortfolioGetAllBeers(selectedItemView.getContext()).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();
}
}
我得到的错误是:
03-03 14:30:00.495 20817-20817/com.beerportfolio.beerportfoliopro E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.NullPointerException
at com.beerportfolio.beerportfoliopro.PortfolioGetAllBeers$1.onItemClick(PortfolioGetAllBeers.java:114)
at android.widget.AdapterView.performItemClick(AdapterView.java:298)
at android.widget.AbsListView.performItemClick(AbsListView.java:1237)
at android.widget.ListView.performItemClick(ListView.java:4555)
at android.widget.AbsListView$PerformClick.run(AbsListView.java:3037)
at android.widget.AbsListView$1.run(AbsListView.java:3724)
at android.os.Handler.handleCallback(Handler.java:730)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:158)
at android.app.ActivityThread.main(ActivityThread.java:5789)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1027)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:843)
at dalvik.system.NativeStart.main(Native Method)
简而言之 我认为我需要让这些行能够将OnSelectedListener从投资组合页面绑定到此异步任务:
PortfolioGetAllBeers task = new PortfolioGetAllBeers(c);
task.setOnArticleSelectedListener(Portfolio.this);
task.execute(url);
我无法将Portfolio.this传递到该行,因为我们不在Portfolio中,而是从它启动了另一个异步任务。
答案 0 :(得分:0)
似乎在这一行:
new PortfolioGetAllBeers(selectedItemView.getContext()).execute(url);
您正在创建并触发设置侦听器的异步任务。所以你应该做以下事情之一:
在执行创建的异步任务之前始终设置侦听器
在调用之前检查侦听器是否为null:
if(listener != null){
listener.onArticleSelected(tempID, tempBrewID);
}