标签: android-context

可以使用"mContext"(在onCreate初始化)吗?

这是一个坏习惯,为什么会这样?因此,在onCreate之后添加此权限的每个活动 ......

mContext = this;
Run Code Online (Sandbox Code Playgroud)

然后用它在所有其他情况下的上下文必需的?例如

Toast.makeText(mContext, mContext.getString(R.string.someString), Toast.LENGTH_LONG);
Run Code Online (Sandbox Code Playgroud)

编辑:如果我有这样的事情......如何传递上下文怎么办?因为不能应用(因为View.OnClickListener()).

someButton = (Button) findViewById(R.id.someButton);
someButton.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        Toast.makeText(mContext, mContext.getString(R.string.warning), Toast.LENGTH_LONG).show();
    }
});
Run Code Online (Sandbox Code Playgroud)

android android-context

1
推荐指数
1
解决办法
9413
查看次数

将Context从主Activity传递到另一个类

这可能是错误的方法,所以请告诉我是否是这种情况:

我正在尝试在另一个类中使用getFileStreamPath(根据我的理解派生自Context),将一些代码与主活动类分开.我这样做是通过将主活动的上下文传递给另一个类,并使用它来调用其方法.

在我的主要活动课程中:

LocalStorage lc = new LocalStorage(this);
Run Code Online (Sandbox Code Playgroud)

然后,在另一个班级:

public class LocalStorage {
    Context ctx;

    public LocalStorage (Context c) {
        c = ctx;
        File lfile = ctx.getFileStreamPath("Activity.log");

    ....
Run Code Online (Sandbox Code Playgroud)

但显然我遗漏了一些东西,因为在LocalStorage类中传递的上下文上运行getFileStreamPath会导致NullPointerException.

android android-context

1
推荐指数
1
解决办法
2182
查看次数

来自 Activity.onStart() 的静态上下文

我想从一个类生成通知,Utilities.java,的子类之外Context。我也想过提供SingletonContext类和已经看过帖子IKE。我希望能够return != null Context反对,因为通知可以在任何给定时间生成,因为它是从messageReceived()回调生成的。

做这样的事情有什么缺点:

public static Context c;    

public class MainActivity extends Activity{
    @Override
    public void onStart()
      super.onStart()
      c = this.getApplicationContext();
}

//other method somewhere outside this class
public Context getContext(){
   return MainActivity.c
}
Run Code Online (Sandbox Code Playgroud)

我认为这与将其放在 上没有任何不同onCreate(),但是,它可以保证活动开始时上下文是最新的。

java static android android-context

1
推荐指数
1
解决办法
2909
查看次数

Android - 如何将上下文参数传递给方法?

我正在尝试为我女儿开发一个简单的应用程序,但我不是专业人士:)

我想知道如何将上下文传递给布尔方法?

我的问题是,当尝试合并下面的两个代码时

private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager 
     = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null;}
Run Code Online (Sandbox Code Playgroud)

public static boolean hasActiveInternetConnection(Context context) {
if (isNetworkAvailable(context)) {
    try {
        HttpURLConnection urlc = (HttpURLConnection) (new URL("http://www.google.com").openConnection());
        urlc.setRequestProperty("User-Agent", "Test");
        urlc.setRequestProperty("Connection", "close");
        urlc.setConnectTimeout(1500); 
        urlc.connect();
        return (urlc.getResponseCode() == 200);
    } catch (IOException e) {
        Log.e(LOG_TAG, "Error checking internet connection", e);
    }
} else {
    Log.d(LOG_TAG, "No network available!");
}
return false;}
Run Code Online (Sandbox Code Playgroud)

我收到错误是因为我不知道如何传递Context参数。

parameters android android-context

1
推荐指数
1
解决办法
6008
查看次数

如何在无法从 getApplicationContext() 获取上下文的情况下初始化上下文?

我想访问一个扩展 SQLiteOpenHelper 的类以从 java 类获取数据库的上下文。我需要传递应用程序上下文才能获得它,但无权访问 getApplicationContext()。

如何在非活动的 java 类中获取应用程序上下文?

android android-context

1
推荐指数
1
解决办法
1万
查看次数

RecyclerView.Adapter的上下文

我想添加ProgressDialog一个适配器。AFAIK,.this用于活动和getActivity.getApplicationContext()片段。那适配器呢?可能吗?

Unable to add window -- token null is not valid; is your activity running?使用时出现错误mContext.getApplicationContext()

编辑:

在一个片段中,我将卡片显示为

allGroupsView = (RecyclerView) rootView.findViewById(R.id.allGroupsView);
adapterGroup = new AdapterGroup(getActivity().getApplicationContext(), results);
allGroupsView.setAdapter(adapterGroup);
allGroupsView.setLayoutManager(new LinearLayoutManager(getActivity().getApplicationContext()));
Run Code Online (Sandbox Code Playgroud)

在班上 AdapterGroup

