简体   繁体   中英

How i can send my Retrofit data from MainActivity to my Fragment?

I have one api for movies, i want to show in MovieFragment popular movies. For testing at first i want to show movies title in textview. Sorry for my English. Please help me , I'm confused. My MainActivity.java code:

package com.example.view;

import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;

import android.os.Bundle;
import android.widget.Toast;

import com.example.view.fragments.MovieFragment;
import com.example.workingproject.R;
import com.google.android.material.bottomnavigation.BottomNavigationView;

import java.util.List;

import retrofit.IApiInterface;
import retrofit.MoviesResult;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class MainActivity extends AppCompatActivity {

    private static final String BASE_URL = "https://developers.themoviedb.org/";
    private static final String API_KEY = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
    private static final String CATEGORY = "Popular";
    private static final String LANGUAGE = "en-US";
    public static int pages = 1;

    private String text;

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

        BottomNavigationView bottomNavigationView = findViewById(R.id.bottom_nav);
        bottomNavigationView.setOnNavigationItemSelectedListener(navListener);

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        IApiInterface apiInterface = retrofit.create(IApiInterface.class);

        Call<MoviesResult> moviesResultCall = apiInterface.getPopularMovies(CATEGORY, API_KEY, LANGUAGE, pages);

        moviesResultCall.enqueue(new Callback<MoviesResult>() {

            @Override
            public void onResponse(Call<MoviesResult> call, Response<MoviesResult> response) {
                if (response.isSuccessful()) {
                    MoviesResult moviesResult = response.body();

                    List<MoviesResult.Result> result = moviesResult.getResults();

                    for (MoviesResult.Result r : result) {
                        text = r.getTitle();
                        Toast.makeText(MainActivity.this, "text", Toast.LENGTH_SHORT).show();
                    }
                }
            }

            @Override
            public void onFailure(Call<MoviesResult> call, Throwable t) {
                t.printStackTrace();
            }
        });
    }

    private BottomNavigationView.OnNavigationItemSelectedListener navListener = ((menuItem) -> {
        Fragment selectedFragment = null;

        switch (menuItem.getItemId()) {
            case R.id.frame_container:
                selectedFragment = new MovieFragment();
                break;
        }

        getSupportFragmentManager().beginTransaction().replace(R.id.frame_container, selectedFragment).commit();
        return true;
    });
}

In This fragment i want to get data from MainActivity and append it in my textview. My Fragment code:

package com.example.view.fragments;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import com.example.workingproject.R;

import retrofit.MoviesResult;

public class MovieFragment extends Fragment {

    private TextView textView;

    private OnDataSetListener listener;

    public interface OnDataSetListener {
         void sendData(String data);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_movies, container, false);

        textView = view.findViewById(R.id.text_view);

        return view;
    }
}

The easiest way to communicate between your activity and fragments is using interfaces. The idea is basically to define an interface inside a given fragment A and let the activity implement that interface.

Once it has implemented that interface, you could do anything you want in the method it overrides.

The other important part of the interface is that you have to call the abstract method from your fragment and remember to cast it to your activity. It should catch a ClassCastException if not done correctly.

There is a good tutorial on Simple Developer Blog on how to do exactly this kind of thing.

I hope this was helpful to you!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM