使用 hashmap 的多列列表中的 nullPointerException [英] nullPointerException in multi column list using hashmap

查看:12
本文介绍了使用 hashmap 的多列列表中的 nullPointerException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在 SO 上尝试过类似问题的参考资料,但没有找到合适的解决方案.

我正在尝试从网页中获取数据并以包含 4 列的行的格式显示它.

I'm trying to fetch the data from a webpage and display it in format consisting of rows having 4 columns.

网页上的数据:

SBIN ;1916.00;1886.85;1.54@LT ;1315.50;1310.30;0.40@TCS ;1180.00;1178.00;0.17@AXISBANK;1031.30.5PN901.53.590.53.59090.30.530.30.30.30.30.30.30.30.30.30.30.40916.35;1.70@GAIL;400.00;398.45;0.39@

我想以表格形式显示

    SBIN.........1916.00.....1886.85.....1.54

    LT...........1315.50.....1310.30.....0.40  and so on. 

请注意,我不想要点,我希望每个值都是一行中的一个单独的列.

Note that I don't want dots, I want each value to be a separate column within a row.

我的数据由 7 行组成.我使用了 http://www.technotalkative.com/android-multi- 中的代码列列表视图/

My Data consists of 7 rows. I have used the code from http://www.technotalkative.com/android-multi-column-listview/

当我运行下面的代码时,我得到 nullPointerException.

When I run the below code, I get nullPointerException.

请注意,当我尝试数组 arr[] 和 subarr[] 的值时,它们会显示正确的内容.

