将JSON数据解析为listview android

时间:2015-07-13 06:31:42

标签: android json listview android-arrayadapter

我的 JSONDATA

[{"Name":"47ABC","Location":"Chennai","Image":"47ABC_175.png","Funding":"150","Founded":"2013 ","Status":1,"RowVAl":1},{"Name":"57ABC","Location":"Mumbai","Image":"57ABC_175.png","Funding":"1250","Founded":"2010 ","Status":2,"RowVAl":1}]

我的 onBackground

 protected String doInBackground(String... params) {


  return Utils.getJSONStringHTTPResponse(connString + "/GetSearch", "1");

            }

getJSONStringHTTPResponse上课

public static String getJSONStringHTTPResponse(String url,String EmpId) {
        String jsonString = null;
        String httpRequest=url;
        System.out.println("Coonstring : " + httpRequest);

        HttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(httpRequest);
        List<NameValuePair> list = new ArrayList<NameValuePair>();
        list.add(new BasicNameValuePair("PageNumber", EmpId));


        try {

            httpPost.setEntity(new UrlEncodedFormEntity(list));
            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            jsonString = EntityUtils.toString(httpResponse.getEntity());
            jsonString = android.text.Html.fromHtml(jsonString).toString();
            System.out.println("Response: " + jsonString);

        } catch (Exception e) {
            return "Exception" + e.getMessage();
        }

        return jsonString;
    }   

