Данные, проанализированные из Json, не могут быть правильно выбраны при добавлении другого аргумента в конструктор - PullRequest
0 голосов
/ 13 июня 2018

Это первый раз, когда я задаю вопрос !!так терпите меня.Приложение является проектом (популярный этап фильма 2) из ​​udacity, где мне нужно получить информацию о фильмах, таких как tilte или poster_path или background_path.

, поэтому, когда я выбираю данные из json, все работает отлично, но когда я добавляю другой аргументString backdrop в моем Movies.java class.then getmBackdrop() показывает пусто, и я не могу получить данные обзора фона и голосования. Но если я удаляю фон из конструктора, это работает нормально.я не знаю, что происходит, пожалуйста, помогите мне.

это Movies.java класс

public class Movies implements Parcelable {


    //Movies Data
    public  long mID;
    private String mPosterPath;
    private String mReleaseDate;
    private String mTitle;
    private String mVote;
    private String mOverview;
    private String mBackdrop;
    private ArrayList<Trailers> trailers;
    private ArrayList<Reviews> reviews;

    public Movies() {

    }

    public Movies(String title, String releaseDate, String posterPath,
                  String backdrop,String vote, String overview) {
       // this.mID=id;
        this.mTitle = title;
        this.mReleaseDate = releaseDate;
        this.mPosterPath = posterPath;
        this.mBackdrop = backdrop;
        this.mVote = vote;
        this.mOverview = overview;
        this.trailers = new ArrayList<>();
        this.reviews = new ArrayList<>();

    }
    public long  getID(){ return mID ;}


    public String getmBackdrop() { return mBackdrop; }

    public String getPosterPath() {
        return mPosterPath;
    }

    public String getTitle() {
        return mTitle;
    }

    public String getReleaseDate() {
        return mReleaseDate;
    }

    public String getOverview() {
        return mOverview;
    }

    public String getVote() {
        return mVote +"/10";
    }

    public void setTrailers(ArrayList<Trailers> trailers) {
        this.trailers = trailers;
    }

    public void setReviews(ArrayList<Reviews> reviews) {
        this.reviews = reviews;
    }

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeLong(mID);
        dest.writeString(mTitle);
        dest.writeString(mReleaseDate);
        dest.writeString(mPosterPath);
        dest.writeValue(mBackdrop);
        dest.writeString(mVote);
        dest.writeString(mOverview);
    }

    protected Movies(Parcel in) {
        mID = in.readLong();
        mTitle = in.readString();
        mReleaseDate = in.readString();
        mPosterPath = in.readString();
        mBackdrop = in.readString();
        mVote = in.readString();
        mOverview = in.readString();
    }

    public static final Creator<Movies> CREATOR = new Creator<Movies>() {
        public Movies createFromParcel(Parcel source) {
            return new Movies(source);
        }

        public Movies[] newArray(int size) {
            return new Movies[size];
        }
    };
}

MoviepediaJsonUtils.java, где я анализирую данные

public class MoviepediaJsonUtils {
    public static ArrayList<Movies> getParseMovieJson(String jsonMovies) throws JSONException {


        final String IMAGE_BASE_URL = "https://image.tmdb.org/t/p/w500/";
        final String BACKDROP_URL= "https://image.tmdb.org/t/p/w1280/";

        JSONObject movieJson = new JSONObject(jsonMovies);
        JSONArray movieArray = movieJson.getJSONArray("results");

        ArrayList<Movies> movieArrayList = new ArrayList<>();

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

            JSONObject movieObject = movieArray.getJSONObject(i);

            long id = movieObject.getLong("id");
            String title = movieObject.getString("title");
            String release_date = movieObject.getString("release_date");
            String poster_path = movieObject.getString("poster_path");
            String backdrop = movieObject.getString("backdrop_path");
            String vote_average = movieObject.getString("vote_average");
            String overview = movieObject.getString("overview");


            Movies movies = new Movies(title, release_date,
                    IMAGE_BASE_URL + poster_path, BACKDROP_URL+backdrop,vote_average, overview);

            movieArrayList.add(movies);
        }

        return movieArrayList;
    }

    public static String getResponseFromHttpUrl(InputStream stream) throws IOException {
        Scanner scanner = new Scanner(stream);
        scanner.useDelimiter("\\A");

        boolean hasInput = scanner.hasNext();
        if (hasInput) {
            return scanner.next();
        } else {
            return null;
        }
    }

}



