Duplicate method to log out - android

I'm a beginner and I have (I think) a simple question for you. I have a method used in every Activity except LoginActivity. It's opened when I click on the shutdown icon. This is code ->
public void logOut(MenuItem item) {
Intent intent = new Intent("THIS_CLASS".this, LoginActivity.class);
startActivity(intent);
}
but I do not want to duplicate it in every Activity, may exist any solution ? I am writing here because I can't find a solution on the Web. The problem is that I can not express my intentions in the question on the Internet. Every "duplicate method" gives answers not on the subject. I am not looking for complete code. I prefer only prompt.

Firstly, create a help class and add a static method like this:
import android.content.Context;
import android.content.Intent;
public class MyHelper {
public static void startActivityB(Context context) {
Intent intent = new Intent(context, LoginActivity.class);
context.startActivity(intent);
}
}
Then call the method and pass correct context like below:
findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
MyHelper.startActivityB(YourActivity.this);
}
});
Note: if MyHelper, LoginActivity,YourActivity are not in a same package, you should import corresponding package, that is an easy job.

It's not the best solution, but if you want a bunch of activities to share the same methods, then create a BaseActivity that they all extend from.
public abstract class BaseActivity extends Activity {
//... Shared stuff
protected void logOut() {
//Do some data cleaning and whatever else you need
Intent intent = new Intent(getApplicationContext(), LoginActivity.class);
startActivity(intent);
}
}
public class MyActivity extends BaseActivity {
//... Main code
private void onLogOutClicked() {
logout();
}
}
Just make sure you clean out your authentication/session data when this occurs. Try to utilise inheritance for shared functionality.

Related

How to call an activity in Application Class and waiting until it finishes

I would like to inject an activity before the main activiy shows up. I added the following code in OnCreate method in the application class
[Application]
public class XYZ: Application
{
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
Intent intent = new Intent(this, typeof(SplashActivity));
intent.AddFlags(ActivityFlags.NewTask);
StartActivity(intent);
// rest code.. but I dont want it is excuded until my splashactivity
closed
}
}
I cannot find startActivityForResult method in the application class so after StartActivity, the code still is executed that I do not want.
How can make it stop there and wait until splashscreen is closed.
I am not inderested in doing Splasscreen as a mainlauncher. I just want to inject it with another reasons and there is no another way for me.
Note: its for xamarin but java code is also fine.
We can do it for example by interface:
// our app class
public class MyApplication extends Application implements IComplete {
#Override
public void onCreate() {
super.onCreate();
Intent intent = new Intent(this, Main2Activity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
// rest code.. but I dont want it is excuded until my splashactivity
}
#Override
public void notify(boolean result) {
// do the rest code part here ...
}
}
// the interface
public interface IComplete {
void notify(boolean result);
}
// and the interface calling code snipped in the SplashActivity
#Override
public void onBackPressed() {
super.onBackPressed();
((MyApplication)getApplication()).notify(true);
}
hope helps you,
Good luck )

android get activity context in abstract base class

I am creating an abstract base class to keep my navigation drawer code in one place and want to implement an onClickListener on my app title (defined in the toolbar) to start my launch activity
I am using the following code :
#Override
public void onClick(View view) {
switch (view.getId()){
case R.id.toolbar_title:
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
return;
}
}
The app works properly, but I read somewhere that one must not use the Application context to start new activities. However, android studio doesn't let me use any other context apart from getApplicationContext and getBaseContext, maybe because this class is abstract.
Which context should I use then?
Have a look at Context.getApplicationContext() and ContextWrapper.getBaseContext(). Both have in common to be defined on a context instance. In your case it's even an Activity.
So you could even use this as a context to start your MainActivity. This is even better, because with any other context type you' have to include the flag FLAG_ACTIVITY_NEW_TASK to start a new activity.
If you get errors by using this for a context, it's because you define your OnClickListener as anonymous inner class which of course isn't a context. For that you'd have to write MyBaseActivity.this instead. This references the outer class instance.
Well, one of the ways can be: You can define an abstract method in your BaseActivity class:
abstract void launchMainActivity();
And call this method in your click listener:
#Override
public void onClick(View view) {
switch (view.getId()){
case R.id.toolbar_title:
launchMainActivity();
return;
}
}
The sub-classes can then implement this method as:
#Override
void launchMainActivity() {
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
}

Changing activity in android clears the memory needed for the previous activities?