我的RowsAdapter class

    public class RowAdapter extends ArrayAdapter<Item> {

        private Activity activity;
        private List<Item> items;
        private Item objBean;
        private int row;

        public RowAdapter(Activity act, int resource, List<Item> arrayList) {
            super(act, resource, arrayList);
            this.activity = act;
            this.row = resource;
            this.items = arrayList;
        }

我的onPostExecute班级

                    JSONArray jsonArray=new JSONArray(result);

                    for (int i = 0; i < 3; i++) {
                        JSONObject objJson = jsonArray.getJSONObject(i);
                        System.out.println(i+"/"+objJson.getString(Name));
                        Item objItem = new Item();

                        objItem.setName(objJson.getString(Name));
                        objItem.setLocation(objJson.getString(Location));
                        objItem.setImage(objJson.getString(Image));
                        objItem.setFounded(objJson.getString(Funding));
                        objItem.setFounded(objJson.getString(Founded));
                        objItem.setStatus(objJson.getString(Status));
                        objItem.setRowVAls(objJson.getString(RowVAl));

                        System.out.println("obj::"+objItem);
                        arrayOfList.add(objItem);
                      }

 setAdapterToListview();

我的SetAdaptertoListView班级

public void setAdapterToListview() {
        try {

        objAdapter = new NewsRowAdapter(MainActivity.this, R.layout.row,
                arrayOfList);

            listView.setAdapter(objAdapter);  //i get error on this line
        }catch(Exception e){
            e.printStackTrace();
            System.out.println(e.getMessage());

        }
    }

ITEM

public String getName() {
        return Name;
    }

    public void setName(String Name) {
        this.Name = Name;
    }

包含所有getter和setter。

整个Stacktrace

07-13 12:07:16.825  11951-11951/com.company.agsl.letsventure W/System.err﹕ java.lang.NullPointerException
07-13 12:07:16.830  11951-11951/com.company.agsl.letsventure W/System.err﹕ at com.company.agsl.letsventure.MainActivity$MyTask.onPostExecute(MainActivity.java:126)
07-13 12:07:16.835  11951-11951/com.company.agsl.letsventure W/System.err﹕ at com.company.agsl.letsventure.MainActivity$MyTask.onPostExecute(MainActivity.java:65)
07-13 12:07:16.835  11951-11951/com.company.agsl.letsventure W/System.err﹕ at android.os.AsyncTask.finish(AsyncTask.java:631)
07-13 12:07:16.835  11951-11951/com.company.agsl.letsventure W/System.err﹕ at android.os.AsyncTask.access$600(AsyncTask.java:177)
07-13 12:07:16.835  11951-11951/com.company.agsl.letsventure W/System.err﹕ at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
07-13 12:07:16.835  11951-11951/com.company.agsl.letsventure W/System.err﹕ at android.os.Handler.dispatchMessage(Handler.java:99)
07-13 12:07:16.835  11951-11951/com.company.agsl.letsventure W/System.err﹕ at android.os.Looper.loop(Looper.java:176)
07-13 12:07:16.835  11951-11951/com.company.agsl.letsventure W/System.err﹕ at android.app.ActivityThread.main(ActivityThread.java:5419)
07-13 12:07:16.835  11951-11951/com.company.agsl.letsventure W/System.err﹕ at java.lang.reflect.Method.invokeNative(Native Method)
07-13 12:07:16.835  11951-11951/com.company.agsl.letsventure W/System.err﹕ at java.lang.reflect.Method.invoke(Method.java:525)
07-13 12:07:16.835  11951-11951/com.company.agsl.letsventure W/System.err﹕ at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1046)
07-13 12:07:16.835  11951-11951/com.company.agsl.letsventure W/System.err﹕ at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:862)
07-13 12:07:16.835  11951-11951/com.company.agsl.letsventure W/System.err﹕ at dalvik.system.NativeStart.main(Native Method)
07-13 12:07:16.840  11951-11951/com.company.agsl.letsventure W/System.err﹕ java.lang.NullPointerException
07-13 12:07:16.850  11951-11951/com.company.agsl.letsventure W/System.err﹕ at android.widget.ArrayAdapter.getCount(ArrayAdapter.java:330)
07-13 12:07:16.850  11951-11951/com.company.agsl.letsventure W/System.err﹕ at android.widget.ListView.setAdapter(ListView.java:470)
07-13 12:07:16.850  11951-11951/com.company.agsl.letsventure W/System.err﹕ at com.company.agsl.letsventure.MainActivity.setAdapterToListview(MainActivity.java:169)
07-13 12:07:16.850  11951-11951/com.company.agsl.letsventure W/System.err﹕ at com.company.agsl.letsventure.MainActivity$MyTask.onPostExecute(MainActivity.java:156)
07-13 12:07:16.850  11951-11951/com.company.agsl.letsventure W/System.err﹕ at com.company.agsl.letsventure.MainActivity$MyTask.onPostExecute(MainActivity.java:65)
07-13 12:07:16.850  11951-11951/com.company.agsl.letsventure W/System.err﹕ at android.os.AsyncTask.finish(AsyncTask.java:631)
07-13 12:07:16.850  11951-11951/com.company.agsl.letsventure W/System.err﹕ at android.os.AsyncTask.access$600(AsyncTask.java:177)
07-13 12:07:16.850  11951-11951/com.company.agsl.letsventure W/System.err﹕ at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
07-13 12:07:16.855  11951-11951/com.company.agsl.letsventure W/System.err﹕ at android.os.Handler.dispatchMessage(Handler.java:99)
07-13 12:07:16.855  11951-11951/com.company.agsl.letsventure W/System.err﹕ at android.os.Looper.loop(Looper.java:176)
07-13 12:07:16.855  11951-11951/com.company.agsl.letsventure W/System.err﹕ at android.app.ActivityThread.main(ActivityThread.java:5419)
07-13 12:07:16.855  11951-11951/com.company.agsl.letsventure W/System.err﹕ at java.lang.reflect.Method.invokeNative(Native Method)
07-13 12:07:16.855  11951-11951/com.company.agsl.letsventure W/System.err﹕ at java.lang.reflect.Method.invoke(Method.java:525)
07-13 12:07:16.855  11951-11951/com.company.agsl.letsventure W/System.err﹕ at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1046)
07-13 12:07:16.855  11951-11951/com.company.agsl.letsventure W/System.err﹕ at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:862)
07-13 12:07:16.855  11951-11951/com.company.agsl.letsventure W/System.err﹕ at dalvik.system.NativeStart.main(Native Method)
07-13 12:07:16.860  11951-11951/com.company.agsl.letsventure I/System.out﹕ Exception:nullnull
07-13 12:07:16.865  11951-11951/com.company.agsl.letsventure D/AbsListView﹕ unregisterIRListener() is called
07-13 12:07:16.875  11951-11951/com.company.agsl.letsventure E/ViewRootImpl﹕ sendUserActionEvent() mView == null
07-13 12:07:17.110  11951-11951/com.company.agsl.letsventure D/AndroidRuntime﹕ Shutting down VM
07-13 12:07:17.110  11951-11951/com.company.agsl.letsventure W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x41e6f700)
07-13 12:07:17.125  11951-11951/com.company.agsl.letsventure E/AndroidRuntime﹕ FATAL EXCEPTION: main
    java.lang.NullPointerException
            at android.widget.ArrayAdapter.getCount(ArrayAdapter.java:330)
            at android.widget.ListView.onMeasure(ListView.java:1140)
            at android.view.View.measure(View.java:16831)
            at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:728)
            at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:477)
            at android.view.View.measure(View.java:16831)
            at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5245)
            at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
            at android.view.View.measure(View.java:16831)
            at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5245)
            at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1410)
            at android.widget.LinearLayout.measureVertical(LinearLayout.java:695)
            at android.widget.LinearLayout.onMeasure(LinearLayout.java:588)
            at android.view.View.measure(View.java:16831)
            at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5245)
            at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
            at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2586)
            at android.view.View.measure(View.java:16831)
            at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2189)
            at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1352)
            at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1535)
            at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1249)
            at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6364)
            at android.view.Choreographer$CallbackRecord.run(Choreographer.java:791)
            at android.view.Choreographer.doCallbacks(Choreographer.java:591)
            at android.view.Choreographer.doFrame(Choreographer.java:561)
            at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:777)
            at android.os.Handler.handleCallback(Handler.java:730)
            at android.os.Handler.dispatchMessage(Handler.java:92)
            at android.os.Looper.loop(Looper.java:176)
            at android.app.ActivityThread.main(ActivityThread.java:5419)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:525)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1046)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:862)
            at dalvik.system.NativeStart.main(Native Method)