public class AdapterGroup extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

private Context mContext;
private LayoutInflater inflater;
List<DataGroup> data= Collections.emptyList();
DataGroup current;

public AdapterGroup(Context context, List<DataGroup> results) {
    this.mContext = context;
    inflater = LayoutInflater.from(mContext);
    this.data = results;
}

// Inflate the layout when viewholder created …
Run Code Online (Sandbox Code Playgroud)

android android-context android-adapter

1
推荐指数
1
解决办法
6170
查看次数

Android数据绑定的疑惑

It seems to me that Android Data Binding is an interesting tool, but it doesn't tie very well with the (overly) complex architecture of Android. Many example or tutorials show only some basic scenario that obviously works, but when things become harder then problems arise.

For example: many views (like RecyclerView or ViewPager) require adapters or decorators that need Context and it seems wrong to pass the Context to every ViewModel because it breaks the separation of layers.

ViewFlipper: how …

data-binding android android-context android-recyclerview android-databinding

1
推荐指数
1
解决办法
1260
查看次数

getSystemService() 不适用于适配器类

我试图将 onClickListener 添加到 RecyclerView 内的一个按钮,该按钮复制一个字符串,但它说 getSystemService(CLIPBOARD_SERVICE) 不可用。

public void onBindViewHolder(ViewHolder holder, int position) {
        holder.title.setText(cardItems.get(position).title);
        holder.content.setText(cardItems.get(position).content);
        holder.copyButton.setOnClickListener(new View.OnClickListener(){
            public void onClick(View v){

                myClipboard = (ClipboardManager)getSystemService(CLIPBOARD_SERVICE);
                String text;
                text = EditText.getText().toString();
                myClip = ClipData.newPlainText("text", text);
                myClipboard.setPrimaryClip(myClip);

                Toast.makeText(getApplicationContext(), "Text Copied", Toast.LENGTH_SHORT).show();
            }
        });
    }
Run Code Online (Sandbox Code Playgroud)

java android android-context android-adapter clipboardmanager

1
推荐指数
1
解决办法
3686
查看次数

IllegalStateException:片段 YoutubeLessonFragment 未附加到上下文

YouTubePlayerSupportFragment在我的一个片段中使用,但我没有在布局文件中使用它,而是以编程方式初始化它。一些用户在运行时面临此崩溃:

Fatal Exception: java.lang.IllegalStateException: Fragment YoutubeLessonFragment{3a2e875} not attached to a context.
       at android.support.v4.app.Fragment.requireContext(Fragment.java:614)
       at android.support.v4.app.Fragment.getResources(Fragment.java:678)
       at android.support.v4.app.Fragment.getString(Fragment.java:700)
       at com.musicmuni.riyaz.youtubelesson.YoutubeLessonFragment.loadYoutubeVideo(YoutubeLessonFragment.java:168)
       at com.musicmuni.riyaz.youtubelesson.YoutubeLessonPresenter$2.onModuleLoaded(YoutubeLessonPresenter.java:188)
       at com.musicmuni.riyaz.data.AppDataRepositoryImpl$10.run(AppDataRepositoryImpl.java:187)
       at android.os.Handler.handleCallback(Handler.java:754)
       at android.os.Handler.dispatchMessage(Handler.java:95)
       at android.os.Looper.loop(Looper.java:163)
       at android.app.ActivityThread.main(ActivityThread.java:6221)
       at java.lang.reflect.Method.invoke(Method.java)
       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904)
       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:794)
Run Code Online (Sandbox Code Playgroud)

我用于初始化 youtube 片段的代码如下:

private YouTubePlayerSupportFragment youtubePlayerFrag;
.........
    public void loadYoutubeVideo(String videoId) {
            mVideoId = videoId;
            if(getContext() != null) {
                youtubePlayerFrag = YouTubePlayerSupportFragment.newInstance();
                youtubePlayerFrag.initialize(getString(R.string.youtube_api_developer_key),
                        this);
                getChildFragmentManager().beginTransaction().add(R.id.flYoutubeVideoHolder,
                        youtubePlayerFrag).commit();
            }
        }
Run Code Online (Sandbox Code Playgroud)

其中,loadYoutubeVideo(...)从正在运行的线程加载所需要的视频ID的背景下得到一个回调。这里有什么指点吗?

android android-context android-youtube-api

1
推荐指数
1
解决办法
4364
查看次数

如何在 Kotlin 中追加 2 个字符串?

我正在尝试连接 2 个字符串,但不知道如何去做。

这是我的代码:

 val word = R.string.word
Run Code Online (Sandbox Code Playgroud)

我试图将它附加到"$currentPage/5"里面我试图以这种方式 和这种方式setText("$currentPage/5") 制作它 ,但它不起作用,它只显示数字而不是文本setText("$word $currentPage/5")setText("${R.string.value} $currentPage/5")

android android-context kotlin

1
推荐指数
1
解决办法
1万
查看次数