json数据不能从Web解析

时间:2016-02-27 09:14:00

标签: android json

MainActivity.java

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.ListView;
import android.widget.Toast;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;

public class MainActivity extends Activity {


    ListView list;
    ActorsAdapter adapter;
    ArrayList<Actors> actorslist;


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


        list = (ListView)findViewById(R.id.list);

        adapter = new ActorsAdapter(getApplicationContext(), R.layout.list_category, actorslist);

        list.setAdapter(adapter);
        actorslist=new ArrayList<Actors>();

        new actorsAsyncTask().execute("http://paradiseitsolutions.co.in/app/sanvi/json/getcategory.php");
        }

    public class actorsAsyncTask extends AsyncTask<String,Void,Boolean>{


        @Override
        protected Boolean doInBackground(String... params) {

                try {
                    HttpClient client= new DefaultHttpClient();
                    HttpPost post=new HttpPost(params[0]);
                    HttpResponse response= client.execute(post);
                    int status =response.getStatusLine().getStatusCode();
                    if(status==200){
                        HttpEntity entity=response.getEntity();
                        String data= EntityUtils.toString(entity);


                        JSONObject jobj= new JSONObject(data);
                        JSONArray jarray = jobj.getJSONArray("result");

                        for(int i =0;i<jarray.length();i++){

                            Actors actor = new Actors();
                            JSONObject jrealObject = jarray.getJSONObject(i);
                            actor.setId(jrealObject.getString("id"));
                            actor.setName(jrealObject.getString("name"));
                            actor.setImage(jrealObject.getString("image"));

                            actorslist.add(actor);
                        }
                        return true;
                    }
            } catch (IOException e) {
                e.printStackTrace();
            } catch (JSONException e) {
                    e.printStackTrace();
                }

            return false;
        }

        @Override
        protected void onPostExecute(Boolean result) {
            super.onPostExecute(result);

            if(result== false)
            {
                //data is not parse
                Toast.makeText(getApplicationContext(), "this is my Toast message!!! =)",
                        Toast.LENGTH_LONG).show();
            }else {
                ActorsAdapter adapter =new ActorsAdapter(getApplicationContext(),R.layout.list_category,actorslist);
                list.setAdapter(adapter);
            }
        }
    }
}

ActorsAdapter.java

    import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import java.io.InputStream;
import java.util.ArrayList;

/**
 * Created by paradise on 2/27/2016.
 */
public class ActorsAdapter extends ArrayAdapter<Actors> {



    ArrayList<Actors> ArrayListActors;
    int Resource;
    Context context;
    LayoutInflater vi;


    public ActorsAdapter(Context context, int resource, ArrayList<Actors> objects) {
        super(context, resource, objects);

        ArrayListActors =objects;
        Resource=resource;
        this.context = context;

        vi=(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

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

        ViewHolder holder;

        if(convertView == null){

            convertView = vi.inflate(Resource,null);
            holder = new ViewHolder();

            holder.ivImage = (ImageView)convertView.findViewById(R.id.ivImage);
            holder.tvId = (TextView)convertView.findViewById(R.id.tvId);
            holder.tvName = (TextView)convertView.findViewById(R.id.tvName);

            convertView.setTag(holder);
        }else {

            holder = (ViewHolder)convertView.getTag();
        }

        new DownloadImageTask(holder.ivImage).execute();
        holder.tvId.setText("id =" + ArrayListActors.get(position).getId());
        holder.tvName.setText("name=" +ArrayListActors.get(position).getName());

        return convertView;
    }



    static class ViewHolder {

        public TextView tvId;
        public ImageView ivImage;
        public TextView tvName;

    }

    private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
        ImageView bmImage;

        public DownloadImageTask(ImageView bmImage) {
            this.bmImage = bmImage;
        }
        protected Bitmap doInBackground(String... urls) {
            String urldisplay = urls[0];
            Bitmap mIcon = null;
            try {
                InputStream in = new java.net.URL(urldisplay).openStream();
                mIcon = BitmapFactory.decodeStream(in);
            } catch (Exception e) {
                Log.e("Error", e.getMessage());
                e.printStackTrace();
            }
            return mIcon;
        }

    }

}

Actors.java

    public class Actors {

    private String id;
    private String name;
    private String image;

   //getters and setters

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

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

    public String getImage() {
        return image;
    }

    public void setImage(String image) {
        this.image = image;
    }
    //default constructor
    public Actors(){

    }
}

activity_main.xml中

 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="5dp"
    tools:context="com.example.paradise.pagalshayar.MainActivity">

    <ListView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/list"
        tools:listitem="@layout/list_category">

    </ListView>
</RelativeLayout>

list_category.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">


    <TextView
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:text="id"
        android:id="@+id/tvId"/>

   <ImageView
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:id="@+id/ivImage"/>

    <TextView
        android:text="name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/tvName"/>
</LinearLayout>
  

在我的应用3类和2 xml文件中。但问题是,json没有解析应用程序已经崩溃和gove错误消息是Fatel Exception:main

错误消息

02-27 13:57:16.197 19624-19624/com.example.paradise.pagalshayar E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.paradise.pagalshayar, PID: 19624
   java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.paradise.pagalshayar/com.example.paradise.pagalshayar.MainActivity}: java.lang.NullPointerException: Attempt to invoke interface method 'int java.util.List.size()' on a null object reference
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
    at android.app.ActivityThread.-wrap11(ActivityThread.java)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:148)
    at android.app.ActivityThread.main(ActivityThread.java:5417)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.NullPointerException: Attempt to invoke interface method 'int java.util.List.size()' on a null object reference
    at android.widget.ArrayAdapter.getCount(ArrayAdapter.java:337)
    at android.widget.ListView.setAdapter(ListView.java:491)
    at com.example.paradise.pagalshayar.MainActivity.onCreate(MainActivity.java:40)
    at android.app.Activity.performCreate(Activity.java:6251)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476) 
    at android.app.ActivityThread.-wrap11(ActivityThread.java) 
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344) 
    at android.os.Handler.dispatchMessage(Handler.java:102) 
    at android.os.Looper.loop(Looper.java:148) 
    at android.app.ActivityThread.main(ActivityThread.java:5417) 
    at java.lang.reflect.Method.invoke(Native Method) 
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 

3 个答案:

答案 0 :(得分:1)

在您的错误中明确提到列表为空尝试调用接口方法&#39; int java.util.List.size()&#39;在空对象引用上

actorslist=new ArrayList<Actors>();
adapter = new ActorsAdapter(getApplicationContext(), R.layout.list_category, actorslist);

在使用之前初始化您的ArrayList

答案 1 :(得分:0)

这是问题..您正在设置列表而不初始化它。

adapter = new ActorsAdapter(getApplicationContext(), R.layout.list_category, actorslist);

onCreate()

删除这些行
 adapter = new ActorsAdapter(getApplicationContext(), R.layout.list_category, actorslist);

        list.setAdapter(adapter);

答案 2 :(得分:0)

问题是你在listview上设置适配器后初始化你的ArrayList ..............

这样做..

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


        list = (ListView)findViewById(R.id.list);
        actorslist=new ArrayList<Actors>();
        adapter = new ActorsAdapter(getApplicationContext(), R.layout.list_category, actorslist);

        list.setAdapter(adapter);


        new actorsAsyncTask().execute("http://paradiseitsolutions.co.in/app/sanvi/json/getcategory.php");
        }