MainActivityFragments.java 

public class MainActivityFragments extends Fragment {
    private static final int COLUMN = 2;
    private RecyclerView mRecyclerView;
    SharedPreferences mSettings;
    GridLayoutManager mGridLayoutManager;

    private SharedPreferences.Editor mEditor;
    private static final String SHARED_KEY_SORT = "sort";
    private static final String POPULARITY = "popular";
    private static final String RATINGS = "top_rated";
    public static String[] backdrop;

    public static final String SAVE_LAST_UPDATE_ORDER = "save_last_update_order";
    private String mLastUpdateOrder;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater,
                             @Nullable ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.poster_fragment, container, false);
        if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT){
            mGridLayoutManager = new GridLayoutManager(getActivity(),2, LinearLayoutManager.VERTICAL,false);
        }else{
            mGridLayoutManager = new GridLayoutManager(getActivity(), 4,LinearLayoutManager.VERTICAL,false);
        }
        mRecyclerView = view.findViewById(R.id.rv_movies);
        mRecyclerView.setHasFixedSize(true);
        mRecyclerView.setLayoutManager(mGridLayoutManager);
        mSettings = PreferenceManager.getDefaultSharedPreferences(getActivity());
        mEditor = mSettings.edit();
        mEditor.apply();
        mRecyclerView.setAdapter(new MoviesAdapter(getActivity(), new ArrayList<Movies>()));


        return view;
    }


    @Override
    public void onStart() {
        super.onStart();
        if (needToUpdateUi()) {
            updateUi();
        }
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putString(SAVE_LAST_UPDATE_ORDER, mLastUpdateOrder);

    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        if (savedInstanceState != null) {
            mLastUpdateOrder = savedInstanceState.getString(SAVE_LAST_UPDATE_ORDER);
        }
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(true);
        updateUi();
    }


    //   OnCreateOptionMenues  will be here
    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        inflater.inflate(R.menu.poster_fragment, menu);
        Drawable drawable = menu.findItem(R.id.icon).getIcon();
        if (drawable != null) {
            drawable.mutate();
            drawable.setColorFilter(Color.WHITE, PorterDuff.Mode.SRC_ATOP);
        }
    }


    //  OnOptionitemSelected
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.poularity:
                mEditor.putString(SHARED_KEY_SORT, POPULARITY);
                mEditor.apply();
                updateUi();
                item.setChecked(true);
                return true;
            case R.id.top_rated:
                mEditor.putString(SHARED_KEY_SORT, RATINGS);
                mEditor.apply();
                updateUi();
                item.setChecked(true);
                return true;
        }
        return super.onOptionsItemSelected(item);
    }


    @Override
    public void onPrepareOptionsMenu(Menu menu) {
        super.onPrepareOptionsMenu(menu);
        String sortBy = mSettings.getString(SHARED_KEY_SORT, POPULARITY);
        if (sortBy.equals(POPULARITY)) {
            menu.findItem(R.id.poularity).setChecked(true);
        } else {
            menu.findItem(R.id.top_rated).setChecked(true);
        }
    }

    private void updateUi() {
        if (isNetworkAvailable()) {
            OnTaskCompleted taskCompleted = new OnTaskCompleted() {
                @Override
                public void onFetchMoviesTaskCompleted(ArrayList<Movies> movies) {
                    mRecyclerView.setAdapter(new MoviesAdapter(getActivity(), movies));
                }
            };
            MoviesAsyncTask moviesAsyncTask = new MoviesAsyncTask(taskCompleted);
            mSettings = PreferenceManager.getDefaultSharedPreferences(getActivity());


            String sortBy = mSettings.getString(SHARED_KEY_SORT, POPULARITY);
            mLastUpdateOrder = sortBy;
            moviesAsyncTask.execute(sortBy);
        } else {
            Toast.makeText(this.getActivity().getApplicationContext(), "Need Internet Connection", Toast.LENGTH_LONG).show();
        }
    }



    private boolean needToUpdateUi() {
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
        if (!mLastUpdateOrder.equals(prefs.getString(SHARED_KEY_SORT, POPULARITY))) {
            return true;
        } else {
            return false;
        }
    }


    //Based on a stackoverflow snippet
    private boolean isNetworkAvailable() {
        ConnectivityManager connectivityManager
                = (ConnectivityManager) this.getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();

        return activeNetworkInfo != null && activeNetworkInfo.isConnected();
    }

}

