doufendi9063 2017-01-27 07:03
浏览 64
已采纳

在JSON解析时,Android应用程序停止工作

Having Problem in Android Application - Unfortunately stopped Working

FATAL EXCEPTION: main Process: com.example.faizanamin.myapplication, PID: 12590 java.lang.NullPointerException: Attempt to invoke interface method 'int java.util.List.size()' on a null object reference

package com.example.faizanamin.myapplication;

import android.content.Context;
import android.os.AsyncTask;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.MenuItemHoverListener;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.accessibility.CaptioningManager;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RatingBar;
import android.widget.TextView;

import com.example.faizanamin.myapplication.models.MovieModel;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {
    private TextView tvData;
    private ListView lvMovies;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

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

        //new JSONTask().execute("http://android.devfever.com/moviesdemo.txt");


    }

    public class  JSONTask extends AsyncTask<String, String, List<MovieModel> >{
        @Override
        protected List<MovieModel> doInBackground(String... params) {
            HttpURLConnection connection = null;
            BufferedReader reader = null;
            try {
                URL url=new URL(params[0]);
                connection = (HttpURLConnection)url.openConnection();
                connection.connect();

                InputStream stream = connection.getInputStream();

                reader = new BufferedReader(new InputStreamReader(stream));
                String line="";
                StringBuffer buffer =  new StringBuffer();
                while((line=reader.readLine())!=null){
                    buffer.append(line);
                }

                String finalJson = buffer.toString();

                JSONObject parentObject = new JSONObject(finalJson);
                JSONArray parentArray = parentObject.getJSONArray("movies");


                List<MovieModel> movieModelList = new ArrayList<>();
                for(int i=0;i<parentArray.length();i++) {
                    JSONObject finalObject = parentArray.getJSONObject(i);
                    MovieModel movieModel = new MovieModel();
                    movieModel.setMovie(finalObject.getString("movie"));
                    movieModel.setYear(finalObject.getInt("year"));
                    movieModel.setRating((float) finalObject.getDouble("rating"));
                    movieModel.setDirector(finalObject.getString("director"));
                    movieModel.setDuration(finalObject.getString("duration"));
                    movieModel.setTagline(finalObject.getString("tagline"));
                    movieModel.setImage(finalObject.getString("image"));
                    movieModel.setStory(finalObject.getString("story"));

                    List<MovieModel.Cast> castList = new ArrayList<>();
                    for(int j=0; j<finalObject.getJSONArray("cast").length(); j++){
                        MovieModel.Cast cast = new MovieModel.Cast();
                        cast.setName(finalObject.getJSONArray("cast").getJSONObject(j).getString("name"));
                        castList.add(cast);
                    }
                    movieModel.setCastList(castList);
                    movieModelList.add(movieModel);
                }
                return movieModelList;
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (JSONException e) {
                e.printStackTrace();
            } finally {
                if (connection!=null) {
                    connection.disconnect();
                }
                try {
                    if(reader!=null){
                        reader.close();}
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return null;
        }

        @Override
        protected void onPostExecute(List<MovieModel> result) {
            super.onPostExecute(result);

            // TODO NEED TO SET DATA
            MovieAdapter adapter = new MovieAdapter(getApplicationContext(),R.layout.row,result);
            lvMovies.setAdapter(adapter);
        }
    }
    public class MovieAdapter extends ArrayAdapter{

        private List<MovieModel> movieModelList;
        private int resource;
        private LayoutInflater inflater;
        public MovieAdapter(Context context, int resource, List<MovieModel> objects) {
            super(context, resource, objects);
            movieModelList = objects;
            this.resource = resource;
            inflater = (LayoutInflater)getSystemService(LAYOUT_INFLATER_SERVICE);


        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if(convertView == null){
                convertView = inflater.inflate(resource,null);
            }
            ImageView lvMovieIcon;
            TextView tvMovie,tvTagline,tvYear,tvDuration,tvDirector,tvCast,tvStory;
            RatingBar rMovieRating;

            lvMovieIcon = (ImageView)findViewById(R.id.imageView);
            tvMovie = (TextView)findViewById(R.id.movieName);
            tvTagline = (TextView)findViewById(R.id.tagline);
            tvYear = (TextView)findViewById(R.id.year);
            tvDuration = (TextView)findViewById(R.id.duration);
            tvDirector = (TextView)findViewById(R.id.director);
            rMovieRating = (RatingBar) findViewById(R.id.rating);
            tvCast = (TextView)findViewById(R.id.cast);
            tvStory = (TextView)findViewById(R.id.story);

            tvMovie.setText(movieModelList.get(position).getMovie());
            tvTagline.setText(movieModelList.get(position).getTagline());
            tvYear.setText("Year: "+movieModelList.get(position).getYear());
            tvDuration.setText(movieModelList.get(position).getDuration());
            tvDirector.setText(movieModelList.get(position).getDirector());
            //Rating Bar
            rMovieRating.setRating(movieModelList.get(position).getRating()/2);
            StringBuffer stringBuffer = new StringBuffer();
            for(MovieModel.Cast cast:movieModelList.get(position).getCastList()){
                stringBuffer.append(cast.getName()+", ");
            }
            tvCast.setText(stringBuffer);
            tvStory.setText(movieModelList.get(position).getStory());
            return convertView;
        }
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu){
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item){
        int id = item.getItemId();
        if(id == R.id.action_refreash){
            new JSONTask().execute("http://android.devfever.com/allmovielist.txt");
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}
  • 写回答

1条回答 默认 最新

  • dongzuo9096 2017-01-27 07:15
    关注

    I think you are not getting JSON from your webservice so You should check list in onPostExecute and then set Adapter like this

         @Override
            protected void onPostExecute(List<MovieModel> result) {
                super.onPostExecute(result);
               // TODO NEED TO SET DATA
               if(result != null && result.size() > 0){
                   MovieAdapter adapter = new MovieAdapter(getApplicationContext(),R.layout.row,result);
                   lvMovies.setAdapter(adapter);
                }
            }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 ansys fluent计算闪退
  • ¥15 有关wireshark抓包的问题
  • ¥15 需要写计算过程,不要写代码,求解答,数据都在图上
  • ¥15 向数据表用newid方式插入GUID问题
  • ¥15 multisim电路设计
  • ¥20 用keil,写代码解决两个问题,用库函数
  • ¥50 ID中开关量采样信号通道、以及程序流程的设计
  • ¥15 U-Mamba/nnunetv2固定随机数种子
  • ¥15 vba使用jmail发送邮件正文里面怎么加图片
  • ¥15 vb6.0如何向数据库中添加自动生成的字段数据。