带有动态按钮的Android listview onclicklistener

时间:2017-10-11 00:43:47

标签: android listview

我构建了一个listview,它显示了数据库中表名的动态按钮。当一个人点击按钮时,它应该抓住按钮的文本,然后将其传递给下一个活动,该活动将填充对应于数据库表的信息并在屏幕顶​​部显示该文本。当我点击按钮时,我写的代码不断崩溃。我需要调用其他东西,或者这个代码不能用于按钮吗?

public class UserArea extends AppCompatActivity {

SectionListAdapter sectionListAdapter;
ListView listView;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_area);

TextView tvWelcomeMsg = (TextView) findViewById(R.id.tvWelcome);

/**Get Sections and Display as buttons*/
listView = (ListView) findViewById(R.id.lvSections);
sectionListAdapter = new SectionListAdapter(this, R.layout.section_layout);
listView.setAdapter(sectionListAdapter);

Response.Listener<String> responseListener = new Response.Listener<String>() {
    @Override
    public void onResponse(String response) {
        try {

            JSONObject jsonResponse = new JSONObject(response);
            boolean success = jsonResponse.getBoolean("success");
            /** If data successfully gathered*/
            if (success) {

                JSONArray jsonArray= jsonResponse.getJSONArray("Flights");

                int count = 0;

                String flight;

                while(count<jsonArray.length()) {

                    JSONObject SL = jsonArray.getJSONObject(count);
                    flight = SL.getString("Flight");

                    SectionList sl = new SectionList(flight);
                    sectionListAdapter.add(sl);

                    count++;

                }

            }
            /** If data is not gathered*/
            else {
                AlertDialog.Builder builder = new AlertDialog.Builder(UserArea.this);
                builder.setMessage("Failed to connect")
                        .setNegativeButton("Retry", null)
                        .create()
                        .show();
            }
        }
        /** if any other response is received*/
        catch (JSONException e) {
            e.printStackTrace();
        }
    }
};

/**Creates Request to get the data*/
GetSectionRequest getSections = new GetSectionRequest(responseListener);
/**Creates a queue to run the code*/
RequestQueue queue = Volley.newRequestQueue(UserArea.this);
queue.add(getSections);

/**End*/

/**Creates onclicklistener to pass clicked section name*/

listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int i, long id) {

      Intent intent = new Intent (UserArea.this, Personnel.class);
      intent.putExtra("section", listView.getItemAtPosition(i).toString());
      UserArea.this.startActivity(intent);
    }
});

SectionListAdapter

public class SectionListAdapter extends ArrayAdapter  {

    List list = new ArrayList();

    public SectionListAdapter(Context context, int resource) {
        super(context, resource);
    }


    public void add(SectionList object) {
        super.add(object);
        list.add(object);
    }

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

    @Override
    public Object getItem(int position) {
        return list.get(position);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        View row;
        row = convertView;

        SectionListAdapter.SectionListHolder sectionListHolder;

        if (row == null){
            LayoutInflater layoutInflater = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            row = layoutInflater.inflate(R.layout.section_layout, parent, false);
            sectionListHolder = new SectionListAdapter.SectionListHolder();
            sectionListHolder.bSection = row.findViewById(R.id.bSectionName);

        }else{

            sectionListHolder = (SectionListAdapter.SectionListHolder)row.getTag();

        }
        SectionList SectionList = (SectionList) this.getItem(position);
        sectionListHolder.bSection.setText(SectionList.getFlight());



        return row;
    }

    static class SectionListHolder{

        Button bSection;
    }
}

Log Cat

10-10 19:31:26.797 6595-6595/com.example.yikes.recall E/AndroidRuntime:
FATAL EXCEPTION: main
Process: com.example.yikes.recall, PID: 6595
java.lang.NullPointerException: Attempt to read from field 'android.widget.Button com.example.yikes.recall.SectionListAdapter$SectionListHolder.bSection' on a null object reference

1 个答案:

答案 0 :(得分:0)

我试试代码:

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        final ListView listView = new ListView(this);
        listView.setBackgroundColor(Color.WHITE);
        setContentView(listView);

        final String[] activities = new String[]{"Item1", "Item2", "Item3", "Item4"};
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line);
        listView.setAdapter(adapter);

        for (String item : activities) {
            adapter.add(item);
        }


        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String item = listView.getItemAtPosition(position).toString();
                Intent intent = new Intent(MainActivity.this, SampleActivity.class);
                intent.putExtra("item", item);
                MainActivity.this.startActivity(intent);
            }
        });
    }

它正在工作,我想

/**Creates Request to get the data*/
GetSectionRequest getSections = new GetSectionRequest(responseListener);
/**Creates a queue to run the code*/
RequestQueue queue = Volley.newRequestQueue(UserArea.this);
queue.add(getSections);

需要一些时间,您可以在启动应用时添加ProgressDialog,并在响应回调时关闭。希望它可以帮到你!