【问题标题】:adding button to listview in android在android中将按钮添加到listview
【发布时间】:2014-06-17 12:31:26
【问题描述】:

嗨,在我的应用程序中,我正在解析 json url 以显示它工作正常的图像和文本。
之后,我添加了一个名为 Add to Listview 的按钮,它在所有地方都正确显示。但是在我点击添加按钮之后,我想移动到另一个活动。单击添加按钮后,它显示不幸的错误。

谁能告诉我我在代码中做错了什么?

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 title;

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

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

        // Locate the TextViews in listview_item.xml
        title = (TextView) itemView.findViewById(R.id.rank);

        // Locate the ImageView in listview_item.xml
        thumb_url = (ImageView) itemView.findViewById(R.id.flag);

        // Capture position and set results to the TextViews
        title.setText(resultp.get(MainActivity.TITLE));

        // Capture position and set results to the ImageView
        // Passes flag images URL into ImageLoader.class
        imageLoader.DisplayImage(resultp.get(MainActivity.THUMB_URL), thumb_url);
        // Capture ListView item click
        Button Add = (Button) itemView.findViewById(R.id.add);

        Add.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("title", resultp.get(MainActivity.TITLE));
                // 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("thumb_url", resultp.get(MainActivity.THUMB_URL));
                // Start SingleItemView Class
                context.startActivity(intent);
            }


            public void onClick(DialogInterface dialog, int which) {
                // TODO Auto-generated method stub
            }
        });
        return itemView;
    }

    public void onClick(DialogInterface dialog, int which) {
        // TODO Auto-generated method stub
    }
}

SingleItemView 类

public class SingleItemView extends Activity {
    // Declare Variables
    String title;
    /*String country;
    String population;
    */
    String thumb_url;

    ImageLoader imageLoader = new ImageLoader(this);

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // Get the view from singleitemview.xml
        setContentView(R.layout.singleitemview);

        Intent i = getIntent();
        // Get the result of rank
        title = i.getStringExtra("title");
        // Get the result of country
                /*country = i.getStringExtra("country");
                // Get the result of population
                population = i.getStringExtra("population");*/
        // Get the result of flag
        thumb_url = i.getStringExtra("thumb_url");

        // Locate the TextViews in singleitemview.xml
        TextView txtrank = (TextView) findViewById(R.id.rank);
                /*TextView txtcountry = (TextView) findViewById(R.id.country);
                TextView txtpopulation = (TextView) findViewById(R.id.population);
    */
        // Locate the ImageView in singleitemview.xml
        ImageView imgflag = (ImageView) findViewById(R.id.flag);

        // Set results to the TextViews
        txtrank.setText(title);
                /*txtcountry.setText(country);
                txtpopulation.setText(population);
    */
        // Capture position and set results to the ImageView
        // Passes flag images URL into ImageLoader.class
        imageLoader.DisplayImage(thumb_url, imgflag);
    }
}

MainActivity 类

public class MainActivity extends Activity {
    // Declare Variables
    JSONObject jsonobject;
    JSONArray jsonarray;
    ListView listview;
    ListViewAdapter adapter;
    ProgressDialog mProgressDialog;
    ArrayList<HashMap<String, String>> arraylist;
    static String TITLE = "title";
    /*static String COUNTRY = "country";
    static String POPULATION = "population";*/
    static String THUMB_URL = "thumb_url";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // Get the view from listview_main.xml
        setContentView(R.layout.listview_main);
        // Execute DownloadJSON AsyncTask
        new DownloadJSON().execute();
    }

    // DownloadJSON AsyncTask
    private class DownloadJSON extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            // Create a progressdialog
            mProgressDialog = new ProgressDialog(MainActivity.this);
            // Set progressdialog title
            mProgressDialog.setTitle("Loading...");
            // Set progressdialog message
            mProgressDialog.setMessage("Loading...");
            mProgressDialog.setIndeterminate(false);
            // Show progressdialog
            mProgressDialog.show();
        }

        @Override
        protected Void doInBackground(Void... params) {
            // Create an array
            arraylist = new ArrayList<HashMap<String, String>>();
            // Retrieve JSON Objects from the given URL address
            jsonobject = JSONfunction
                    .getJSONfromURL("http://indianpoliticalleadersmap.com/android/DemoSchool/json/json_item.php");

            try {
                // Locate the array name in JSON
                jsonarray = jsonobject.getJSONArray("veg_food");

                for (int i = 0; i < jsonarray.length(); i++) {
                    HashMap<String, String> map = new HashMap<String, String>();
                    jsonobject = jsonarray.getJSONObject(i);
                    // Retrive JSON Objects
                    map.put("title", jsonobject.getString("title"));
                            /*map.put("country", jsonobject.getString("country"));
                            map.put("population", jsonobject.getString("population"));*/
                    map.put("thumb_url", jsonobject.getString("thumb_url"));
                    // 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.listview);
            // Pass the results into ListViewAdapter.java
            adapter = new ListViewAdapter(MainActivity.this, arraylist);
            // Set the adapter to the ListView
            listview.setAdapter(adapter);
            // Close the progressdialog
            mProgressDialog.dismiss();
        }
    }
}

