gpt4 book ai didi

java - 找不到符号方法 getcontext

转载 作者:行者123 更新时间:2023-12-01 16:51:06 26 4
gpt4 key购买 nike

我是 android/java 编程新手,并且遇到错误,提示符号 getContext 无法解析。该系统以Activity启动,有两个fragment。第一个是显示 Rest Api 的按钮。请帮忙

InstansiActivity.java:

package com.example.instansi;


import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.os.Bundle;


import com.example.instansi.adapter.InstansiAdapter;
import com.example.instansi.model.DaftarInstansiItem;

import java.util.ArrayList;

public class InstansiActivity extends AppCompatActivity {
private InstansiAdapter instansiAdapter;
private RecyclerView rvInstansi;
private com.example.instansi.viewmodel.InstansiViewModel instansiViewModel;

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

instansiAdapter= new InstansiAdapter(getContext());
instansiAdapter.notifyDataSetChanged();

rvInstansi= view.findViewById(R.id.finstansi_rv);
rvInstansi.setLayoutManager(new GridLayoutManager(getContext(),1));

instansiViewModel= new ViewModelProvider(this).get(com.example.instansi.viewmodel.InstansiViewModel.class);
instansiViewModel.setInstansi();
instansiViewModel.getInstansi().observe(this, getInstansi_);

rvInstansi.setAdapter(instansiAdapter);
}


private Observer<ArrayList<DaftarInstansiItem>> getInstansi_ = new Observer<ArrayList<DaftarInstansiItem>>() {
@Override
public void onChanged(ArrayList<DaftarInstansiItem> daftarInstansiItems) {
if (daftarInstansiItems != null) {
instansiAdapter.setData(daftarInstansiItems);
}
}
};
}

最佳答案

获取 Activity 上下文的简单方法是放置this

在您的 Activity 中,要获取 Activity 上下文,请使用 this,要获取 applicationContext(),请使用 getApplicationContext()

activity contextapplication context 之间最区别是:Application context 与应用程序的生命周期相关联,而Activity contextActivity生命周期相关联。

关于java - 找不到符号方法 getcontext,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61685807/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com