java - Android - 从每个函数中获取全局变量的值

标签 java android

我使用 Android Studio 制作应用程序。我有一个名为“GlobalVariables.java”的文件,其中包含以下代码:

public class GlobalVariables extends Application {
    public String CallingActivity;

    public String getCallVariable() {
        return CallingActivity;
    }

    public void setCallVariable(String Value) {
        CallingActivity = Value;

    }
}

在 list 文件中我有:

<application android:name=".GlobalVariables" .....

我还有一个 LanguageActivity.java 文件,其中包含以下代码:

package com.testApp;

//import android.content.Intent;
//import android.support.v7.app.ActionBarActivity;
import android.app.ListActivity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Toast;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;


public class LanguageActivity extends ListActivity {
 //   public class CountrycodeActivity extends ListActivity {
 public static final String TAG = "MyActivity";
       // public static String RESULT_CONTRYCODE = "countrycode";
        public String[] countrynames;
        private TypedArray imgs;
        private List<Country> countryList;
        Locale myLocale;
        Context context;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            populateCountryList();
            ArrayAdapter<Country> adapter = new CountryListArrayAdapter(this, countryList);
            setListAdapter(adapter);
            getListView().setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    ReadWriteFile RWFile = new ReadWriteFile();
                    if (position == 0) {
                        ChangeLanguage("el", getBaseContext());
                        try {
                            RWFile.LangWrite("en",getBaseContext());
                            Log.e(TAG, "LANG === en");
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }else{
                        ChangeLanguage("en", getBaseContext());
                        try {
                            RWFile.LangWrite("en",getBaseContext());
                            Log.e(TAG, "LANG === en");
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    imgs.recycle(); //recycle images
                    finish();
                }
            });
        }

        private void populateCountryList() {
            countryList = new ArrayList<Country>();
            countrynames = getResources().getStringArray(R.array.country_names);
            //countrycodes = getResources().getStringArray(R.array.country_codes);
            imgs = getResources().obtainTypedArray(R.array.country_flags);
            for(int i = 0; i < countrynames.length; i++){
                countryList.add(new Country(countrynames[i], imgs.getDrawable(i)));
            }
        }

        public class Country {
            private String name;
           // private String code;
            private Drawable flag;
            public Country(String name, Drawable flag){
                this.name = name;
               // this.code = code;
                this.flag = flag;
            }
            public String getName() {
                return name;
            }
            public Drawable getFlag() {
                return flag;
            }
           // public String getCode() {
               // return code;
           // }
        }
        public void ChangeLanguage(String value, Context context){
            Resources res = context.getResources();
            DisplayMetrics dm = res.getDisplayMetrics();
            android.content.res.Configuration conf = res.getConfiguration();
            conf.locale = new Locale(value.toLowerCase());
            res.updateConfiguration(conf, dm);


            GlobalVariables mApp = ((GlobalVariables)getApplicationContext());
            String Activity = mApp.getCallVariable();
           if (Activity.equals("Login")){
                final Intent intent = new Intent(LanguageActivity.this, LoginActivity.class);
                startActivity(intent);
            }else if (Activity.equals("Signup")){
                final Intent intent = new Intent(LanguageActivity.this, SignupActivity.class);
                startActivity(intent);
            }
        }
    }

当我运行代码时,应用程序崩溃并出现以下错误: java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法“android.content.Context android.content.Context.getApplicationContext()” 如果我改变

GlobalVariables mApp = ((GlobalVariables)getApplicationContext());
        String Activity = mApp.getCallVariable();

String Activity = ((GlobalVariables) this.getApplication()).getCallVariable();

然后我收到错误: java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法“java.lang.String com.testApp.GlobalVariables.getCallVariable()”

我做了很多尝试,但没有任何帮助。无论如何,什么可以解决我的问题? 我为什么要这样做?我想知道哪个 Activity 调用了 ChangeLanguage() 来重新启动它以显示所选语言。

最佳答案

依赖注入(inject)将解决您的问题。如果你使用dagger2,解决这类问题会更​​好,因为创建单例会更容易。如果您愿意,我可以在这里发布您如何做到这一点。如果您希望我使用 dagger2 基础知识来编辑此答案,请在此答案下方发表评论。

关于java - Android - 从每个函数中获取全局变量的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43347134/

相关文章:

java - 同步一个进程和并行组

android - Kotlin 中的 RecyclerView itemClickListener

java - 在 Java 中从二进制转换回其字符串值

java - 主类在 JUnit 线程错误中运行异常

java - 如何在Scala中实现这种Java机制呢?

android - 检测 Android 应用何时进入后台

android - "Create project from existing source"是否修改现有样本?

android - 有没有类似 mechanize for Android 的工具?

java - 如何禁用 EditText 并保持背景颜色为白色?

java - 存储过程调用期间使用 CallableStatement 的 SQL 语句无效