我正在尝试开发listview下拉列表,但是,当我运行应用程序时,我看不到listview下拉列表,它应该显示来自strings.xml的各种选项我在尝试实现OnitemSelecteListener时遇到了一些错误。
PlaceActivity.Java
public class PlaceActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
public ArrayList<GetterSetter> myArrayList;
private Toolbar toolbar;
private Spinner spinner;
ListView myList;
private String[] places;
ProgressDialog dialog;
TextView nodata;
PlaceAdapter adapter;
GetterSetter addValues;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_place);
if (!isNetworkAvailable()) {
Toast.makeText(getApplicationContext(), "Enable internet connection and RE-LAUNCH!!",
Toast.LENGTH_LONG).show();
return;
}
myList = (ListView) findViewById(R.id.myList);
toolbar = (Toolbar) findViewById(R.id.tool_bar);
places = getResources().getStringArray(R.array.places);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
setTitle("Title");
spinner = (Spinner) findViewById(R.id.spinnerplaces);
// Create an ArrayAdapter using the string array and a default spinner
ArrayAdapter<CharSequence> listAdapter = ArrayAdapter
.createFromResource(this, R.array.places,
android.R.layout.simple_spinner_item);
// Specify the layout to use when the list of choices appears
listAdapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
spinner.setAdapter(listAdapter);
}
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null;
}
public void onItemSelected(AdapterView<?> parent, View view, int itemPosition, long itemId) {
dialog = ProgressDialog.show(this, "", "Please wait", true);
// Google Places Access key and location values.
new readFromGooglePlaceAPI()
.execute("https://maps.googleapis.com/maps/api/place/nearbysearch/json?"
+ "location=53.795984,-1.759398&radius=900&sensor=true&"
+ "key=API_Key&types="
+ places[itemPosition]);
myList.OnItemSelectedListener (this);
return true;
}
public class readFromGooglePlaceAPI extends AsyncTask<String, Void, String> {
@Override protected String doInBackground(String... param) {
return readJSON(param[0]);
}
protected void onPostExecute(String str) {
myArrayList = new ArrayList<GetterSetter>();
try {
JSONObject root = new JSONObject(str);
JSONArray results = root.getJSONArray("results");
for (int i = 0; i < results.length(); i++) {
JSONObject arrayItems = results.getJSONObject(i);
JSONObject geometry = arrayItems.getJSONObject("geometry");
JSONObject location = geometry.getJSONObject("location");
addValues = new GetterSetter();
addValues.setLat(location.getString("lat"));
addValues.setLon(location.getString("lng"));
addValues.setName(arrayItems.getString("name").toString());
addValues.setRating(arrayItems.getString("rating").toString());
addValues.setVicinity(arrayItems.getString("vicinity").toString());
myArrayList.add(addValues);
Log.d("Before", myArrayList.toString());
}
} catch (Exception e) {
}
System.out
.println("############################################################################");
Log.d("After:", myArrayList.toString());
nodata = (TextView) findViewById(R.id.nodata);
nodata.setVisibility(View.GONE);
adapter = new PlaceAdapter(PlaceActivity.this, R.layout.list_row, myArrayList);
myList.setAdapter(adapter);
adapter.notifyDataSetChanged();
dialog.dismiss();
}
}
public String readJSON(String URL) {
StringBuilder sb = new StringBuilder();
HttpGet httpGet = new HttpGet(URL);
HttpClient client = new DefaultHttpClient();
try {
HttpResponse response = client.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
if (statusLine.getStatusCode() == 200) {
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
} else {
Log.e("JSON", "Couldn't find JSON file");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return sb.toString();
}
@Override public void onNothingSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
Intent details = new Intent(PlaceActivity.this, Details.class);
details.putExtra("name", myArrayList.get(arg2).getName());
details.putExtra("rating", myArrayList.get(arg2).getRating());
details.putExtra("vicinity", myArrayList.get(arg2).getVicinity());
details.putExtra("lat", myArrayList.get(arg2).getLat());
details.putExtra("lon", myArrayList.get(arg2).getLon());
startActivity(details);
}
错误1 - 类必须在AdapterView.OnItemSelectedListener上声明为abstract或实现抽象方法。
public class PlaceActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
错误2 - 方法不会覆盖其超类。
@Override public void onNothingSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
Intent details = new Intent(PlaceActivity.this, Details.class);
details.putExtra("name", myArrayList.get(arg2).getName());
details.putExtra("rating", myArrayList.get(arg2).getRating());
details.putExtra("vicinity", myArrayList.get(arg2).getVicinity());
details.putExtra("lat", myArrayList.get(arg2).getLat());
details.putExtra("lon", myArrayList.get(arg2).getLon());
startActivity(details);
}
答案 0 :(得分:0)
我想你忘了添加spinner.setAdapter(list);在onCreate()
的末尾您可以使用它来实现OnItemSelectedListener:
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
这样的事情:
public class PlaceActivity extends AppCompatActivity {
public ArrayList<GetterSetter> myArrayList;
private Toolbar toolbar;
private Spinner spinner;
ListView myList;
private String[] places;
ProgressDialog dialog;
TextView nodata;
PlaceAdapter adapter;
GetterSetter addValues;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_place);
if (!isNetworkAvailable()) {
Toast.makeText(getApplicationContext(), "Enable internet connection and RE-LAUNCH!!",
Toast.LENGTH_LONG).show();
return;
}
myList = (ListView) findViewById(R.id.myList);
toolbar = (Toolbar) findViewById(R.id.tool_bar);
places = getResources().getStringArray(R.array.places);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
setTitle("Title");
spinner = (Spinner) findViewById(R.id.spinnerplaces);
// Create an ArrayAdapter using the string array and a default spinner
ArrayAdapter<CharSequence> listAdapter = ArrayAdapter
.createFromResource(this, R.array.places,
android.R.layout.simple_spinner_item);
// Specify the layout to use when the list of choices appears
listAdapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
spinner.setAdapter(listAdapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
Intent details = new Intent(PlaceActivity.this, Details.class);
details.putExtra("name", myArrayList.get(arg2).getName());
details.putExtra("rating", myArrayList.get(arg2).getRating());
details.putExtra("vicinity", myArrayList.get(arg2).getVicinity());
details.putExtra("lat", myArrayList.get(arg2).getLat());
details.putExtra("lon", myArrayList.get(arg2).getLon());
startActivity(details);
}
});
}
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null;
}
public void onItemSelected(AdapterView<?> parent, View view, int itemPosition, long itemId) {
dialog = ProgressDialog.show(this, "", "Please wait", true);
// Google Places Access key and location values.
new readFromGooglePlaceAPI()
.execute("https://maps.googleapis.com/maps/api/place/nearbysearch/json?"
+ "location=53.795984,-1.759398&radius=900&sensor=true&"
+ "key=API_Key&types="
+ places[itemPosition]);
myList.OnItemSelectedListener (this);
return true;
}
public class readFromGooglePlaceAPI extends AsyncTask<String, Void, String> {
@Override protected String doInBackground(String... param) {
return readJSON(param[0]);
}
protected void onPostExecute(String str) {
myArrayList = new ArrayList<GetterSetter>();
try {
JSONObject root = new JSONObject(str);
JSONArray results = root.getJSONArray("results");
for (int i = 0; i < results.length(); i++) {
JSONObject arrayItems = results.getJSONObject(i);
JSONObject geometry = arrayItems.getJSONObject("geometry");
JSONObject location = geometry.getJSONObject("location");
addValues = new GetterSetter();
addValues.setLat(location.getString("lat"));
addValues.setLon(location.getString("lng"));
addValues.setName(arrayItems.getString("name").toString());
addValues.setRating(arrayItems.getString("rating").toString());
addValues.setVicinity(arrayItems.getString("vicinity").toString());
myArrayList.add(addValues);
Log.d("Before", myArrayList.toString());
}
} catch (Exception e) {
}
System.out
.println("############################################################################");
Log.d("After:", myArrayList.toString());
nodata = (TextView) findViewById(R.id.nodata);
nodata.setVisibility(View.GONE);
adapter = new PlaceAdapter(PlaceActivity.this, R.layout.list_row, myArrayList);
myList.setAdapter(adapter);
adapter.notifyDataSetChanged();
dialog.dismiss();
}
}
public String readJSON(String URL) {
StringBuilder sb = new StringBuilder();
HttpGet httpGet = new HttpGet(URL);
HttpClient client = new DefaultHttpClient();
try {
HttpResponse response = client.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
if (statusLine.getStatusCode() == 200) {
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
} else {
Log.e("JSON", "Couldn't find JSON file");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return sb.toString();
}
}
答案 1 :(得分:0)
试试这个:
从PlaceActivity中的onCreate事件替换以下行
if ([self.locationManager respondsToSelector:@selector(setAllowsBackgroundLocationUpdates:)]) {
[self.locationManager setAllowsBackgroundLocationUpdates:YES];
[self.locationManager pausesLocationUpdatesAutomatically:NO];
}
由此
[self.locationManager stopUpdatingLocation];
[self.locationManager startUpdatingLocation];
并删除&#34;实现AdapterView.OnItemSelectedListener&#34;来自PlaceActivity。
同样删除以下2方法,您将在onCreate事件
之外处理spinner = (Spinner) findViewById(R.id.spinnerplaces);
// Create an ArrayAdapter using the string array and a default spinner
ArrayAdapter<CharSequence> listAdapter = ArrayAdapter
.createFromResource(this, R.array.places,
android.R.layout.simple_spinner_item);
// Specify the layout to use when the list of choices appears
listAdapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
spinner.setAdapter(listAdapter);
和
spinner = (Spinner) findViewById(R.id.spinnerplaces);
// Create an ArrayAdapter using the string array and a default spinner
ArrayAdapter<String> listAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, getResources().getStringArray(R.array.places));
// Apply the adapter to the spinner
spinner.setAdapter(listAdapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
dialog = ProgressDialog.show(this, "", "Please wait", true);
// Google Places Access key and location values.
new readFromGooglePlaceAPI()
.execute("https://maps.googleapis.com/maps/api/place/nearbysearch/json?"
+ "location=53.795984,-1.759398&radius=900&sensor=true&"
+ "key=API_Key&types="
+ places[itemPosition]);
myList.OnItemSelectedListener (this);
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
Intent details = new Intent(PlaceActivity.this, Details.class);
details.putExtra("name", myArrayList.get(arg2).getName());
details.putExtra("rating", myArrayList.get(arg2).getRating());
details.putExtra("vicinity", myArrayList.get(arg2).getVicinity());
details.putExtra("lat", myArrayList.get(arg2).getLat());
details.putExtra("lon", myArrayList.get(arg2).getLon());
startActivity(details);
}
});