Implementing code from activity class to fragment

时间:2017-05-16 09:20:52

标签: android android-fragments

I have an activity that uses the following piece of code:

MainActivity.this.movies.add(movie);

Now I am trying to use the same piece of code in a fragment, like below:

getActivity().this.movies.add(movie);

But, I am getting an error at this line: Cannot resolve symbol movies

I have also tried with

getActivity().movies.add(movie);

but no success either.

All other parts of the fragment are correct.

EDITED

Complete method:

 private void getMoviesFromDB(int id) {

        AsyncTask<Integer, Void, Void> asyncTask = new AsyncTask<Integer, Void, Void>() {
            @Override
            protected Void doInBackground(Integer... movieIds) {

                OkHttpClient client = new OkHttpClient();
                Request request = new Request.Builder()
                        .url("http://.../movies.php?id=" + movieIds[0])
                        .build();
                try {
                    okhttp3.Response response = client.newCall(request).execute();

                    JSONArray array = new JSONArray(response.body().string());

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

                        JSONObject object = array.getJSONObject(i);

                        Movie movie = new Movie(object.getInt("id"), object.getString("movie_name"),
                                object.getString("movie_image"), object.getString("movie_genre"));

                        getActivity().movies.add(movie);
                    }


                } catch (IOException e) {
                    e.printStackTrace();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                return null;
            }

EDITED, COMPLETE ACTIVITY CLASS

import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;

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

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

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;


public class MainActivity extends AppCompatActivity {

    private static final String TAG = MainActivity.class.getSimpleName();
    private List<Movie> movies;
    private RecyclerView recyclerView;
    private GridLayoutManager gridLayout;
    private MoviesAdapter adapter;


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

        recyclerView = (RecyclerView) findViewById(R.id.recyclerview);
        movies = new ArrayList<>();
        getMoviesFromDB(0);

        gridLayout = new GridLayoutManager(this, 2);
        recyclerView.setLayoutManager(gridLayout);

        adapter = new MoviesAdapter(this, movies);
        recyclerView.setAdapter(adapter);

        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {

                if (gridLayout.findLastCompletelyVisibleItemPosition() == movies.size() - 1) {
                    getMoviesFromDB(movies.get(movies.size() - 1).getId());
                }

            }
        });


    }


    private void getMoviesFromDB(int id) {

        AsyncTask<Integer, Void, Void> asyncTask = new AsyncTask<Integer, Void, Void>() {
            @Override
            protected Void doInBackground(Integer... movieIds) {

                OkHttpClient client = new OkHttpClient();
                Request request = new Request.Builder()
                        .url("http://juarezserver.com/movies/movies.php?id=" + movieIds[0])
                        .build();
                try {
                    Response response = client.newCall(request).execute();

                    JSONArray array = new JSONArray(response.body().string());

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

                        JSONObject object = array.getJSONObject(i);

                        Movie movie = new Movie(object.getInt("id"), object.getString("movie_name"),
                                object.getString("movie_image"), object.getString("movie_genre"));

                        MainActivity.this.movies.add(movie);
                    }


                } catch (IOException e) {
                    e.printStackTrace();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                return null;
            }

            @Override
            protected void onPostExecute(Void aVoid) {
                adapter.notifyDataSetChanged();
            }
        };

        asyncTask.execute(id);
    }


}

3 个答案:

答案 0 :(得分:1)

You need to convert the Activity to your Activity like below:

((MainActivity)getActivity()).movies.add(movie);

答案 1 :(得分:1)

Make sure you have declared movies as a static field, otherwise it will not be accessible from the fragment.

public static List<Movies> movies = new ArrayList<Movies>();

Now add by below way

((MainActivity) getActivity()).movies.add(movie);

答案 2 :(得分:1)

如果您想将电影设为私有,则必须在MainActivity中创建一个公共方法来更改电影值:

public void addMovie(Movie movie){
    movies.add(movie);
}

然后你可以从Fragment这样调用它:

((MainActivity) getActivity()).addMovie(movie);