Making use of getActivity() in a static method - java

public class QRProductActivityPageObject {
public static void testProductDetail() throws InterruptedException {
ActivityTestRule<ProductInfoActivity> rule = new ActivityTestRule<ProductInfoActivity>(ProductInfoActivity.class, true, false);
Intent intent = new Intent();
intent.setClass(getActivity(), ProductInfoActivity.class);
rule.launchActivity(intent);
Thread.sleep(2000);
}
}
The above syntax show error that you cant access getActivity() in static method .
But i want to call this new Activity(ProductInfoActivity) through static method only.Any suggestion??

Pass context when method call in Activity or fragment and get Activity from context in static method
public static void testProductDetail(Context context) throws InterruptedException {
ActivityTestRule<ProductInfoActivity> rule = new ActivityTestRule<ProductInfoActivity>(ProductInfoActivity.class, true, false);
Intent intent = new Intent();
Activity activity = (Activity) context;
intent.setClass(activity , ProductInfoActivity.class);
rule.launchActivity(intent);
Thread.sleep(2000);
}
Call static method In activity
testProductDetail(getApplicationContext());
In fragment
testProductDetail(getActivity().getApplicationContext());

Or use the solution I found around here a few weeks ago, it's pretty awesome and elegant. You'd be able to use it anywhere in your APP!
Create a class MyApplication (you could name it differently):
public class MyApplication extends Application {
private static Context context;
public void onCreate() {
super.onCreate();
MyApplication.context = getApplicationContext();
}
public static Context getAppContext() {
return MyApplication.context;
}
}
Go to your app Manifest file and add to the <application... tag the android:name attribute with the value of the name of the class we created:
<application
android:allowBackup="true"
android:icon="#drawable/appico"
android:label="#string/app_name"
android:name="MyApplication"
Now you can get the context for your app from any class like that
MyApplication.getAppContext();

You don't need to call getActivity(). Instead of using setClass() method which requires you to give a context object, you can use setClassName(String packageName, String className) method. Try this:
Intent intent = new Intent();
intent.setClassName("package.name.of.your.app",
ProductInfoActivity.class.getName());

Related

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.

setResult not working in a java class implementing onClickListener

In my project I have some buttons, with their own View.OnClickListener.
What I want is to "externalize" all this onClickListener into a java calss that implements the interface, and handle all the click events, here.
But I found a problem, that I don't know how to fix it.
One of the buttons launch a setResult(RESULT_OK, startChatIntent) and finish(), but thismethods inside the class, are marked as: Cannot be resolved as method.
This is the class : (I take out the other buttons functionalities, that works OK, to make it more clear)
public class startCircuitListener implements View.OnClickListener {
private int mChatType;
private String mGroupName;
private String mNickName;
private String mMessage;
private ArrayList<String> mGroupEmails;
private Context context;
public startCircuitListener(int mChatType, String mGroupName, String mNickName, String mMessage, ArrayList<String> mGroupEmails, Context context) {
this.mChatType = mChatType;
this.mGroupName = mGroupName;
this.mNickName = mNickName;
this.mMessage = mMessage;
this.mGroupEmails = mGroupEmails;
this.context = context;
}
#Override
public void onClick(View v) {
Intent startChatIntent = new Intent();
startChatIntent.putExtra("chatRoom", mGroupName);
startChatIntent.putExtra("chatServer", HelperVariables.CONFERENCE_SERVER_NAME);
startChatIntent.putExtra("nickname", mNickName);
startChatIntent.putExtra("Individual_Group", 0);
startChatIntent.putExtra("MessageToSend", mMessage);
startChatIntent.putExtra("Invitations", mGroupEmails);
setResult(RESULT_OK, startChatIntent);
finish();
}
}
How can I make work setResult and finish()?
You have to create your listener instance with the current Activity instance, and store it as a member of startCircuitListener.
Then call this.myActivity.setResult(RESULT_OK, startChatIntent);. Same thing for finish();

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

startActivity from a custom class

I have a menu and 5 activities. To avoid repeating the menu code, I have created a public class and call it in every activity:
Testclass testclass = new Testclass(Main.this);
...but unfortunately I can't use startActivity() in the class. This is my class code:
public class Testclass extends Activity {
public Testclass(Activity cc) {
Intent intent = new Intent(cc,Next.class);
startActivity(intent);
}
}
Try this and tell me if it helped you.
public class Testclass extends Activity {
public Testclass(Activity cc) {
final Context context = Testclass.this.getContext();
Intent intent = new Intent(context , Next.class);
context.startActivity(intent);
}
}
You misunderstood the concept of an Activity and its life cycle. You DON'T instantiate the Activity, the Activity has callback mechanisms (onCreate, onResume, etc.) that tell you exactly what to do. You never ever have to call new Activity().
The fact that you're doing
Testclass testclass = new Testclass(Main.this); shows that you have a misunderstanding of this concept: http://developer.android.com/training/basics/activity-lifecycle/index.html
To fix your error, read the docs and then it will be clear what is wrong with your approach.
Hint: Your Testclass already IS an Activity, because you inherit from Activity.
And next time please provide the whole error log to your problem, so it can give the whole picture of what can be wrong with your code.
Why not use this code?
startActivity(new Intent(Main.this, Next.class));
// "Main" is your current Activity
// "Next" is your next Activity to be opened.
I think, it's very simple to use without create a new public class. Please compare your codes with my code above, only one line.
I think you don't use the correct Context to start the Intent.
Instead try
{
public Testclass() {
Intent intent = new Intent(this,Next.class);
startActivity(intent);
}
}
if the this doesn't work either, try getApplicationContext() instead.
#you can used Weak Reference Objects to store Context of Activity class#
##in activity class##
public class Activity extends AppCompatActivity implements View.OnClickListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view);
findViewById(R.id.toNext).setOnClickListener(this);
}
#Override
public void onClick(View v) {
Testclass thread = new Testclass(Activity.this,v);
new Thread(thread).start();
}
}
}
// in sub class
public class Testclass extends Activity implements Runnable {
View landingPage;
private Activity activity;
public Testclass (Activity activity, View landingPage){
WeakReference<Activity> ActivityWeakReference = new WeakReference<>(Activity);
this.landingPage = landingPage;
this.activity = activityWeakReference.get();
}
#Override
public void run() {
Intent activityIntent = new Intent(activity, Next.class);
activityIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
runOnUiThread(new Runnable() {
#Override
public void run() {
switch (landingPage.getId())
{
case R.id.Next.class:
activity.finish();
activity.startActivity(activityIntent);
break;
}
}
});
}
}

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

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.

Categories