singleitemview.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

     <ImageView
        android:id="@+id/flag"
        android:layout_width="80dp"
        android:layout_height="80dp"
        android:layout_centerVertical="true"
        android:layout_margin="5dp"
        android:background="#444"
        android:padding="3dp" />
     <TextView
        android:id="@+id/rank"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="5dip"

        android:layout_toRightOf="@+id/flag"
        android:maxLines="1"
        android:textSize="15dip"
        android:textStyle="bold" />


    <!--  <TextView
        android:id="@+id/ranklabel"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
         />

    <TextView
        android:id="@+id/rank"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        />
 -->

  <!--   <ImageView
        android:id="@+id/flag"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:background="#000000"
        android:layout_toRightOf="@+id/flag"
        android:padding="1dp" />
 -->

     <Button
         android:id="@+id/add"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:layout_alignParentRight="true"
         android:layout_below="@+id/rank"
         android:text="Add" />

</RelativeLayout>

listview_item.xml

    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" >

        <ImageView
            android:id="@+id/flag"
            android:layout_width="80dp"
            android:layout_height="80dp"
            android:layout_centerVertical="true"
            android:layout_margin="5dp"
            android:background="#444"
            android:padding="3dp" />
         <TextView
            android:id="@+id/rank"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="5dip"

            android:layout_toRightOf="@+id/flag"
            android:maxLines="1"
            android:textSize="15dip"
            android:textStyle="bold" />


        <!--  <TextView
            android:id="@+id/ranklabel"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
             />

        <TextView
            android:id="@+id/rank"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            />
     -->

      <!--   <ImageView
            android:id="@+id/flag"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:background="#000000"
            android:layout_toRightOf="@+id/flag"
            android:padding="1dp" />
     -->

         <Button
             android:id="@+id/add"
             android:layout_width="wrap_content"
             android:layout_height="wrap_content"
             android:layout_alignParentRight="true"
             android:layout_below="@+id/add"
             android:text="Add" />

    </RelativeLayout>

logcat

06-17 18:22:10.146: E/AndroidRuntime(498): FATAL EXCEPTION: main
06-17 18:22:10.146: E/AndroidRuntime(498): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.androidhive/com.example.androidhive.SingleItemView}: java.lang.NullPointerException
06-17 18:22:10.146: E/AndroidRuntime(498):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2585)
06-17 18:22:10.146: E/AndroidRuntime(498):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
06-17 18:22:10.146: E/AndroidRuntime(498):  at android.app.ActivityThread.access$2300(ActivityThread.java:125)
06-17 18:22:10.146: E/AndroidRuntime(498):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
06-17 18:22:10.146: E/AndroidRuntime(498):  at android.os.Handler.dispatchMessage(Handler.java:99)
06-17 18:22:10.146: E/AndroidRuntime(498):  at android.os.Looper.loop(Looper.java:123)
06-17 18:22:10.146: E/AndroidRuntime(498):  at android.app.ActivityThread.main(ActivityThread.java:4627)
06-17 18:22:10.146: E/AndroidRuntime(498):  at java.lang.reflect.Method.invokeNative(Native Method)
06-17 18:22:10.146: E/AndroidRuntime(498):  at java.lang.reflect.Method.invoke(Method.java:521)
06-17 18:22:10.146: E/AndroidRuntime(498):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
06-17 18:22:10.146: E/AndroidRuntime(498):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
06-17 18:22:10.146: E/AndroidRuntime(498):  at dalvik.system.NativeStart.main(Native Method)
06-17 18:22:10.146: E/AndroidRuntime(498): Caused by: java.lang.NullPointerException
06-17 18:22:10.146: E/AndroidRuntime(498):  at android.content.ContextWrapper.getCacheDir(ContextWrapper.java:188)
06-17 18:22:10.146: E/AndroidRuntime(498):  at com.example.androidhive.FileCache.<init>(FileCache.java:15)
06-17 18:22:10.146: E/AndroidRuntime(498):  at com.example.androidhive.ImageLoader.<init>(ImageLoader.java:32)
06-17 18:22:10.146: E/AndroidRuntime(498):  at com.example.androidhive.SingleItemView.<init>(SingleItemView.java:19)
06-17 18:22:10.146: E/AndroidRuntime(498):  at java.lang.Class.newInstanceImpl(Native Method)
06-17 18:22:10.146: E/AndroidRuntime(498):  at java.lang.Class.newInstance(Class.java:1429)
06-17 18:22:10.146: E/AndroidRuntime(498):  at android.app.Instrumentation.newActivity(Instrumentation.java:1021)
06-17 18:22:10.146: E/AndroidRuntime(498):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2577)
06-17 18:22:10.146: E/AndroidRuntime(498):  ... 11 more

