我在onPostExecute()方法中获得空指针异常

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (103)
public class MainActivity extends AppCompatActivity {

    private recycleradapter adapter;


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

        new utility().execute("https://api.themoviedb.org/3/movie/popular?");

        RecyclerView rv = (RecyclerView)findViewById(R.id.recycle);
        rv.setLayoutManager(new GridLayoutManager(MainActivity.this,2));
       adapter = new recycleradapter(MainActivity.this,new ArrayList<movie>());
       rv.setAdapter(adapter);
    }
    }

效用类

public class utility extends AsyncTask<String,Void,ArrayList> {

    private recycleradapter adapter;
    private ArrayList<movie> movielist= new ArrayList<movie>();
    final static String API_PARAM="api_key";
    private static final String LOG_TAG = utility.class.getSimpleName();
    String getJsonresponse = "";


    @Override
    protected ArrayList<movie> doInBackground(String... strings) {

        URL url = buildUrl(strings[0]);
        try {
            getJsonresponse = makehttprequest(url);
        }
        catch (IOException e) {
            e.printStackTrace();
        }
        return movielist;
    }

    @Override
    protected void onPostExecute(ArrayList<movie> movies) {

        adapter.updatemovies(movies);
        adapter.notifyDataSetChanged();

    }



    public  URL buildUrl(String movieurl)
        {
            String MOVIE_BASE_URL = movieurl;

            Uri builturi = Uri.parse(MOVIE_BASE_URL).buildUpon()
                    .appendQueryParameter(API_PARAM,BuildConfig.MyMovieApiKey)
                    .build();

            URL url = null;

            try {
                url = new URL(builturi.toString());
                Log.d(LOG_TAG,builturi.toString());
            }
            catch (MalformedURLException e)
            {
                e.printStackTrace();
            }
            return url;
        }

        public  String makehttprequest(URL url)throws IOException
        {
            String jsonresponse = null;
            if(url==null)
                return jsonresponse;
            HttpURLConnection urlConnection = null;
            InputStream reader  = null;
            try
            {
                urlConnection = (HttpURLConnection) url.openConnection();
                urlConnection.setReadTimeout(10000);
                urlConnection.setConnectTimeout(15000);
                urlConnection.setRequestMethod("GET");
                urlConnection.connect();

                if (urlConnection.getResponseCode() == 200)
                {
                    Log.v(LOG_TAG,""+urlConnection.getResponseCode());
                    reader = urlConnection.getInputStream();
                    jsonresponse = readFromStream(reader);
                }
                else
                {
                    Log.e(LOG_TAG, "error while connecting" + urlConnection.getResponseCode());
                }
            }
            catch (IOException e) {
                Log.e(LOG_TAG, "error while parsing json Response", e);
            }
            finally {
                if (urlConnection != null)
                    urlConnection.disconnect();
                if (reader != null)
                    reader.close();
            }
            return jsonresponse;
        }

        public  String readFromStream(InputStream reader)throws IOException
        {
            StringBuilder output = new StringBuilder();
            if (reader != null) {
                InputStreamReader isr = new InputStreamReader(reader, Charset.forName("UTF-8"));
                BufferedReader br = new BufferedReader(isr);
                String line = br.readLine();
                while (line != null) {
                    output.append(line);
                    line = br.readLine();
                }
                //   Log.v("imout",LOG_TAG);
            }
            return output.toString();
        }

        public  ArrayList<movie> parsejson(String jsoninput)throws JSONException
        {
            String posterpath = "";
            String id = "";
            try
            {
                JSONObject jobj = new JSONObject(jsoninput);
                JSONArray result = jobj.getJSONArray("results");

                for(int i=0;i<result.length();i++)
                {
                    movie contract  = new movie();
                    JSONObject firstresult = result.getJSONObject(i);
                    posterpath = firstresult.getString("poster_path");
                    id = firstresult.getString("id");
                    contract.setId(id);
                    contract.setPoster(posterpath);
                    movielist.add(contract);
                }

            }
            catch (JSONException e)
            {
                Log.e(LOG_TAG,"inside parsejson",e);
            }
            return movielist;
        }

    }

适配器类

public class recycleradapter extends RecyclerView.Adapter<recycleradapter.ViewHolder> {

    private LayoutInflater mInflater;
    //  private TextView myTextView;
    private ArrayList<movie> mtext;
    private int mnoofitems;
    private String animal;
    movie x;

    public recycleradapter(Context context, ArrayList<movie> text) {

        this.mtext = text;
        this.mInflater = LayoutInflater.from(context);
    }

    public void updatemovies(ArrayList<movie> movies)
    {
        this.mtext = movies;
    }
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = mInflater.inflate(R.layout.recyclervw, parent, false);
        return new ViewHolder(view);
    }

    public void onBindViewHolder(ViewHolder holder, int position) {
        x = mtext.get(position);
        holder.bind(position);
    }

    @Override
    public int getItemCount() {
        return mtext.size();
    }


    public class ViewHolder extends RecyclerView.ViewHolder  {
        TextView myImageView;
        // TextView myText;

        ViewHolder(View itemView) {
            super(itemView);
            myImageView = (TextView) itemView.findViewById(R.id.image);

        }

        /*     @Override
             public void onClick(View view) {
                 if (mClickListener != null) mClickListener.onItemClick(view, getAdapterPosition());
             }
     */
        public void bind(int position) {
            //  myImageView.setImageBitmap();
             myImageView.setText(x.getPoster());
        }
    }

我只是试图显示电影海报ID,但是在onPostExecute()方法中获得空指针异常。我无法调试它。这是我所得到的错误的片段

6-16 21:51:36.441 18466-18466/com.example.tarun.moviereview E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.tarun.moviereview, PID: 18466
    java.lang.NullPointerException: Attempt to invoke virtual method 'void com.example.tarun.moviereview.recycleradapter.updatemovies(java.util.ArrayList)' on a null object reference
        at com.example.tarun.moviereview.utility.onPostExecute(utility.java:57)
        at com.example.tarun.moviereview.utility.onPostExecute(utility.java:23)
        at android.os.AsyncTask.finish(AsyncTask.java:660)
        at android.os.AsyncTask.-wrap1(AsyncTask.java)
        at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:677)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:163)
        at android.app.ActivityThread.main(ActivityThread.java:6342)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:880)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:770)
提问于
用户回答回答于

你正在尝试在空指针上使用方法adapter

@Override
protected void onPostExecute(ArrayList<movie> movies) {
    adapter.updatemovies(movies); // adapter has not been initialized
    adapter.notifyDataSetChanged();
}
用户回答回答于

公共类实用程序扩展AsyncTask{

你就是这样定义AsyncTask的吗?应该是

public class Utility extends AsyncTask<String, Void, ArrayList<movie>{

所属标签

可能回答问题的人

  • 天使的炫翼

    15 粉丝531 提问35 回答
  • 旺仔小小鹿

    社区 · 运营 (已认证)

    48 粉丝0 提问27 回答
  • 富有想象力的人

    2 粉丝0 提问26 回答
  • 发条丶魔灵1

    6 粉丝525 提问25 回答

扫码关注云+社区

领取腾讯云代金券