Cannot be referenced from a static context - java

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!

Related

Using a global Variable inside a class

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

onResume() getting called on pressing back arrow. Please see details

I have a method in onResume() which fetches user's data and should get called when user launch the app. This is working fine.
The problem is that for example after opening 'Settings' when I tap/click on the back arrow, the method in onResume() gets called again and user data starts getting fetched again.
What I want is, I want that method to get called only when user launches the app and not every time the user transition back from settings to main activity.
Here's the onResume() in MainActivity.java:
#Override
protected void onResume() {
super.onResume();
fetchUserData();
}
Here's how I transition to Settings.java:
Intent settingsIntent = new Intent(MainActivity.this, SettingsActivity.class);
startActivity(settingsIntent);
Please let me how can I restrict the fetchUserData() to get called only when user launches the app and not again when user transition back to main activity from any other activity by tapping/clicking on back arrow.
Sorry, if question seems to be badly formatted. I'm still a beginner here.
if you want the method to be called only once when the activity opens move it inside OnCreate() method.OnResume() can be called several times.You can see the documentation of acttivity lifecycle here
You could adapt the following code, by setting a flag/indicator so that only wanted returns are processed (eg set resume_state to RESUMESTATE_NOTHING except when starting an intent after which you want to fetchUserData:-
public class AisleListByCursorActivity extends AppCompatActivity {
public final static int RESUMESTATE_NOTHING = 0;
public final static int RESUMESTATE_AISLEADD = 1;
public final static int RESUMESTATE_AISLESTOCK = 2;
public final static int RESUMESTATE_AISLEDELETE =3;
public final static int RESUMESTATE_AISLEUPDATE = 4;
public int resume_state = RESUMESTATE_NOTHING;
public ShopsCursorAdapter currentsca;
public AislesCursorAdapter currentaca;
public ShopListSpinnerAdapter currentslspa;
public long currentshopid;
private final static String THIS_ACTIVITY = "AisleListByCursorActivity";
private final ShopperDBHelper shopperdb = new ShopperDBHelper(this,null, null, 1);
private ListView aisleslistview;
private Cursor csr;
private int shopid = 0;
protected void onResume() {
super.onResume();
switch (resume_state) {
case RESUMESTATE_AISLEADD:case RESUMESTATE_AISLEUPDATE: {
Cursor csr = shopperdb.getAislesPerShopAsCursor(currentshopid);
currentaca.swapCursor(csr);
resume_state = RESUMESTATE_NOTHING;
break;
}
default: {
resume_state = RESUMESTATE_NOTHING;
}
}
}
........
public void aalbcadd(View view) {
resume_state = RESUMESTATE_AISLEADD;
Intent intent = new Intent(this,AisleAddActivity.class);
intent.putExtra("Caller",THIS_ACTIVITY);
intent.putExtra("SHOPID", currentshopid);
startActivity(intent);
}
Create method in OnStart() or onCreate() rather than onResume(). for reference - please see this link for better understanding of Android LifeCycle http://developer.android.com/reference/android/app/Activity.html
If you want your method to be called only once you must put that method in onCreate method of Activity. Because onResume is always called you come back to the activity as per Android lifecycle. So just replace you method fetchUserData(); into onCreate like below:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_app_list);
fetchUserData();
}
#Override
protected void onResume() {
super.onResume();
}

How to call one method from another class in Android

When ever im calling fromcheckpass(mcontext) im getting nullpointerexception. Where imdoing wrong. Help me out!
From onClick() i'm calling fromcheckpass(mcontext).
public void onClick(View v) {
InboxActivity inboxActivity = new InboxActivity();
inboxActivity.fromcheckpass(CheckPass.this);
}
How can I call fromcheckpass(mcontext) method ?
public void fromcheckpass(Context mcontext) {
Toast.makeText(mcontext, "WEL COME", Toast.LENGTH_LONG).show();
Db = new MySQLiteHelper(this);
String DbInsert = Utils.getPreferences("DbInsert", this);
if (!DbInsert.equalsIgnoreCase("Inserted")) {
SaveDataInDB();
}
MessageListView = (ListView) findViewById(R.id.lvInbox);
ActionBar bar = getActionBar();
bar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#0154A4")));
bar.setTitle(R.string.app_name);
bar.setTitle(Html.fromHtml("<font color='#ffffff'>WeText </font>"));
bar.setIcon(R.drawable.icon_top);
Utils.getOverflowMenu(this);
attachListeners();
dataList = Utils.getLatestMessageOfAllContacts(InboxActivity.this);
if (dataList.isEmpty()) {
Toast.makeText(getApplicationContext(), "NO MESSAGES", Toast.LENGTH_LONG).show();
} else {
iAdapter = new Adapter(InboxActivity.this, dataList);
MessageListView.setAdapter(iAdapter);
}
}
Whenever I call fromCheckpass(mcontex) method the app crashes. Here is my logcat:
Process: com.futureappspk.WeTextFree, PID: 29065
java.lang.NullPointerException
at android.content.ContextWrapper.getSharedPreferences(ContextWrapper.java:186)
at android.preference.PreferenceManager.getDefaultSharedPreferences(PreferenceManager.java:369)
at com.futureappspk.WeTextFree.Utils.getPreferences(Utils.java:432)
at com.futureappspk.WeTextFree.InboxActivity.fromcheckpass(InboxActivity.java:130)
at com.futureappspk.WeTextFree.CheckPass$1.onClick(CheckPass.java:40)
Here is my util class method which is calling fromcheckpass(mcontext)
public static String getPreferences(String key, Context context) {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
String userName = sharedPreferences.getString(key, "UserName");
return userName;
}
Please try This
I think your CheckPass is not your Activity.
Hence pass Context correctly like
getActivity() or getApplicationContext();
in onClick Method
Hope it helps
To inform you the error is at this line
String DbInsert = Utils.getPreferences("DbInsert", this);
Possible reasons
You have to use getSharedPreferences with the instance of Context class like
ctx.getSharedPreferences("MY_PREF",0);
You have not shown your Utils class but as I guess getPreferences method is a static method of the class and you are calling it directly without initializing any Context of application. So I suggest you to initialize the Context in the Constructor of your Utils class and use the getSharedPreferences method only with the instance of Utils class.
UPDATE
Try not to make it static, do something like this
public class Utils {
private SharedPreferences sharedPreferences;
public Utils (Context context) {
this.sharedPreferences = getPreferences(MODE_PRIVATE);
}
public String getPreferences(String key) {
sharedPreferences.getString(key, "UserName");
return userName;
}
}

How to call public class in android java

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).

Passing string from class to main activity

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.

Categories