I am developing a multi level game, where each level is a new activity.
I want to know, if i change the activity like
Intent myIntent = new Intent(getBaseContext(), Level3.class);
startActivity(myIntent);
The memory used for Level 1 and 2 is cleared?
If not, how can I clear everything from previous level activities so the phone uses just the memory just for the current activity ?
You need to call finish() for the activity (or activities) that you no longer want to be active. You can simply call it right after starting the new activity:
Intent myIntent = new Intent(getBaseContext(), Level3.class);
startActivity(myIntent);
finish();
Otherwise, the previous activity will remain on the activity stack.
since you are using an activity/level design, just add a check if your activity is finishing in your onPause method, and null all your references to the current level, that way the GC will know that your level object should be released, and it will release it as soon as possible.
#Override
public void onPause(){
super.onPause();
if (isFinishing()){
levelObject = null;
}
}
I would not recommend you to create Activity for each of your game level. Would be better to create some Controller that will initializate you game levels in one Activity. And of cource it must have some methods to clear memmory from last stage, something like this :
class StageManager
{
public Stage curStage;
public initStage(Stage stage)
{
//init stage here
curStage = stage;
stage.init();
}
public clearStage()
{
//do some clearing staff
curStage .clear();
}
}
abstract class Stage
{
public abstract init();
public abstract clear();
}
abstract class FirstStage extends Stage
{
//....
}
abstract class SecondStage extends Stage
{
//....
}
In Activity :
StageManager stageManager = new StageManager();
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.your_view);
stageManager.init(new FirstStage());
}
#Override
public void onClick(View theView)
{
int id = theView.getId();
if (id == R.id.btnNextLevel) {
stageManager.clear();
stageManager.init(new SecondStage());
}
}
Instead of your custom manager, you can use fragmets :
http://developer.android.com/training/basics/fragments/creating.html
http://developer.android.com/training/basics/fragments/fragment-ui.html
In both ways - fragments or yout own manager you will seperate different stages logic to different classes.
Youd don't need to create another Activity to seperate yours 1000+ lines code. Just use one of Stage or Stratagy desing patters.
And if you still want to use Activities just do something like this :
Intent myIntent = new Intent(getBaseContext(), Level3.class);
startActivity(myIntent);
finish();
and in onDestroy() :
#Override
protected void onDestroy()
{
//here you must clear all data that were used in this Stage (Activity) like this :
clearMemmory();
super.onDestroy();
}
private void clearMemmory()
{
if(stageData!=null)
{
stageData.clear();
stageData =null;
}
}
or clear memmory directly before opening another Stage, something like :
clearMemmory();
Intent myIntent = new Intent(getBaseContext(), Level3.class);
startActivity(myIntent);
finish();
Best wishes.

Error while using PackageManager in Android

I got a problem in one Android Application which I am working in which I am getting error when I use PackageManager.
The Application is as follows:
Home.java
package com.main.home;
public class Home extends Activity
{
//onclicking a Button say "send"
send.onClickListener()
{
public void onClick() {
Intent i =new Intent();
i.setClassName("com.main.home", "com.main.home.home1");
startActivity(i);
}
}
Home1.java
package com.main.home;
import com.andr.resulting.Result ;
public class Home1 extends Activity {
EditText et=(EditText)findViewById(R.id.e1);
//Clicking on forwardButton in that onClick()
public void onClick()
{
String s[] = {e1.getText().toString(),""};
//Calling a method in a class Result of another package which is not activity
Result.finalfunc(Home1.this,s);
}
Result.java
package com.andr.resulting; //different package
public class Result {
public static void finalfunc(Activity act,String[] re) ...
//Here I want to get the details of this particular class's package (com.andr.resulting) using PackageManager
// I tried like this:
Result.this.getPackageManager().getApplicationInfo(Result.getPackageName(),0))
I am getting error getPackageManager() does not exists in this class file.
How do I solve this issue? I will be eagerly waiting for valuable reply.
Thanks in Advance.
try this::
this.getPackageManager().getApplicationInfo(this.getPackageName(), 0);
Result doesn't extend Context like your Activity class does. So the method isn't available in that class. You need to call act.getPackageManager() inside there instead of this.getPackageManager().

New Activity nullpointerexception

I have a beginners problem. Here is my situation:
I want to start a new activity from the main activity. The code to launch the new activity is found in a separate class file. I seem to be passing the wrong arguments and I am ending up in a nullpointerexception when trying to launch the new activity. The new activity launches fine when I place the code in the main activity class file, therefore the second activity and the manifest are fine. Here is a sample of my code:
In my main activity class where I instanciate the second class (THIS IS MY MAIN ACTIVITY. I OMITTED THE REST BECAUSE I DO NOT THINK IT IS RELATED TO THE PROBLEM):
Tester mytest = new Tester();
mytest.test(this);
In my second class file (THIS IS NOT AN ACTIVITY; IT IS A CLASS THAT IS INSTANTIATED IN THE ACTIVITY):
public class Tester extends Activity {
Intent myIntent;
public void test (Context context) {
myIntent = new Intent (Intent.ACTION_VIEW);
myIntent.setClass(context, newActivity.class);
thebutton.setOnClickListener(
new OnClickListener() {
public void onClick(View v) {
startActivity(myIntent);
}
}
):}
When I perform the click I receive a nullpointerexception at startactivity. Can anyone enlighten me on this please?I am sure that I am wrongly using the context.
Activities are started with Intents. Please read the Android Application Fundamentals first and try the Hello World app :)
I understood that you will use your separate Tester class at all cost ;) so I'm trying to adapt and help you out there.
First of all, don't let your class inherit from Activity. This won't help you, cause this calls will probably not have any valid context. Activity somehow implements the template pattern, providing you key method like onCreate(...), onPause(...) etc and is instantiated by the Android OS.
If you still want to use the class, you have to pass in the context. Probably you're aiming for some MVC/MVP pattern structure, anyway.
public class Tester {
private Context context;
public Tester(Context context){
this.context = context;
}
public void test () {
final Intent myIntent = new Intent(context, NewActivity.class);
//guess this comes from somewhere, hope through a findViewById method
thebutton.setOnClickListener(
new OnClickListener() {
public void onClick(View v) {
context.startActivity(myIntent);
}
}
)};
}
}
This would be a proposed solution from my side. A problem I still see here is on how you retrieve the button in that test() method. In order to have that work properly you have to retrieve it from some View class (with view.findViewByid(R.id.myButton)) or to create it dynamically and associate it with the view during the onCreate(...) of your Activity (probably using an Inflater).

Categories

Resources