标签: android-context

Context和Acitivity有什么区别?

可能重复:
活动上下文和应用程序上下文之间的差异

何时使用Context和Activity.我已经阅读了使用Context和Activity作为参数的代码,如下面的构造函数,请在此清除我

public AmazedView(Context context, Activity activity) {
        super(context);

        mActivity = activity;

        // init paint and make is look "nice" with anti-aliasing.
        mPaint = new Paint();
        mPaint.setTextSize(14);
        mPaint.setTypeface(mFont);
        mPaint.setAntiAlias(true);

        // setup accelerometer sensor manager.
        mSensorManager = (SensorManager)                activity.getSystemService(Context.SENSOR_SERVICE);
        // register our accelerometer so we can receive values.
        // SENSOR_DELAY_GAME is the recommended rate for games
        mSensorManager.registerListener(mSensorAccelerometer, SensorManager.SENSOR_ACCELEROMETER,
                SensorManager.SENSOR_DELAY_GAME);

        // setup our maze and marble.
        mMaze = new Maze(mActivity);
        mMarble = new Marble(this);

        // load array from /res/values/strings.xml
        mStrings = …
Run Code Online (Sandbox Code Playgroud)

java android constructor android-context android-activity

3
推荐指数
2
解决办法
6024
查看次数

如何从Application对象调用activity方法finish()?

我有一段代码来删除数据库中的Item.我从两个不同的活动中调用相同的代码.因此,为了避免代码重复,我想将代码转移到Application对象.其中一个活动中的代码如下所示:

private void deleteItem() {
    AlertDialog.Builder alert = new AlertDialog.Builder(Activity1.this);
    alert.setTitle(R.string.confirmTitle);
    alert.setMessage(R.string.confirmMessage);
    alert.setPositiveButton(R.string.delete_btn,
            new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int button) {
                    final DbHelper db = new DbHelper(Activity1.this);
                    AsyncTask<Long, Void, Object> deleteTask = new AsyncTask<Long, Void, Object>() {
                        @Override
                        protected Object doInBackground(Long... params) {
                            db.deleteItem(params[0]);
                            return null;
                        }

                        @Override
                        protected void onPostExecute(Object result) {
                            finish();
                        }
                    };
                    deleteTask.execute(new Long[] { rowID });
                }
            });
    alert.setNegativeButton(R.string.cancel_btn, null).show();
}
Run Code Online (Sandbox Code Playgroud)

现在将它放在应用程序对象中,我将函数更改为public,为输入提供了两个参数:Context和rowID.但是在AsyncTask的onPostExecute方法中,我必须关闭活动.在活动中,我通过finish()完成了这个.在这种情况下我该怎么做?我也在应用程序对象中附加了代码.

public void deleteItem(final Context context, final long rowID) {
    AlertDialog.Builder alert …
Run Code Online (Sandbox Code Playgroud)

android android-context activity-finish

3
推荐指数
2
解决办法
6380
查看次数

如何在 oncreate 之外使用 SharedPreferences?

如何SharedPreferences在没有 的情况下使用oncreate

访问时得到空指针。

  public class Ftr extends Activity 

   { 
    SharedPreferences preferences;

    Context ab=this;

  public void ft()
     {
       preferences = PreferenceManager.getDefaultSharedPreferences(ab);
      String result = preferences.getString("F","");
        }
      }
Run Code Online (Sandbox Code Playgroud)

ft()从另一个活动调用 FunctionFtr只是一个类而不是一个活动。

SharedPreferences在这种情况下如何使用?

java android function android-context sharedpreferences

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

如何从上下文中获取片段对象

是否有可能从上下文对象中获取片段对象?我基本上试图从我扩展的SearchView类访问片段对象.由于context是传递给SearchView构造函数的唯一对象,因此我希望以某种方式从中获取对该片段的引用.

我知道我们可以通过使用来从活动中获取它getSupportFragmentManager().findFragmentById(R.id.xxx).但getSupportFragmentManager()只能在FragmentActivity课堂上使用.有没有办法从另一个类访问片段?

android android-context android-fragments searchview

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

getApplicationContext()返回null,但适用于其他活动

我正在使用SQLite数据库,每当我调用它时,我都需要将上下文传递给它.我通常使用getApplicationContext()来执行此操作,该工作在其他活动中.在我当前的类中,它只返回null.救命!

04-06 16:46:19.523: E/AndroidRuntime(4279): Process: com.example.schoolandrevisiontimetable, PID: 4279
04-06 16:46:19.523: E/AndroidRuntime(4279): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.schoolandrevisiontimetable/com.example.schoolandrevisiontimetable.Input_slessontime}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference
04-06 16:46:19.523: E/AndroidRuntime(4279):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2225)
04-06 16:46:19.523: E/AndroidRuntime(4279):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2388)
04-06 16:46:19.523: E/AndroidRuntime(4279):     at android.app.ActivityThread.access$800(ActivityThread.java:148)
04-06 16:46:19.523: E/AndroidRuntime(4279):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1292)
04-06 16:46:19.523: E/AndroidRuntime(4279):     at android.os.Handler.dispatchMessage(Handler.java:102)
04-06 16:46:19.523: E/AndroidRuntime(4279):     at android.os.Looper.loop(Looper.java:135)
04-06 16:46:19.523: E/AndroidRuntime(4279):     at android.app.ActivityThread.main(ActivityThread.java:5312)
04-06 16:46:19.523: E/AndroidRuntime(4279):     at java.lang.reflect.Method.invoke(Native Method)
04-06 16:46:19.523: E/AndroidRuntime(4279):     at java.lang.reflect.Method.invoke(Method.java:372)
04-06 16:46:19.523: E/AndroidRuntime(4279):     at …
Run Code Online (Sandbox Code Playgroud)

