I'm using android studio for a project api 21 minimum,
I have an activity with a textfield and a button, when click, I want the text of the textfield stored for the life of the application, I'm using a global variable for that.
I've got a class variable that extends Application:
package com.example.user.variableglobale;
import android.app.Application;
public class Variable extends Application {
private String chiffre;
public String getChiffre() {
return this.chiffre;
}
public void setChiffre(String chiffre) {
this.chiffre = chiffre;
}
inside my main :
final Variable VG = (Variable) getApplication();
final TestVar tV = new TestVar();
btnOk.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
tV.testVar(MainActivity.this);
VG.setChiffre(String.valueOf(txt.getText()));
}
});
and here is the java class called with the button:
public class TestVar {
public void testVar(Context context) {
Variable VG = (Variable) context.getApplicationContext();
String temp = VG.getChiffre();
Toast.makeText(context.getApplicationContext(), "test java VG " + temp, Toast.LENGTH_SHORT).show();
}
}
Can anyone explain the way to use global variable inside java class?
When I click on the button, a toast appears with a "null" value for "temp" (seem to be not initialized).
In my example, I tried with "context", to no avail.
ok, finally it work,
inside my onclickListener i have to swap declaration of variable and calling of my class... everything ok
I think a better way to store that variable would be to store it in shared preferences. You can access it in any activity and it persists even if app is closed.
You can use it withoud needing a class for variable like this.
main:
static final String CHIFFRE_KEY = "chiffre_key";
final TestVar tV = new TestVar();
btnOk.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString(CHIFFRE_KEY, String.valueOf(txt.getText()));
editor.commit();
tV.testVar(MainActivity.this);
}
});
and testVar method would look like this
public void testVar(Context context) {
String vg = getActivity().getPreferences(Context.MODE_PRIVATE).getString(CHIFFRE_KEY);
Toast.makeText(context.getApplicationContext(), "test java VG " + vg, Toast.LENGTH_SHORT).show();
}
You can read more about Shared Preferences here
Related
I have the following problem, I am trying to call InterstitialLaunch.java from MainActivity.java to display Interstitial, however, in my case it reports an error from MainActivity.java and says that 'inter_launched (android.content.Context)' cannot be referenced from a static context.
What can be done about this problem and how to solve the problem, some idea, thanks.
InterstitialLaunch.java
public class InterstitialLaunch extends Activity {
public void inter_launched(Context mContext) {
SharedPreferences prefs = mContext.getSharedPreferences("interlaunch", 0);
SharedPreferences.Editor editor = prefs.edit();
// Increment launch counter
long launch_count = prefs.getLong("launch_count", 0) + 1;
editor.putLong("launch_count", launch_count);
// Get date of first launch
Long date_firstLaunch = prefs.getLong("date_firstlaunch", 0);
if (date_firstLaunch == 0) {
date_firstLaunch = System.currentTimeMillis();
editor.putLong("date_firstlaunch", date_firstLaunch);
}
// Wait at least n days before opening
if (launch_count >= LAUNCHES_UNTIL_PROMPT) {
if (System.currentTimeMillis() >= date_firstLaunch +
(DAYS_UNTIL_PROMPT * 24 * 60 * 60 * 1000)) {
interstitialLaunch(mContext, editor);
}
}
editor.apply();
}
public void interstitialLaunch(final Context mContext, final SharedPreferences.Editor editor) {
MobileAds.initialize(this, new OnInitializationCompleteListener() {
#Override
public void onInitializationComplete(InitializationStatus initializationStatus) {
Map<String, AdapterStatus> statusMap = initializationStatus.getAdapterStatusMap();
for (String adapterClass : statusMap.keySet()) {
AdapterStatus status = statusMap.get(adapterClass);
Log.d("MyApp", String.format(
"Adapter name: %s, Description: %s, Latency: %d",
adapterClass, status.getDescription(), status.getLatency()));
}
InterstitialAd.load(getApplicationContext(),
getString(R.string.interstitial_id),
new AdRequest.Builder().build(),
new InterstitialAdLoadCallback() {
#Override
public void onAdLoaded(#NonNull InterstitialAd interstitialAd) {
interstitialAd.show(InterstitialLaunch.this);
}
}
);
}
});
}
}
MainActivity.java
InterstitialLaunch.inter_launched(MainActivity.this);
Shows this error in MainActivity.java:
Non-static method 'inter_launched(android.content.Context)' cannot be referenced from a static context
In Java, something like ClassName.method() means invoking a static method.
Your inter_launched is not a static but a dynamic (instance) method because the method doesn't have static modifier.
If you would invoke an instance method, you must do something like instanceOfTheClass.method().
For example:
InterstitialLaunch interstitialLaunch = new InterstitialLaunch();
interstitialLaunch.inter_launched(MainActivity.this);
In order to call that inter_launched(Context) function from outside the class, you first need to instantiate the class.
This isn't a good example, because it isn't a good practice to create an instance of an activity, and then to call a function from it, from another class.
For your code to work, you can just override the onCreate function in the InterstitialLaunch Activity, and call the inter_launched(Context) inside it.
Now to create this activity, you just need to create an intent and start the activity. Here's an example:
Intent intent = new Intent(context, InterstitialLaunch.class)
startActivity(intent)
Let me know if it worked for you!
In order to learn java and android app building, I am creating an app that will store players’ scores (for a real card game for example). So the number of players is not fixed.
First, I have created a class “Player”, containing an id, a name and the score.
public class Player {
int idj;
String namej;
int scorej;
public Player(int idj, String namej, int scorej) {
this.idj = idj;
this.namej = namej;
this.scorej = scorej;
}
public int getIdj() {
return idj;
}
public void setIdj(int idj) {
this.idj = idj;
}
public String getNamej() {
return namej;
}
public void setNamej(String namej) {
this.namej = namej;
}
public int getScorej() {
return scorej;
}
public void setScorej(int scorej) {
this.scorej = scorej;
}
}
Then I would like to create a new player each time I click a button on the UI. Here is my button that call the “newPlayer” method on click:
Button bT1 = (Button) findViewById(R.id.bT1);
bT1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
newPlayer();
}
});
Here is the “newPlayer” method called by each button click. But this method doesn’t work. This method has to instanciate a player object and increment the reference variable name according to the “nbrPlayer” variable.
This var is counting the number of players :
public int nbrPlayer = 1;
And this is the "newPlayer" method :
private void newPlayer(){
player(nbrPlayer) = new Player(nbrPlayer,"var1FromEditText"," var2FromEditText ");
nbrPlayer ++;
}
Thanks for your help. (I am eventually looking for a good tutorial for that but for now I did not find one).
Each time when a new player hits the button, you should create instance of a player by passing id, name and score. Like this
Player newPlayer = new Player(nbrPlayer,"playerName",0);
But in your code you are not storing nbrPlayer value, so you cannot retrieve the value when that instance is dead. So you should store it in any storage to retrieve it back. I used shared preference to store that value. Check my code
private void newPlayer(){
SharedPreferences prefs = this.getSharedPreferences(
"MY_DATA", Context.MODE_PRIVATE);
int nbrPlayer = prefs.getInt("idj", 0);
if(nbrPlayer==0){
nbrPlayer = 1;
}
Player newPlayer = new Player(nbrPlayer,"playerName",0);
nbrPlayer ++;
SharedPreferences.Editor editor = getSharedPreferences("MY_DATA", MODE_PRIVATE).edit();
editor.putInt("idj", nbrPlayer);
editor.apply();
Log.d(TAG,"Player:"+nbrPlayer);
}
in your activty where you have the button you must have a counter
your code will be like this:
int counter = 1;
Button bT1 = (Button) findViewById(R.id.bT1);
bT1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
new Player(counter++,"var1FromEditText"," var2FromEditText ");
}
});
there is no reason to have a method newPlayer since you are not returing the player so it will die after creation.
your question is not clear where you are planning to show this players at all. so even in my solution the player is created in the button click but nothing happens with it...
you must add it to a list or set or show somewhere
I'm working with run time permissions and trying to make a method displaying permission rationale/s for taken permission/s and rationale/s
The problem is:
"Variable 'requiredPermissions' is accessed from within inner class, needs to be declared final"
That's how I call the method:
showRationale(R.string.permission_ACCESS_FINE_LOCATION_rationale, new String[]{Manifest.permission.ACCESS_FINE_LOCATION});
And that's the method:
private void showRationale(int rationale, String[] requiredPermissions) {
Snackbar.make(findViewById(R.id.myCoordinatorLayout), rationale, Snackbar.LENGTH_INDEFINITE)
.setAction(R.string.go_grant_permission, new View.OnClickListener() {
#Override
public void onClick(View view) {
// 'requiredPermissions' below causes the problem
ActivityCompat.requestPermissions(MapsActivity.this, requiredPermissions, MY_PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION);
}
})
.show();
}
You can realize onClick via interface, and not make this variable final.
What about this:
private void showRationale(int rationale, final String[] requiredPermissions) {
Snackbar.make(findViewById(R.id.myCoordinatorLayout), rationale, Snackbar.LENGTH_INDEFINITE)
.setAction(R.string.go_grant_permission, new View.OnClickListener() {
#Override
public void onClick(View view) {
// 'requiredPermissions' below causes the problem
ActivityCompat.requestPermissions(MapsActivity.this, requiredPermissions, MY_PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION);
}
})
.show();
}
The problem is that local variables (and method arguments) must be final to be accessed inside inner classes like your OnClickListener. So you should add a final keyword before a declaration of the argument. To do so, change this line
private void showRationale(int rationale, String[] requiredPermissions) {
to
private void showRationale(int rationale, final String[] requiredPermissions) {
Read more on this topic here.
this is my public class in android!
public class Logout {
public SharedPreferences pref;
public Logout(Context context){
pref = context.getSharedPreferences(LoginActivity.loginpreferences, context.MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.remove(LoginActivity.name_user);
editor.remove(LoginActivity.type_user);
editor.remove(LoginActivity.id_user);
editor.commit();
}
}
to call class when clicking button (logout) I wrote the code in the following way
private OnClickListener clickitempanel = new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
int id = v.getId();
switch(id){
case 4:
Logout logout = new Logout(mContext);
// logout.notifyAll();
logout.getClass();
Intent in = new Intent();
in.setClass(mContext, FullscreenActivity.class);
mContext.startActivity(in);
break;
}
}
};
textViewItem.setOnClickListener(clickitempanel);
but doesn't running code remove keys from SharedPreferences !
Do you have a listener on that button? Are you sure it is working ?
Also, you people would normally put that logout code in a method instead of in the constructor.
Hint:
Remember to make as less as it is is possible in body of Constructor. Init your variables and avoid call any methods. Only methods which you could call in Constructor are final methods (private method also should be with final statement).
I'm trying to pass something from one class to my MainActivity, but it doesn't seem to work, I don't understand why.
I have my GPS Tracker on another class (not the MainActivity) in order to reuse it.
When the location changes, I want my other class to call a method from within the MainActivity to update my UI.
I summarized my code like that :
My MAIN ACTIVITY :
public class MainActivity extends Activity implements OnClickListener {
TextView tv;
EditText et;
Button btun;
int arg0;
int stuff;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView) findViewById(R.id.tv);
et = (EditText) findViewById(R.id.et);
btun = (Button) findViewById(R.id.btun);
btun.setOnClickListener(this);
}
private void setter(int stuff) {
tv.setText(stuff);
}
public void setText(int _stuff) {
_stuff = stuff;
setter(_stuff);
}
#Override
public void onClick(View v) {
Getter get = new Getter();
get.getInfo(Integer.parseInt(et.getText().toString()));
}
The other Class :
public class Getter {
int _getString;
MainActivity main = new MainActivity();
public void getInfo(int getString) {
_getString = getString * 8;
main.setText(_getString);
}
}
I end up having a NullPointerException in my LogCat
at :
- tv.setText(stuff);
- setter(_stuff);
- main.setText(_getString);
- get.getInfo(Integer.parseInt(et.getText().toString()));
and I don't really know why, and above all, how to fix it.
I'll appreciate any help !
(PS : My GPS tracker thingy is working fine, it's just about invoking my setter() method.
Instantiaing an Object of MainActivity doesn't automatically call onCreate method but this method is called when you start an activity using Intent; And using the same intent you can pass extra values. For example:
Intent intent = new Intent(context, MainActivity.class);
intent.putExtra("key", value);
context.startActivity(intent);
and then in your main activity onCreate method:
String value = getIntent.getStringExtra("key");
Edit:
In your case why don't you change your void getInfo(int getString) to return a String value i.e.
public class Getter {
...
...
public String getInfo(int getString) {
_getString = getString * 8;
return Integer.toString(_getString);
}
}
and then in onClick event of MainActivity bind this returned text to TextView
It's maybe because the MainActivity's onCreate()-Method hasn't been called. Therefore the tv is still null causing the NullPointerException
One problem is here. main is an Activity, but it should be the MainActivity calling this object.
public class Getter {
int _getString;
MainActivity main = new MainActivity();
public void getInfo(int getString) {
_getString = getString * 8;
main.setText(_getString);
}
}
I cannot really make out what you are trying to achieve in the Getter class, but either:
1: Pass the Activity instance to the object
public class Getter {
int _getString;
MainActivity _main = null;
public Getter(MainActivity main) {
_main = main;
}
public void getInfo(int getString) {
_getString = getString * 8;
_main.setText(_getString);
}
}
#Override
public void onClick(View v) {
Getter get = new Getter(this);
get.getInfo(Integer.parseInt(et.getText().toString()));
}
or
2: set the text in the Activity and only get the value from the Getter (My choice)
public class Getter {
int _getString;
MainActivity main = new MainActivity();
public void getInfo(int getString) {
return getString * 8;
}
}
#Override
public void onClick(View v) {
Getter get = new Getter();
int info = get.getInfo(Integer.parseInt(et.getText().toString()));
setText(Integer.toString(info));
}
Use Application Class or create a separate Class and declare a static variable in it. Use getter & setter methods to get the value. To update the Textview in mainacivity from other class pass the texview reference variable from main activity and put null check condition in other class if textview is not null then update the value.