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;
}
}
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!
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
I have a value in an activity class. I want to use that value in a non activity class. Normally, to share data between activity classes, I use like,
FirstActivityClass.java
SharedPreferences notification_id = getSharedPreferences("NOTIFICATION_ID", MODE_PRIVATE);
SharedPreferences.Editor notificationIDEditor = notification_id.edit();
notificationIDEditor.putString("notification_id", notificationId)
notificationIDEditor.apply();
And to retrieve the value of notification_id in another class,
SecondActivityClass.java
SharedPreferences notificationIDSharedRetrieve = getSharedPreferences("NOTIFICATION_ID", MODE_PRIVATE);
notificationID = notificationIDSharedRetrieve .getString("notification_id", null);
But suppose the second class was a non-activity class, how can I retrieve the data in a non-activity class?
you can send your Activity context to your calss by creating a custom constructor for example:
class A
{
Context con;
public A(Context con)
{
this.con=con
}
}
Activity B
{
Context con;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.con=getContext();
A = new A(this.con);
}
}
You can cache the global Application context.
myApplicationContext.getSharedPreferences(NOTIFICATION_ID", MODE_PRIVATE)
I have a Activity class from where I am passing some information to a helper class(Non-activity) class. In the helper class I want to use the getSharedPreferences(). But I am unable to use it as it requires the activity context.
here is my code:
class myActivity extends Activity
{
#Override
protected void onCreate(Bundle savedInstanceState)
{
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.home);
Info = new Authenticate().execute(ContentString).get();
ItemsStore.SetItems(Info);
}
}
class ItemsStore
{
public void SetItems(Information info)
{
SharedPreferences localSettings = mContext.getSharedPreferences("FileName", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = localSettings.edit();
editor.putString("Url", info.Url);
editor.putString("Email", info.Email);
}
}
ANy idea how this can be achieved?
Instead of creating memory leaks (by holding activity context in a class field) you can try this solution because shared preferences do not need activity context but ... any context :) For long living objects you should use ApplicationContext.
Create the application class:
public class MySuperAppApplication extends Application {
private static Application instance;
#Override
public void onCreate() {
super.onCreate();
instance = this;
}
public static Context getContext() {
return instance.getApplicationContext();
}
}
Register it at manifest
<application
...
android:name=".MySuperAppApplication" >
...
</application>
Then you can do something like this
public void persistItems(Information info) {
Context context = MySuperAppApplication.getContext();
SharedPreferences sharedPreferences = context.getSharedPreferences("urlPersistencePreferences", Context.MODE_PRIVATE);
sharedPreferences.edit()
.putString("Url", info.Url)
.putString("Email", info.Email);
}
Method signature looks better this way because it does not need external context. This can be hide under some interface. You can also use it easily for dependency injection.
HTH
Try this:
class myActivity extends Activity
{
#Override
protected void onCreate(Bundle savedInstanceState)
{
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.home);
Info = new Authenticate().execute(ContentString).get();
ItemsStore.SetItems(Info, getApplicationContext());
}
}
class ItemsStore
{
public void SetItems(Information info, Context mContext)
{
SharedPreferences localSettings = mContext.getSharedPreferences("FileName",
Context.MODE_PRIVATE);
SharedPreferences.Editor editor = localSettings.edit();
editor.putString("Url", info.Url);
editor.putString("Email", info.Email);
}
}
You need to pass the context to the constructor of non activity class
ItemsStore itemstore = new ItemStore(myActivity.this);
itemstore.SetItems(Info);
Then
Context mContext;
public ItemsStore (Context context)
{
mContext =context;
}
Now mContext can be used as Activity Context.
Note: Do not keep long-lived references to a context-activity (a reference to an activity should have the same life cycle as the activity itself)
Write a public function in your activity. While creating an instance of your helper class in Activity class, pass the context of activity in constructor.
Then from your helper class, using the activity context, call the public function in activity class.
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.