java sqlite android nullpointerexception android-context

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

如何在android中初始化Application类并存储getApplicationContext()?

我在我的应用程序中声明了一个 Application 类:

public class application extends Application {

    String TAG="joshtag";//app.TAG;

    @Override
    public void onCreate() {
        super.onCreate();
        Log.e(TAG, "Initializing APP");
        initializeSingletons(getApplicationContext());
    }

    protected void initializeSingletons(Context c){
        Log.e(TAG, "...preparing to Initialize Singleton");
        app.initInstance(c);
    }
}
Run Code Online (Sandbox Code Playgroud)

正如您想象的那样,我希望这个类在我的应用程序启动后立即运行,目的是初始化一个单例类(这个单例类不扩展任何其他类,并将包含一个变量来存储 getAppContext)。但是,日志消息永远不会在“onCreate”和“initializeSingleton”内部触发,并且单例没有被初始化。我的最终目标是存储一个全局 getAppContext 变量,我可以在不继承它的类中使用该变量。如果我以错误的心态处理问题,请告诉我并说明原因。

java singleton android android-context

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

如何从视图中获取上下文?

我已经实现了WebViewClient来覆盖onReceivedError()事件.这是我的代码:

@Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
    InternetConnectivityChecker internetConnectivityChecker = new InternetConnectivityChecker(view.getContext().getApplicationContext());

    onReceivedErrorListener.onReceivedError();
    if (internetConnectivityChecker.isConnected() == false) {

    }
}
Run Code Online (Sandbox Code Playgroud)

而且,这是我的InternetConnectivityChecker班级:

package com.sama7.sama;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

public class InternetConnectivityChecker {
    private Context context;

    public InternetConnectivityChecker(Context context) {
        context = context;
    }

    public boolean isConnected() {
        NetworkInfo info = ((ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();

        if (info == null || !info.isConnected()) {
            return false;
        }

        return true;
    }

}
Run Code Online (Sandbox Code Playgroud)

运行此代码时,我遇到异常,说:

java.lang.NullPointerException: …
Run Code Online (Sandbox Code Playgroud)

android android-context

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

我的应用程序中Global Dialog的最佳实践是什么?

我的应用程序中有自定义对话框构建器,它将触发许多事件,例如:Asynctasks,Web服务消息,UI输入错误或来自没有活动上下文的服务.我总是习惯currentActivity在我的Application类中创建一个Activity .然后恢复他们坐的每一项活动currentActivity.

  @Override
    protected void onResume() {
        super.onResume();
        MyApplication.currentActivity = MainActivity.this;
Run Code Online (Sandbox Code Playgroud)

然后在创建对话框的情况下,我使用了该上下文.但我有一个问题.例如,我打开RegisterActivity,然后currentActivity更改为它.然后,当应用程序转到后台或某些其他活动打开的情况时,我的应用程序将在创建具有该上下文的对话框时崩溃.因此处理女巫活动currentActivity是一件令人头痛的事.我用Google搜索并发现有些人将CustomDialog嵌入到非布局激活中,然后打开该活动.但似乎不是很好的解决方案.

更新

例如,我有一个SMSManager类来处理我的所有发送短信.我想打开对话框,用户在发送短信之前选择了一些自定义选项.

那么Global Dialog在我的整个应用程序中的最佳实践是什么?

android dialog android-context

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

如何在attachBaseContext调用之前获取sharedPreferences键值?

我的目标是在创建上下文之前重写应用程序语言,并且我将使用该上下文来调用其他活动.它可以通过在"onCreate"上对"重新创建()"方法进行校对,但我不想重新创建活动以实现该目标.例如

@Override
protected void attachBaseContext(Context newBase) {

    //null exception here
    SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);

    String langKey = getString(R.string.pref_language_key);
    String langValue = sharedPreferences.getString(langKey, null);

    super.attachBaseContext(ConfigurationUtil.wrapLanguage(newBase, langValue));
}
Run Code Online (Sandbox Code Playgroud)

如果这不可能,那么如何设置用户从设置中选择的应用程序语言?

android localization android-context sharedpreferences

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

Android - SharedPreferences - 上下文

我想SharedPreference使用kotlin 为我的android 创建一个帮助器类.不幸的是我需要这个Context,我不想每次调用首选项时都将它设置为参数.

如果我使用伴随对象作为上下文并在应用程序启动时设置它我得到以下错误: Do not place Android context classes in static fields; this is a memory leak (and also breaks Instant Run)

那么如何在每次调用首选项时都不通过它来获取上下文?

 var isWorking: Boolean
    get() = getBoolean(IS_WORKING)
    set(isWorking) = setPreference(IS_WORKING, isWorking)

 private fun setPreference(key: String, value: Boolean) {
    val editor = settings.edit()
    editor.putBoolean(key, value)
    editor.commit()
}

 private val settings: SharedPreferences by lazy {
    context.getSharedPreferences("prefs", Context.MODE_PRIVATE)
}
Run Code Online (Sandbox Code Playgroud)

android android-context sharedpreferences kotlin

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