如何在android中匹配onitemclick值与字符串?

时间:2017-01-08 12:16:27

标签: android listview

这里我显示1个listview来自server.if我点击任何项目我想要一些程序发生...如果我在itemclick上放任何条件它显示我空指针异常... 这是我的代码:

public class SubMenu extends AppCompatActivity {

    JSONObject jsonobject;
    JSONArray jsonarray;
    ListView listview;
    ListViewAdapter adapter;
    ProgressDialog mProgressDialog;
    ArrayList<HashMap<String, String>> arraylist;
    static String RANK = "id";
    static String COUNTRY = "name";
    private ProgressDialog pDialog;
    String status="";
    static String FLAG = "image";
    Integer i = 1;
    String _stringVal;

   /* final int Pizza = 0; //should be equal to the index in your array.
    final int Pasta = 1;
    final int Lasagna = 2;
    final int Salad =3 ;
    final int Breakfast = 4;
    final int Beverages= 5;
    final int Soup = 6;

    final int SpecialOffer =7;*/



    private static String url_create_book = "http://cloud....com/broccoli/creatinfo.php";
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);


        setContentView(R.layout.activity_sub_menu);

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        String SelectedId = getIntent().getStringExtra("id");


        getSupportActionBar().setDisplayHomeAsUpEnabled(true);


        // Get the view from listview_main.xml

        // Execute DownloadJSON AsyncTask
        new DownloadJSON().execute();
    }

    // DownloadJSON AsyncTask
    private class DownloadJSON extends AsyncTask<Void, Void, Void> implements AdapterView.OnItemClickListener, AdapterView.OnItemSelectedListener {
 protected Void doInBackground(Void... params) {
            // Create an array
            arraylist = new ArrayList<HashMap<String, String>>();
            // Retrieve JSON Objects from the given URL address
            jsonarray = JsonFunctions
                    .getJSONfromURL("http://cloud.granddubai.com/broccoli/menu_typeitem.php?id=" + getIntent().getStringExtra("id"));
            try {
                for (int i = 0; i < jsonarray.length(); i++) {
                    HashMap<String, String> map = new HashMap<String, String>();
                    jsonobject = jsonarray.getJSONObject(i);
                    map.put("name", jsonobject.getString("name"));
                    map.put("image", jsonobject.getString("image"));
                    // Set the JSON Objects into the array
                    arraylist.add(map);
                }
            } catch (JSONException e) {
                Log.e("Error", e.getMessage());
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void args) {
            // Locate the listview in listview_main.xml
            listview = (ListView) findViewById(R.id.list1);
            // Pass the results into ListViewAdapter.java
            adapter = new ListViewAdapter(SubMenu.this, arraylist);
            // Set the adapter to the ListView
            listview.setAdapter(adapter);
            listview.setOnItemClickListener(this);
            // Close the progressdialog
            // mProgressDialog.dismiss();
        }


        @Override
        public void onItemClick(AdapterView<?> parent, View view,
                                int position, long rowId) {

            //Log.d("ANDROID", parent.getItemAtPosition(position).toString());
            if ( parent.getItemAtPosition(position).toString().equals("Bian‌​‌​ca Pizza"))
            { 
            .....
            }

            else{

                Toast.makeText(SubMenu.this, "hello", Toast.LENGTH_SHORT).show();



            }  @Override
        public void onItemSelected(AdapterView<?> parent,
                                   View view, int pos, long id) {
            //  Toast.makeText(SubMenu.this,"The planet is " + parent.getItemAtPosition(pos).toString(), Toast.LENGTH_LONG).show();
        }

        public void onNothingSelected(AdapterView parent) {
            // Do nothing.
        }
    }

if(parent.getItemAtPosition(position).toString()。equals(&#34; Bian ca Pizza&#34;))...我在这里得到错误..如果我把条件取为空价值......其他工作正常......不知道它没有为条件带来价值。

异常:

FATAL EXCEPTION: main
                  Process: com.example.zeba.broccoli, PID: 32107
                  java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.Object.toString()' on a null object reference
                      at com.example.zeba.broccoli.SubMenu$DownloadJSON.onItemClick(SubMenu.java:161)
                      at android.widget.AdapterView.performItemClick(AdapterView.java:339)
                      at android.widget.AbsListView.performItemClick(AbsListView.java:1532)
                      at android.widget.AbsListView$PerformClick.run(AbsListView.java:3700)
                      at android.widget.AbsListView$3.run(AbsListView.java:5684)
                      at android.os.Handler.handleCallback(Handler.java:739)
                      at android.os.Handler.dispatchMessage(Handler.java:95)
                      at android.os.Looper.loop(Looper.java:145)
                      at android.app.ActivityThread.main(ActivityThread.java:6946)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at java.lang.reflect.Method.invoke(Method.java:372)
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1404)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1199)

这是我的listviewAdapter:

public class ListViewAdapter extends BaseAdapter {

    // Declare Variables
    Context context;
    LayoutInflater inflater;
    ArrayList<HashMap<String, String>> data;
    ImageLoader imageLoader;
    HashMap<String, String> resultp = new HashMap<String, String>();

    public ListViewAdapter(Context context,
                           ArrayList<HashMap<String, String>> arraylist) {
        this.context = context;
        data = arraylist;
        imageLoader = new ImageLoader(context);
    }

    @Override
    public int getCount() {
        return data.size();
    }

    @Override
    public Object getItem(int position) {
        return null;
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

    public View getView(final int position, View convertView, ViewGroup parent) {
        // Declare Variables
        TextView id;
        TextView name;
        TextView population;
        CircleImageView image;

        inflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        View itemView = inflater.inflate(R.layout.list_item1, parent, false);
        // Get the position
        resultp = data.get(position);

        // Locate the TextViews in listview_item.xml
       // id = (TextView) itemView.findViewById(R.id.idq);
        name = (TextView) itemView.findViewById(R.id.type1);


        // Locate the ImageView in listview_item.xml
        image = (CircleImageView) itemView.findViewById(R.id.subimg);
      //  icon = (ImageView) itemView.findViewById(R.id.arrow);
        // Capture position and set results to the TextViews
      //  id.setText(resultp.get(SubMenu.RANK));
        name.setText(resultp.get(SubMenu.COUNTRY));

        // Capture position and set results to the ImageView
        // Passes flag images URL into ImageLoader.class
        imageLoader.DisplayImage(resultp.get(SubMenu.FLAG), image);
      //  imageLoader.DisplayImage(resultp.get(SubMenu.FLAG), icon);
        // Capture ListView item click
        /**itemView.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {
        // Get the position
        resultp = data.get(position);
        Intent intent = new Intent(context, SingleItemView.class);
        // Pass all data rank
        intent.putExtra("rank", resultp.get(MainActivity.RANK));
        // Pass all data country
        intent.putExtra("country", resultp.get(MainActivity.COUNTRY));
        // Pass all data population
        intent.putExtra("population",resultp.get(MainActivity.POPULATION));
        // Pass all data flag
        intent.putExtra("flag", resultp.get(MainActivity.FLAG));
        // Start SingleItemView Class
        context.startActivity(intent);

        }
        });*/
        return itemView;
    }
}

1 个答案:

答案 0 :(得分:2)

您可以使用TextView提取Adapter Class,就像您在parentView中提取的那样匹配字符串值:

   TextView name = (TextView) parent.findViewById(R.id.type1);
   if ( name.getText.toString().equals("Bian‌​‌​ca Pizza"))
   {
          .....
   }