在我上面的代码中,如果我单击添加按钮不起作用,任何人都可以解决它并帮助我。 提前致谢。

【问题讨论】:

  • 你给 Intent 放了什么类型的参数?
  • 嗨,我发布了我的 logcat,你能帮帮我吗

标签: android xml listview custom-adapter


【解决方案1】:
06-17 18:22:10.146: E/AndroidRuntime(498): Caused by: java.lang.NullPointerException
06-17 18:22:10.146: E/AndroidRuntime(498):  at android.content.ContextWrapper.getCacheDir(ContextWrapper.java:188)
06-17 18:22:10.146: E/AndroidRuntime(498):  at com.example.androidhive.FileCache.<init>(FileCache.java:15)
06-17 18:22:10.146: E/AndroidRuntime(498):  at com.example.androidhive.ImageLoader.<init>(ImageLoader.java:32)
06-17 18:22:10.146: E/AndroidRuntime(498):  at com.example.androidhive.SingleItemView.<init>(SingleItemView.java:19)

在初始化ImageLoader 成员变量时,您正尝试将您的活动用作onCreate() 之前的上下文。

在活动生命周期中将初始化移动到onCreate() 或更高版本。

【讨论】:

  • 我要搬哪一个
  • new ImageLoader(this)
【解决方案2】:

嘿,问题出在这条线上

itemView.setOnClickListener(new OnClickListener() {

其实是整体视图,你不应该在这个上设置OnClickListener,而是在viewholder类中放一个按钮,为那个按钮写上onClickListener,这样就可以正常工作了。

公共类 CustomAdapter 扩展 BaseAdapter {

        Context context;


        public CustomAdapter(Context context) {
            this.context = context;

            // this.rowItems = rowItems;
        }

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

        @Override
        public Object getItem(int position) {
            // return _data.get(position);
            return null;
        }

        @Override
        public long getItemId(int position) {
            // return _data.indexOf(getItem(position));
            return position;
        }

        /* private view holder class */
        private class ViewHolder {

            Button rl;
        }

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

            ViewHolder holder = null;

            LayoutInflater mInflater = (LayoutInflater) context
                    .getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
            if (convertView == null) {
                convertView = mInflater.inflate(R.layout.image_holder, null);
                holder = new ViewHolder();
                holder.rl = (Button) convertView.findViewById(R.id.rl);



                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
                convertView.setTag(holder);
            }
        try {
    holder.rl.setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        try {                           a   

                            //call ur intent here

                        } catch (Exception e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                    }
                    }
                });
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            return convertView;
        }   
    }

一个示例项目你可以在这里查看项目custom_list 如果您正在寻找在列表视图示例中加载很酷的图像,您可以参考这里Universal image loader

【讨论】:

  • 能否请您发布此布局 image_holder
  • 你好,请告诉我
  • 嗨,你能帮帮我吗
  • 如果我按下添加按钮什么都没有发生
  • @user3739863: 抱歉我没空,为了您的方便,我上传了一个示例项目,您可以在这里查看项目android-start.yolasite.com/posts.php
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-02
  • 1970-01-01
  • 2015-06-26
  • 1970-01-01
  • 2015-06-26
  • 2011-04-21
相关资源
最近更新 更多