getView

public View getView(final int position, View convertView, ViewGroup parent) {
        View view = convertView;
        ViewHolder holder;

        if (view == null) {
            LayoutInflater inflater = (LayoutInflater) activity
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            view = inflater.inflate(row, null);

            holder = new ViewHolder();
            view.setTag(holder);
        } else {

            holder = (ViewHolder) view.getTag();

        }
        System.out.println(items.size()+" :: Sizess  "+ position);
        if ((items == null) || ((position + 1) > items.size()))
            return view;

        objBean = items.get(position);

        holder.tvName = (TextView) view.findViewById(R.id.name);
        holder.tvLocation = (TextView) view.findViewById(R.id.location);
        holder.tvSector = (TextView) view.findViewById(R.id.sector);
        holder.tvFounded = (TextView) view.findViewById(R.id.foundedyear);
        holder.tvFund=(TextView) view.findViewById(R.id.fundraising);*/
        holder.ivImage= (ImageView) view.findViewById(R.id.imageButton);

        if (holder.tvName != null && null != objBean.getName()
                && objBean.getName().trim().length() > 0) {
            //holder.tvName.setText(Html.fromHtml("Name:"+objBean.getName()));
            holder.tvName.setText(Html.fromHtml(objBean.getName()));
        }

       if (holder.tvLocation != null && null != objBean.getLocation()
                && objBean.getName().trim().length() > 0) {
            holder.tvLocation.setText(Html.fromHtml(objBean.getLocation()));
        }
        if (holder.tvStatus != null && null != objBean.getStatus()
                && objBean.getName().trim().length() > 0) {
            holder.tvStatus.setText(Html.fromHtml(objBean.getStatus()));
        }
        if (holder.tvSector != null&& null != objBean.getSector()
                && objBean.getName().trim().length() > 0) {
            holder.tvSector.setText(Html.fromHtml(objBean.getSector()));
        }
        if (holder.tvFounded != null&& 0 != objBean.getFounded()
                && objBean.getName().trim().length() > 0) {
            holder.tvFounded.setText(Html.fromHtml(""+objBean.getFounded()));
        }
        if (holder.tvFund != null&& 0 != objBean.getFundAsking()
                && objBean.getName().trim().length() > 0) {
            holder.tvFund.setText(Html.fromHtml(""+objBean.getFundAsking()));
        }
        if (holder.ivImage != null&& null != objBean.getName()
                && objBean.getName().trim().length() > 0) {
            URL myUrl = null;
            try {
                myUrl = new URL(objBean.getImage());
                InputStream inputStream = (InputStream)myUrl.getContent();
                Drawable drawable = Drawable.createFromStream(inputStream, null);
                holder.ivImage.setImageDrawable(drawable);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }



        return view;
    }

3 个答案:

答案 0 :(得分:0)

如果我没错,你正在解析

"Status": 1, & "RowVAl": 1

作为

objItem.setStatus(objJson.getString(Status));
objItem.setRowVAls(objJson.getString(RowVAl));

但它们显然是整数而不是字符串。

这可能是获得空指针异常的原因。尝试修复它,它应该解决问题。

答案 1 :(得分:0)

为了最好和最快尝试这个:(使用Gson库)

 Gson gson=new Gson();
  Type listType = new TypeToken<ArrayList<Items>>() {
  }.getType();

  List<Items> itemsList=gson.fromJson(line, listType);
  rowAdapter = new RowAdapter(MainActivity.this, R.layout.row,itemsList);
  listView.setAdapter(rowAdapter);

Items上课到这里:

public class Items {
        private String Name;
        private String Location;
        private String Image;
        private String Funding;
        private String Founded;
        private int Status;
        private int RowVAI;
        // setters and getters goes here

        public Items() {
        }

       public Items(String name, String location, String image, String funding, String founded, int status, int rowVAI) {
           Name = name;
           Location = location;
           Image = image;
           Funding = funding;
           Founded = founded;
           Status = status;
           RowVAI = rowVAI;
       }

       public String getName() {
           return Name;
       }

       public void setName(String name) {
           Name = name;
       }

       public String getLocation() {
           return Location;
       }

       public void setLocation(String location) {
           Location = location;
       }

       public String getImage() {
           return Image;
       }

       public void setImage(String image) {
           Image = image;
       }

       public String getFunding() {
           return Funding;
       }

       public void setFunding(String funding) {
           Funding = funding;
       }

       public String getFounded() {
           return Founded;
       }

       public void setFounded(String founded) {
           Founded = founded;
       }

       public int getStatus() {
           return Status;
       }

       public void setStatus(int status) {
           Status = status;
       }

       public int getRowVAI() {
           return RowVAI;
       }

       public void setRowVAI(int rowVAI) {
           RowVAI = rowVAI;
       }

       @Override
       public String toString() {
           return "Items{" +
                   "Name='" + Name + '\'' +
                   ", Location='" + Location + '\'' +
                   ", Image='" + Image + '\'' +
                   ", Funding='" + Funding + '\'' +
                   ", Founded='" + Founded + '\'' +
                   ", Status=" + Status +
                   ", RowVAI=" + RowVAI +
                   '}';
       }
   }

输出:

[Items{Name='47ABC', Location='Chennai', Image='47ABC_175.png', Funding='150', Founded='2013 ', Status=1, RowVAI=0}, Items{Name='57ABC', Location='Mumbai', Image='57ABC_175.png', Funding='1250', Founded='2010 ', Status=2, RowVAI=0}]

答案 2 :(得分:0)

这是问题

您在jsonStringUtils方法中声明getJSONStringHTTPResponse。 String jsonString = null;

在任何情况下network failure or whatever error try {...}阻止getJSONStringHTTPResponse阻止你的nullPointer Exception必须返回null。所以,当你尝试 转换为JSONArray,您将在以下行中获得 JSONArray jsonArray=new JSONArray(result);

add null Pointer check in

解决方案是您需要在try {}块内找到错误并需要修复。以及onPostExecute if (view == null) { LayoutInflater inflater = (LayoutInflater) activity .getSystemService(Context.LAYOUT_INFLATER_SERVICE); view = inflater.inflate(row, null); holder = new ViewHolder(); holder.tvName = (TextView) view.findViewById(R.id.name); holder.tvLocation = (TextView) view.findViewById(R.id.location); holder.tvSector = (TextView) view.findViewById(R.id.sector); holder.tvFounded = (TextView) view.findViewById(R.id.foundedyear); holder.tvFund=(TextView) view.findViewById(R.id.fundraising);*/ holder.ivImage= (ImageView) view.findViewById(R.id.imageButton); view.setTag(holder); } else { holder = (ViewHolder) view.getTag(); } 方法。

修改1:

像这样编辑你的getView。

ob_start();
dynamic_sidebar( 'my-sidebar-id' );
$sidebar_output = ob_get_clean();
echo apply_filters( 'my_sidebar_output', $sidebar_output );

您需要在if条件

中添加findView方法