MultiCol.java

     package com.multicol;

        import static com.multicol.Constant.FIRST_COLUMN;
        import static com.multicol.Constant.FOURTH_COLUMN;
        import static com.multicol.Constant.SECOND_COLUMN;
        import static com.multicol.Constant.THIRD_COLUMN;

        import java.io.BufferedReader;
        import java.io.InputStream;
        import java.io.InputStreamReader;
        import java.util.ArrayList;
        import java.util.HashMap;

        import org.apache.http.HttpResponse;
        import org.apache.http.client.methods.HttpGet;
        import org.apache.http.impl.client.DefaultHttpClient;

        import android.app.Activity;
        import android.os.AsyncTask;
        import android.os.Bundle;
        import android.util.Log;
        import android.widget.ListView;

        public class MultiCol extends Activity {
            String subarr[] = new String[28];// 7 rows with 4 columns each
            private ArrayList<HashMap<String, String>> list;

            public void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.main);

                ListView lview = (ListView) findViewById(R.id.listview);
                DownloadWebPageTask task = new DownloadWebPageTask();
                task.execute(new String[] { "http://ipad.idealake.com/default.aspx?id=G" });
            }

            private class DownloadWebPageTask extends AsyncTask<String, Void, String> {
                @Override
                protected String doInBackground(String... urls) {
                    String response = "";
                    for (String url : urls) {
                        DefaultHttpClient client = new DefaultHttpClient();
                        HttpGet httpGet = new HttpGet(url);
                        try {
                            HttpResponse execute = client.execute(httpGet);
                            InputStream content = execute.getEntity().getContent();

                            BufferedReader buffer = new BufferedReader(
                                    new InputStreamReader(content));
                            String s = "";
                            while ((s = buffer.readLine()) != null) {
                                response += s;
                            }

                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                    return response;
                }

                @Override
                protected void onPostExecute(String result) {
                    int sub = result.lastIndexOf('@', result.length() - 1);
                    String s1 = result.substring(0, sub + 2);
                    String temp[];
                    String arr1[] = s1.split("@");
                    String arr[] = new String[7];
                                //To remove 8th element which is null
                    for (int j = 0; j < arr.length; j++) {
                        arr[j] = arr1[j];
                    }

                    for (int i = 0; i < arr.length; i++) {
                        temp = arr[i].split(";");
                        subarr[(4 * i)] = temp[0];
                        subarr[(4 * i) + 1] = temp[1];
                        subarr[(4 * i) + 2] = temp[2];
                        subarr[(4 * i) + 3] = temp[3];
                    }

                    list = new ArrayList<HashMap<String, String>>();

                    for (int i = 0; i < ((subarr.length) / 4); i++) {

                        HashMap<String, String> addList = new HashMap<String, String>();
                         addList.put(FIRST_COLUMN, subarr[(4 * i)]);
                         addList.put(SECOND_COLUMN, subarr[((4 * i) + 1)]);
                         addList.put(THIRD_COLUMN, subarr[((4 * i) + 2)]);
                         addList.put(FOURTH_COLUMN, subarr[((4 * i) + 3)]);

                        list.add(addList);
                    }

  //I was writing these two statements before populating list. So they were giving me  nullPointerException.
     listviewAdapter adapter = new listviewAdapter(this, list);
                lview.setAdapter(adapter);
                }
            }
        }

ma​​in.xml

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

            <ListView
                android:id="@+id/listview"
                android:layout_height="wrap_content"
                android:layout_width="match_parent">
            </ListView>
        </LinearLayout>

listviewAdapter.java

          package com.multicol;

        import static com.multicol.Constant.FIRST_COLUMN;
        import static com.multicol.Constant.FOURTH_COLUMN;
        import static com.multicol.Constant.SECOND_COLUMN;
        import static com.multicol.Constant.THIRD_COLUMN;

        import java.util.ArrayList;
        import java.util.HashMap;

        import android.app.Activity;
        import android.view.LayoutInflater;
        import android.view.View;
        import android.view.ViewGroup;
        import android.widget.BaseAdapter;
        import android.widget.TextView;

        public class listviewAdapter extends BaseAdapter {
            public ArrayList<HashMap<String, String>> list;
            Activity activity;

            public listviewAdapter(Activity activity,
                    ArrayList<HashMap<String, String>> list) {
                super();
                this.activity = activity;
                this.list = list;
            }

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

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

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

            private class ViewHolder {
                TextView txtFirst;
                TextView txtSecond;
                TextView txtThird;
                TextView txtFourth;
            }

            @Override
            public View getView(int position, View convertView, ViewGroup parent) {
                ViewHolder holder;
                LayoutInflater inflater = activity.getLayoutInflater();

                if (convertView == null) {
                    convertView = inflater.inflate(R.layout.listview_row, null);
                    holder = new ViewHolder();
                    holder.txtFirst = (TextView) convertView
                            .findViewById(R.id.FirstText);
                    holder.txtSecond = (TextView) convertView
                            .findViewById(R.id.SecondText);
                    holder.txtThird = (TextView) convertView
                            .findViewById(R.id.ThirdText);
                    holder.txtFourth = (TextView) convertView
                            .findViewById(R.id.FourthText);
                    convertView.setTag(holder);
                } else {
                    holder = (ViewHolder) convertView.getTag();
                }

                HashMap<String, String> map = list.get(position);
                holder.txtFirst.setText(map.get(FIRST_COLUMN));
                holder.txtSecond.setText(map.get(SECOND_COLUMN));
                holder.txtThird.setText(map.get(THIRD_COLUMN));
                holder.txtFourth.setText(map.get(FOURTH_COLUMN));

                return convertView;
            }
        }

Constant.java

       package com.multicol;

        public class Constant {
            public static final String FIRST_COLUMN = "First";
            public static final String SECOND_COLUMN = "Second";
            public static final String THIRD_COLUMN = "Third";
            public static final String FOURTH_COLUMN = "Fourth";
        }

listview_row.xml

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

            <TextView
                android:id="@+id/FirstText"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:text="First"
                android:layout_weight="1">
            </TextView>

            <TextView
                android:id="@+id/SecondText"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:text="Second"
                android:layout_weight="2">
            </TextView>

            <TextView
                android:id="@+id/ThirdText"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:text="Third"
                android:layout_weight="1">
            </TextView>

            <TextView
                android:id="@+id/FourthText"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:text="Fourth"
                android:layout_weight="1">
            </TextView>
        </LinearLayout>

LOGCAT

12-07 11:40:19.767: E/AndroidRuntime(2283): FATAL EXCEPTION: main
12-07 11:40:19.767: E/AndroidRuntime(2283): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.multicol/com.multicol.MultiCol}: java.lang.NullPointerException
12-07 11:40:19.767: E/AndroidRuntime(2283):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1955)
12-07 11:40:19.767: E/AndroidRuntime(2283):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1980)
12-07 11:40:19.767: E/AndroidRuntime(2283):     at android.app.ActivityThread.access$600(ActivityThread.java:122)
12-07 11:40:19.767: E/AndroidRuntime(2283):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1146)
12-07 11:40:19.767: E/AndroidRuntime(2283):     at android.os.Handler.dispatchMessage(Handler.java:99)
12-07 11:40:19.767: E/AndroidRuntime(2283):     at android.os.Looper.loop(Looper.java:137)
12-07 11:40:19.767: E/AndroidRuntime(2283):     at android.app.ActivityThread.main(ActivityThread.java:4340)
12-07 11:40:19.767: E/AndroidRuntime(2283):     at java.lang.reflect.Method.invokeNative(Native Method)
12-07 11:40:19.767: E/AndroidRuntime(2283):     at java.lang.reflect.Method.invoke(Method.java:511)
12-07 11:40:19.767: E/AndroidRuntime(2283):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
12-07 11:40:19.767: E/AndroidRuntime(2283):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
12-07 11:40:19.767: E/AndroidRuntime(2283):     at dalvik.system.NativeStart.main(Native Method)
12-07 11:40:19.767: E/AndroidRuntime(2283): Caused by: java.lang.NullPointerException
12-07 11:40:19.767: E/AndroidRuntime(2283):     at com.multicol.listviewAdapter.getCount(listviewAdapter.java:31)
12-07 11:40:19.767: E/AndroidRuntime(2283):     at android.widget.ListView.setAdapter(ListView.java:460)
12-07 11:40:19.767: E/AndroidRuntime(2283):     at com.multicol.MultiCol.onCreate(MultiCol.java:38)
12-07 11:40:19.767: E/AndroidRuntime(2283):     at android.app.Activity.performCreate(Activity.java:4465)
12-07 11:40:19.767: E/AndroidRuntime(2283):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
12-07 11:40:19.767: E/AndroidRuntime(2283):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1919)
12-07 11:40:19.767: E/AndroidRuntime(2283):     ... 11 more

任何帮助

推荐答案

您正在 MultiCol 的 onCreate 中创建 listViewAdapter 并传入对 的引用列表.但是,此时 list 还没有被实例化,因为在您的 AsyncTask 完成之前不会发生这种情况.换句话说:你传入了 null,因此 LogCat 中的 nullpointer 异常.

You are creating the listViewAdapter in the onCreate of MultiCol and passing in a reference to list. However, at that point list has not been instantiated yet, since that does not happen until your AsyncTask finishes. In other words: you're passing in null, hence the nullpointer exception in LogCat.

要更正此问题,您可能需要将以下两行代码移至 DownloadWebPageTask 的 onPostExecute() 末尾:

To correct this, you'll probably want to move the following two lines of code to the end of the onPostExecute() of your DownloadWebPageTask:

listviewAdapter adapter = new listviewAdapter(this, list);
lview.setAdapter(adapter);

这样你就会为适配器提供一个实例化的(非空)列表对象.

That way you will supply the adapter with an instantiated (non-null) list object.

这篇关于使用 hashmap 的多列列表中的 nullPointerException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