How to get activity context into a non-activity class android? - java

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.

Related

FindViewById in a non activity class

How can I use findViewById() in a non activity class. Below is my code snippet. I get the error message: "can't resolve method findViewById" if used directly. And if i try to use the class constructor (Where the imageView is available) i get this error "cannot resolve symbol context"
public class MyBroadcastReceiver extends FirstBroadcastReceiver {
Activity activity;
public MyBroadcastReceiver(Context context, Activity activity){
this.context=context; // error here(cannot resolve symbol context)
this.activity=activity;
}
#Override
protected void (Context context) {
// content
}
#Override
public void onButton(Context context, boolean isClick) {
if(isClick) {
ImageView blueImage = (ImageView)activity.findViewById(R.id.imageView);
blueImage.setColorFilter(0xff000000);
}
}
.......
....
// and so on
And below is my MainActivity with MybroadcastReceiver class instance.Is it correct?
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// and so on
}
}
MyBroadcastReceiver myBroadcastReceiver = new MyBroadcastReceiver(MainActivity.this,this);
#Override
public void onActivityResult() {
// some code
}
#Override
public void onInitialized(MyManager manager){
// some code
}
A BroacastReceiver runs entirely in the background, listening for Intents sent either by the OS or other apps. It is not responsible for any UI interactions, and cannot access any views. Therefore, findViewById cannot be used within a BroadcastReceiver.
See also - What is BroadcastReceiver and when we use it?
You have to pass View to the non activity class, before using findViewByid
and
try using
view.findViewByid(R.id.view_id);
Because context is null in Broadcast class. use Broadcast class constructor to pass parent_activity(Where the imageView is available) context in Broadcast to access the context:
public class Broadcast extends BroadCastReceiver {
Activity activity;
public Broadcast(Context context,Activity activity){
this.context=context;
this.activity=activity;
}
.......
....... //so on
and in parent_activity create Broadcast class instance by passing parent_activity context as:
Broadcast broadcast = new Broadcast(parent_activity.this,this);
Use activity instance as:
#Override
public void onButton(Context context, boolean isClick) {
if(isClick) {
ImageView blueImage = (ImageView) activity.findViewById(R.id.imageView); //<--- here
}
}
.........
......... //so on

How to retrieve shared preferences into a non-activity class from an activity class in Android?

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)

Which is a better way to code getActivity() , getApplicationContext()?

i'm not asking diffrence, but how to use these referenes?, Class level object to store their reference or use getter everytime which is provided by super class, Which is a better code practice: 1. call getActivity(), getApplicationContext() ..etc everytime in a local method or pass method as parameter when required in an activity or fragment.
Store their reference in a class level object and use it whereever it's required with null check in an activity or fragment.
I would like to know what is more efficient and why?
type1:
Class A extends Activity
{
#Override
public void onCreate()
{
methodA(getApplicationContext());
//or if fragment
methodA(getActivity());
Toast.makeText(getApplicationContext(),...).show();
}
private void methodA(Context mContext)
{
......
......
}
private void methodA()
{
Activity activity = getActivity();
......
......
}
}
type2:
class A extends Activity{
private Activity mContext;
private Activity mActRef; //if fragment
#Override
public void onCreate()
{
mContext = getApplicationContext();
mActRef = getActivity();//if fragment;
methodA(mContext);
//or if fragment
methodA(mActRef);
..........
.........
.........
Toast.makeText(mContext,...).show();
}
private void methodA(Context mContext)
{
......
......
}
private void methodA()
{
Toast.makeText(mContext,....).show();
}
}
}
getActivity() and getApplicationContext() both return the context and available throughout the class extend with Activity.
According to my opinion No need to create a global variable for them because they are available at class level. Both are correct but storing the context is not efficient.

How to use classes that extends Activity in Android?

I am new to Android programming.
Basically what I want to do is write a class that extends Activity and then use it in another class that also extends Activity.
In my case what I wanted to do was to be able use GsmCellLocation class members without having to initialise TelephonyManager.
So I created a class named as CellInformation and here is the content:
public class CellInformation extends Activity {
private TelephonyManager tm;
private GsmCellLocation cellLoc;
public CellInformation() {
tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
cellLoc = (GsmCellLocation) tm.getCellLocation();
}
public GsmCellLocation updateCellInfo() {
cellLoc = (GsmCellLocation) tm.getCellLocation();
return cellLoc;
}
public int getCid() {
return (cellLoc.getCid()%65536);
}
public int getLac() {
return cellLoc.getLac();
}
public int getPsc() {
return cellLoc.getPsc();
}
}
and within my main activity this is how I initialise it:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
cell = new CellInformation();
}
I am getting System services not available to Activities before onCreate() error. If I was not meant to initialise it within onCreate, then where should I initialise it?
If my logic is completely wrong and/or this is not Android standard, how can I fix it?
Simply Don't extend the Activity until it is required. I saw the class CellInformation where Activity class not required. Remove it and it will solve your problem.
public class CellInformation {
..... // Method and Attributes.
private Context context;
CellInformation(Context context) {
this.context = context;
tm = (TelephonyManager)this.context.getSystemService(Context.TELEPHONY_SERVICE);
}
}
In Activity make the object of this class like :-
cell = new CellInformation(this);
Now, Make the object of this class in the activity where your require then call the method of this CellInformation.

How to pass (Android) application context to a Java class?

I have the following code in which I am using the application context to retrieve needed information:
public class Data{
private boolean VarA;
public void setVarA(boolean B,Context ctx)
{
SharedPreferences CoreDataStorage = ctx.getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = CoreDataStorage.edit();
editor.putBoolean("PrefVarA", VarA);
edit.commit();
}
}
Now I am calling the public method setVarA() from the below class
public class MyActivity extends Activity{
Data cd = new Data();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.registration);
cd.setVarA(true,this);
}
}
In the activity above it shows me compilation error that it can't cast from MyActivity to Context. Please suggest any solution. Is the above code is not proper way to pass the context?
You need the application Context to access the shared preferences. It should be:
cd.setVarA(true,this.getApplicationContext());
in the onCreate of MyActivity.

Categories