如何将响应onResponse数据传递给活动?

时间:2017-12-25 15:15:06

标签: android mvvm kotlin adapter retrofit2

我想将改进响应传递给Activity,以便我可以在recyclerview适配器中设置数据。我不想使用LiveData或RxJava。 这里imageDetails是Json对象的列表,我想将它传递给MainActivity。

TrendingViewModel.kt

class TrendingViewModel : ViewModel() {

fun fetchGifs() {
    val apiService = GiphyApi().getClient()?.create(ApiInterface::class.java)
    val call = apiService?.getTrendingResults(20, Constants.API_KEY)
    var imageDetails: List<ImageDetails>


    call?.enqueue(object : retrofit2.Callback<GiphyResponse> {

        override fun onResponse(call: Call<GiphyResponse>?, response: Response<GiphyResponse>?) {
            imageDetails = response?.body()?.data!!
        }

        override fun onFailure(call: Call<GiphyResponse>?, t: Throwable?) {
        }
    })
}}

MainActivity.kt

class MainActivity : AppCompatActivity() {

private lateinit var layoutManager: RecyclerView.LayoutManager
lateinit var adapter: RecyclerViewAdapter
lateinit var trendingViewModel: TrendingViewModel

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    val binding: ActivityMainBinding = DataBindingUtil.setContentView(this, R.layout.activity_main)
    val debugTree: Timber.DebugTree = Timber.DebugTree()
    TrendingViewModel().fetchGifs()
    Timber.plant(debugTree)

    trendingViewModel = ViewModelProviders.of(this).get(TrendingViewModel::class.java)
    trendingViewModel.fetchGifs()
    layoutManager = GridLayoutManager(this, 3) as RecyclerView.LayoutManager
    binding.recyclerview.layoutManager = layoutManager
    adapter = RecyclerViewAdapter(this)
    binding.recyclerview.adapter = adapter
    adapter.setListData(//TODO I need the response data here)

}}

RecyclerViewAdapter.kt

编辑:Everthing工作正常但我的列表在调用所有默认函数后会更新。

class RecyclerViewAdapter(context: Context) : RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder>(){


private var gifList: List<ImageDetails>? = Collections.emptyList()
private var mContext: Context? = null

init {
    this.mContext = context
}

fun setListData(list: List<ImageDetails>) {
    gifList=list
    Log.i("Size SetListData", gifList!!.size.toString())

    //Here it is showing List size 20
}

override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder? {
    val binding = DataBindingUtil.inflate<RecyclerviewListItemBinding>(LayoutInflater.from(parent.context), R.layout.recyclerview_list_item,
            parent, false)

    return ViewHolder(binding)

}

override fun onBindViewHolder(holder: ViewHolder, position: Int) {
    //val binding = holder.binding;
    Log.i("Size SizeBindHolder",gifList?.size.toString())

    //Size = 0

    /*Glide.with(mContext)
            .load(gifList?.get(position)?.images?.dimen?.url)
            .into(holder.imageView)*/

}

override fun getItemCount(): Int {
    Log.i("Size ItemCount",gifList?.size.toString())
    // Size = 0 
    return gifList?.size!!
}




class ViewHolder(var binding: RecyclerviewListItemBinding) : RecyclerView.ViewHolder(binding.root) {
    var imageView: ImageView

    init {
        this.binding = binding
        imageView = binding.imageView
    }
}

2 个答案:

答案 0 :(得分:0)

您可以使用传递您需要的方法作为功能参数,请在此处尝试 fetchGifs 接受一个方法作为参数&amp;在 MainActivity 中,我们将 adapter.setListData 作为参数

传递给它
class TrendingViewModel : ViewModel() {

fun fetchGifs(callback: (giphyResponse: GiphyResponse) -> Any) {
    val apiService = GiphyApi().getClient()?.create(ApiInterface::class.java)
    val call = apiService?.getTrendingResults(20, Constants.API_KEY)
    var imageDetails: List<ImageDetails>


    call?.enqueue(object : retrofit2.Callback<GiphyResponse> {

        override fun onResponse(call: Call<GiphyResponse>?, response: Response<GiphyResponse>?) {
            imageDetails = response?.body()?.data!!
            callback(imageDetails) 
        }

        override fun onFailure(call: Call<GiphyResponse>?, t: Throwable?) {
        }
    })
}}




class MainActivity : AppCompatActivity() {

private lateinit var layoutManager: RecyclerView.LayoutManager
lateinit var adapter: RecyclerViewAdapter
lateinit var trendingViewModel: TrendingViewModel

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    val binding: ActivityMainBinding = DataBindingUtil.setContentView(this, R.layout.activity_main)
    val debugTree: Timber.DebugTree = Timber.DebugTree()
    Timber.plant(debugTree)

    trendingViewModel = ViewModelProviders.of(this).get(TrendingViewModel::class.java)
    trendingViewModel.fetchGifs()
    layoutManager = GridLayoutManager(this, 3) as RecyclerView.LayoutManager
    binding.recyclerview.layoutManager = layoutManager
    adapter = RecyclerViewAdapter(this)
    binding.recyclerview.adapter = adapter
    TrendingViewModel().fetchGifs(result -> adapter.setListData(result))


}}

答案 1 :(得分:0)

1-在您的活动中添加:

    public class MainActivity extends AppCompatActivity implements Observer { 
        ....
    }

2-在您的update()中实施方法activity

    @Override
    public void update(Observable o, Object arg) {


    }

3-创建一个Observable对象:

public class RetrofitObservable extends Observable {

    private static RetrofitObservable instance = null;

    public static RetrofitObservable getInstance() {

         if(instance == null) {

             instance = new RetrofitObservable();

         }

         return instance;
    }

    public void notifyObserverWithResponse(Object response) {

        setChanged();

        notifyObservers(response);

    }

}
活动onResume()中的

4-添加以下行:

RetrofitObservable.getInstance().addObserver(this);

5-在您的活动中onPause()添加以下行:

RetrofitObservable.getInstance().deleteObserver(this);
在您的Retrofit响应中,请拨打以下行:

RetrofitObservable.getInstance(). notifyObserverWithResponse(yourResponseHere);

7-在您的活动update方法中,处理您的回复:

@Override
public void update(Observable o, Object arg) {

    YourRetrofitResponse response = (YourRetrofitResponse) arg;

    // make your changes here

}