简体   繁体   English

通过旋转器使用setOnItemSelectedListener和onNothingSelected

[英]using the setOnItemSelectedListener and onNothingSelected with spinner

I was just wondering if anyone can help me resolve the problem which i am currently facing as I am trying to implement setOnItemSelectedListener and onNothingSelected events with spinner. 我只是想知道是否有人可以通过旋转器实现setOnItemSelectedListener和onNothingSelected事件,从而解决当前面临的问题。

Once the user selects option from spinner it will show them google places names, then when the user clicks on a place ,it will show another page which is called details.java and this contains details of the place as well as mapview. 一旦用户从微调器中选择了选项,它将向他们显示google地名,然后当用户单击某个地时,将显示另一个页面,称为details.java,其中包含该地的详细信息以及mapview。

I think I am using both of the particular options incorrectly, therefore please can someone help and advise me?. 我认为我在使用这两个特定选项时均不正确,因此请有人可以帮助我吗?

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);
        ArrayAdapter<CharSequence> list = ArrayAdapter.createFromResource(PlaceActivity.this, R.array.places,android.R.layout.simple_spinner_item);
        list.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

        spinner.setOnItemSelectedListener(this);
    }


    private boolean isNetworkAvailable() {
        ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
        return activeNetworkInfo != null;
    }

    @Override
    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=AIzaSyA7CzOa10AOfBAU9FvaIrVlVyCKzXxiCc0&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<?> parent) {
        // no-op
    }

where do I put the below code. 我将以下代码放在哪里。

 @Override public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
        Intent details = new Intent(MainActivity.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);
    }

You're in the right direction. 您的方向正确。 Right now you have the necessary methods, but you have make your class implement the OnItemSelectedListener and set it as the listener for your spinner as such: 现在,您具有必需的方法,但已使您的类实现OnItemSelectedListener并将其设置为旋转器的侦听器,如下所示:

public class PlaceActivity extends AppCompatActivity implements OnItemSelectedListener { ... } 公共类PlaceActivity扩展AppCompatActivity 实现OnItemSelectedListener {...}

And then to set the class as the listener you can add this line after: spinner = (Spinner) findViewById(R.id.spinnerplaces); 然后将类设置为侦听器,您可以在此之后添加以下行:spinner =(Spinner)findViewById(R.id.spinnerplaces);

spinner.setOnItemSelectedListener(this); spinner.setOnItemSelectedListener(本);

I suggest something like this: 我建议是这样的:

spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

    @Override
    public void onItemSelected(AdapterView<?> parent, View view, 
                               int pos, long id) {
//If you're wondering, int pos is the position of the item selected (starting with 0)
// what you want onClick
}

Your code: 您的代码:

 @Override public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
        Intent details = new Intent(MainActivity.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);
    }

can go below the initialization of the spinner. 可以低于微调器的初始化。

Hope it helps! 希望能帮助到你! Good Luck! 祝好运!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM