1

I use Android Studio to make an app. I have a file named 'GlobalVariables.java' and this code in it:

public class GlobalVariables extends Application {
    public String CallingActivity;

    public String getCallVariable() {
        return CallingActivity;
    }

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

    }
}

In the manifest file I have:

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

I also have a LanguageActivity.java file which has this code:

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);
            }
        }
    }

When I run the code, the app craches with this error: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference If I change

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

to

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

then I get error: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.testApp.GlobalVariables.getCallVariable()' on a null object reference

I did many tries but nothing helped. What will solve my problem anyway? Why do I do this? I want to know which Activity called ChangeLanguage() to restart it to show the selected language.

PEHLAJ
  • 9,980
  • 9
  • 41
  • 53
John Stergiou
  • 47
  • 1
  • 7
  • Possible duplicate of [What is a NullPointerException, and how do I fix it?](http://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it) – Martin De Simone Apr 11 '17 at 13:21

4 Answers4

0

Dependency injection will solve your problem. If you use dagger2, solve this kind of problem will be better, because will be easier create singletons. If you want i can post here how you can do this. Comment below this answer if you want me to edit this with dagger2 basics.

Danilo Silva
  • 171
  • 9
0

Add this to the AndroidManifest.xml:

<application
    android:name=".GlobalVariables"/>
Doron Yakovlev Golani
  • 5,188
  • 9
  • 36
  • 60
0

Try:

public class GlobalVariables extends Application {
public String CallingActivity;
public staric GlobalVariables instance;

@Override
public void onCreate()
{super.onCreate();
 this.instance = this;
}

public String getCallVariable() {
    return CallingActivity;
}

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

}

public static GlobalVariables getInstance()
{
    return instance;
}
}

String Activity = GlobalVariables.getInstance().getCallVariable();

maatik5
  • 148
  • 16
  • With your code I get this error: java.lang.NullPointerException: Attempt to invoke virtual method 'android.app.ActivityThread$ApplicationThread android.app.ActivityThread.getApplicationThread()' on a null object reference – John Stergiou Apr 11 '17 at 13:57
0

Try replacing the line

GlobalVariables mApp = ((GlobalVariables)getApplicationContext());

with:

GlobalVariables mApp = new GlobalVariables();

And in line :

String Activity = mApp.getCallVariable();

Replace 'Activity' with 'activity' because Activity is a pre-defined word.

Edit 1: IS this is how you tried:

GlobalVariables mApp = GlobalVariables.getInstance();
mApp.setCallVariable(value);
mApp.getCallVariable();
Sindhu
  • 421
  • 1
  • 6
  • 16
  • With your changes and the code of maatik5 the app runs but I get null. I have called "**GlobalVariables.getInstance().setCallVariable("Login");**" and with **Log.e(TAG,"Value = " + CallingActivity);** inside setCallVariable() I see "Login" in the variable. But when I get the value, I get null. – John Stergiou Apr 11 '17 at 14:00
  • I set the value: **GlobalVariables.getInstance().setCallVariable("Login");** I get the value: **GlobalVariables mApp = new GlobalVariables(); String activity = mApp.getCallVariable();** Your solution gives error: java.lang.NullPointerException: Attempt to invoke virtual method 'android.app.ActivityThread$ApplicationThread android.app.ActivityThread.getApplicationThread()' on a null object reference – John Stergiou Apr 11 '17 at 14:13
  • You need to set and get the value using same object i.e :mApp. You are trying to set the value using GlobalVariables.getInstance().setCallVariable("Login") and getting the value using mApp.getCallVariable(); . These are creating two different objects. So you please try using same object for both setting and getting value – Sindhu Apr 11 '17 at 14:23
  • With my calling method and this: public String getCallVariable() { Log.e(TAG,"ret Value = " + this.CallingActivity); return this.CallingActivity; } public void setCallVariable(String Value) { this.CallingActivity = Value; Log.e(TAG,"set Value = " + this.CallingActivity); } I get: set Value = Login ret Value = null **The set Value and the get Value are not in the same function.** The variable passes from one Activity to another. – John Stergiou Apr 11 '17 at 14:26
  • Then try using SharedPreferences. When you set value , save the value using shared preferences and get the value from shared preferences. See the link: https://developer.android.com/reference/android/content/SharedPreferences.html – Sindhu Apr 11 '17 at 14:45
  • I solved the problem by passing mApp as parameter to the function. Now I have another problem. App crashes with: **startActivity(intent);** – John Stergiou Apr 11 '17 at 14:46
  • Did you add the activity that you are calling through intent in AndroidManifest.xml file – Sindhu Apr 11 '17 at 15:39