DeatailActivityFragment

public class DetailActivityFragments extends Fragment {
    private final String TAG = this.getClass().getSimpleName();




    private static final String PARCEL_KEY = "movie_parcel";
    Movies mMovie;
    OnTaskCompleted mlistener;
    ArrayList<Trailers> mTrailers;
    ArrayList<Reviews> mReviews;
    ImageView poster;
    ImageView backdrop;
    public DetailActivityFragments() {

    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.activity_detail_fragment,
                container, false);
        Movies parceableExtra = getActivity().getIntent().getParcelableExtra(PARCEL_KEY);

        poster = view.findViewById(R.id.poster_IV);
        TextView title = view.findViewById(R.id.title_TV);
        TextView releaseDate = view.findViewById(R.id.relaesedate_TV);
        TextView vote = view.findViewById(R.id.vote_TV);
        TextView overView = view.findViewById(R.id.overview_TV);
        backdrop = view.findViewById(R.id.image_id);
        final FloatingActionButton fab1 = view.findViewById(R.id.fab);

        //String gotPosition = getStringExtra("position");
        //intGotPosition=Integer.parseInt(gotPosition);
       // String url = "https://image.tmdb.org/t/p/w1280"+DetailActivityFragments.backdrop[intGotPosition];

        title.setText(parceableExtra.getTitle());
        releaseDate.setText(parceableExtra.getReleaseDate());
        vote.setText(parceableExtra.getVote());
        overView.setText(parceableExtra.getOverview());

        Picasso.with(view.getContext()).load(parceableExtra.getPosterPath())
                .into(poster);

        Picasso.with(this.getActivity()).load( parceableExtra.getmBackdrop())
                .error(R.drawable.sam).into(backdrop);


        fab1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Context context = view.getContext();
                Intent i=new Intent(context , TrailerActivity.class);
                startActivity(i);
            }
        });

        return view;
    }
}

MoviesAsyncTask.java

public class MoviesAsyncTask extends AsyncTask<String, Void, ArrayList<Movies>>  {


    private final String LOG_TAG = MoviesAsyncTask.class.getSimpleName();
    final String MY_API_KEY = "removed deliberately";
    ArrayList<Movies> mMovies;
    private OnTaskCompleted mListener;

    public MoviesAsyncTask(OnTaskCompleted listener) {
        mListener = listener;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();

    }

    @Override
    protected ArrayList<Movies> doInBackground(String... params) {


        if (params.length == 0) {
            return null;
        }

            final String MOVIEDB_BASE_URL =
                    "https://api.themoviedb.org/3/movie/";
            final String APIKEY = "api_key";


            Uri builtUri = Uri.parse(MOVIEDB_BASE_URL).buildUpon()
                    .appendPath(params[0])
                    .appendQueryParameter(APIKEY, MY_API_KEY)
                    .build();


            URL url = null;
            try {
                url = new URL(builtUri.toString());
            } catch (MalformedURLException e) {
                e.printStackTrace();
            }
            URLConnection connection = null;
            try {
                connection = url.openConnection();
            } catch (IOException e) {
                e.printStackTrace();
            }
            String response = null;
            try {
                response = MoviepediaJsonUtils.getResponseFromHttpUrl(connection.getInputStream());
            } catch (IOException e) {
                e.printStackTrace();
            }

            try {
                return MoviepediaJsonUtils.getParseMovieJson(response);
            } catch (JSONException e) {
                e.printStackTrace();
            }


        return null;
    }

    @Override
    protected void onPostExecute(ArrayList<Movies> movies) {
        super.onPostExecute(movies);
        mListener.onFetchMoviesTaskCompleted(movies);
        mMovies = movies;
    }
} 

1 Ответ

0 голосов
/ 13 июня 2018

Попытайтесь добавить вашу строку в конец вашего класса или удалить весь сгенерированный код, добавьте вашу строку, а затем снова примените реализацию пакета.

Это происходит потому, что вы не обновляете методы участка.

...