Define generic method can open all activities - java

Can i define an activity in parent class of all activities that that can open new activity like this method that working:
public class ActivityBase extends Activity{
public <T extends Activity,U extends Activity> void openActivity()
{
Intent myIntent = new Intent(T.this, U.class);
T.this.startActivity(myIntent);
}
}
public class ActivityChield extends ActivityBase{
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_warning_unregistered_shipping);
// Set widgets reference
btnOpenActivity = (Button)findViewById(R.id.btn_wus_select_violation);
// Set widgets event listener
setListeners();
}
private void setListeners()
{
btnOpenActivity.setOnClickListener( new View.OnClickListener()
{
#Override
public void onClick(View view)
{
openActivity<ActivityChield , OtherActivity>();
}
});
}
}
This code is not working . Please help me how can i define a method that can open all activities with one method.

I don't think this way is a perfect solution. Better is to write the calling code when you need.
By the way here is a solution for your question
public void openActivity(Class<?> calledActivity) {
Intent myIntent = new Intent(this, calledActivity);
this.startActivity(myIntent);
}
And you can call it as
openActivity(OtherActivity.class);

Related

How do I call one method of an activity from another class

This is a part of my activity class,
public class StatusActivity extends AppCompatActivity {
private boolean cFlag = false;
public boolean getFlag() { return cFlag; }
public void setFlag(boolean cFlag) {
this.cFlag = cFlag;
}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list);
adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1,
android.R.id.text1, messages);
ListView listView = findViewById(android.R.id.list);
listView.setAdapter(adapter);
adapters.add(adapter);
Button btn = findViewById(R.id.btnCustomerCheckIn);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setFlag(true);
cFlag = getFlag();
Intent intent = new Intent(StatusActivity.this, MainActivity.class);
Toast.makeText(StatusActivity.this, "customer checked in",
Toast.LENGTH_LONG).show();
startActivity(intent);
}
});
}
this is a part of another class named as position
public class Position {
StatusActivity statusactivity = new StatusActivity();
public boolean ccflag = statusactivity.getFlag();
statusactivity.setFlag(false);
}
when i am calling
statusactivity.setFlag(false);
it is showing an error. couldn't recognize that what is the error that i am getting. but
statusactivity.getFlag();
is working properly. any help is appreciated
StatusActivity statusactivity = new StatusActivity();
This is totally wrong because you are trying to create a new Instance of activity.
If you want to use "setFlag" method from other activity then you must create a static method inside StatusActivity so you can access using directly StatusActivity.
And If you want to call from any fragment of this activity then please get an instance of this activity by the cast from "getActivity()" to StatusActivity and use that instance for call "setFlag" or "getFlag" method.
You can implement like below in Activity.
private static boolean cFlag = false;
public static boolean getFlag() {
return cFlag;
}
public static void setFlag(boolean cFlag) {
StatusActivity.cFlag = cFlag;
}
and call from position class like below
public class Position {
public boolean ccflag = StatusActivity.getFlag();
StatusActivity.setFlag(false);
}
you can not instantiate Activity class. if you want to call a method from activity, fist you should check that activity already running and not destroyed then by having the context of your class you just cast it like below then use its method
StatusActivity statusactivity= (StatusActivity )context;
statusactivity.setFlag(false);

How to implement startActivity() inside the OnClick() method of a separate Java class?

So i made three 3 java files.
main activity class
ButtonListener.java(Separate java class)
PurpleActivty.class(activity)
I implemented OnclickListener and OnClick method inside my ButtonListener.java file.
I want to start intent startActivity() inside my onClick(View v) of ButtonListener file. But it is throwing error on startActivity() line.
I know that i can make OnClick method under onCreate of AvtivityClass but i don't want to do this as i have made a separate java file that can handle all my button listeners.
File MainActivity.java
public class MainActivity extends AppCompatActivity {
public Button intentPurple;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
intentPurple=findViewById(R.id.button5);
Intent gg= new Intent(MainActivity.this, PurpleActivty.class);
ButtonListener B= new ButtonListener(gg);
intentPurple.setOnClickListener(B);
}
}
file ButtonListener.java
public class ButtonListener implements View.OnClickListener {
private Intent g;
public ButtonListener(Intent F) {
this.g=F;
}
#Override
public void onClick(View v) {
switch(v.getId()) {
case R.id.button5:
startActivity(g); // this line is error(red underline g) error msg
break; //is "startActivity() in ContextCompat cannot be
//applied to"
}}}
Any way to solve this issue?
You need to call startActivity from the context of the activity, not from your custom handler class. Refactor ButtonListener to this:
public class ButtonListener implements View.OnClickListener {
private Intent g;
private Context caller;
public ButtonListener(Intent f, Context caller) {
this.g = f;
this.caller = caller;
}
#Override
public void onClick(View v) {
switch(v.getId()) {
case R.id.button5:
caller.startActivity(g);
break;
}
}
}
Then call your listener like this:
intentPurple = findViewById(R.id.button5);
Intent gg = new Intent(MainActivity.this, PurpleActivty.class);
ButtonListener b = new ButtonListener(gg, MainActivity.this);
intentPurple.setOnClickListener(b);
I believe in
public ButtonListener(Intent F) {
this.g=F;
}
you dont have to use this, because the variable names are different.
Other than that I believe the
Intent gg= new Intent(**MainActivity.this**, PurpleActivty.class);
MainActivity.this is causing the issue as you are in a different class, you should pass MainActivity´s context as a parameter too and use
context.startActivity(g);
OR
view.getContext().startActivity(g);

How to interact with UI from a different class

I would like to update my UI from a different class. I am familiar with runOnUiThread() method, but don't know how to implement it in this scenario?
public class UploadAct extends MainActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_upload);
}
//my code and functions would go here
}
Then, my UploadData class
public class UploadData extends UploadAct {
public void doSomethig(){
printThis("I want to print this message to the UI");
}
public void printThis(String messsage) {
final String mess = message;
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),mess,Toast.LENGTH_LONG).show();
// I want this to display on the main thread
txt_upload.setText(mess);// and this also
}
});
}
}
Use BroadcastReceiver
// define a Broadcast Intent Action in String resources
<string name="broadcast_id">MY_BROADCAST_ID</string>
// register receiver in constructor/onCreate()
MyBroadcastReceiver myBroadcastReceiver = new MyBroadcastReceiver();
IntentFilter myIntentFilter = new IntentFilter();
myIntentFilter.addAction(context.getString(R.string.broadcast_id));
context.registerReceiver(myBroadcastReceiver, myIntentFilter);
// place your BroadcastReceiver in MainActivity, your UploadData class
public class MyBroadcastReceiver extends BroadcastReceiver {
public MyBroadcastReceiver(){
super();
}
#Override public void onReceive(Context context, Intent intent) {
Log.d(TAG, "Broadcast received");
if(intent.getAction() != null && intent.getAction().equals(context.getString(R.string.broadcast_id)) ){
// do something
}
}
}
// send Broadcasts from where you want to act, your UploadAct class.
Intent intent = new Intent();
intent.setAction(context.getString(R.string.broadcast_id));
context.sendBroadcast(intent);
Log.d(TAG, "Broadcast sent.");
// you can unregister this receiver in onDestroy() method
context.unregisterReceiver(myBroadcastReceiver);
You can also use an interface to update your UI as a listener.
First, Create an interface
public interface UpdateTextListener {
void updateText(String data);
}
Then, Call its method in your UploadData class
public class UploadData extends UploadAct {
UpdateTextListener listener;
public void doSomethig(){
listener.updateText("data to be loaded");
}
}
Then, Update your UploadAct by listening to this method
public class UploadAct extends MainActivity implements UpdateTextListener {
#Override
public void updateText(String data) {
textview.setText(data);
}
}
First of all - there is no such thing like UI of some class. There are activities that can have handles to UI widgets (ex TextView). If you want to make some changes to UI from your UploadData class you have to pass somehow reference to this class. Possibly by constructor:
public class UploadData extends UploadAct{
private TextView txt_upload;
public UploadData(TextView tv)
{
txt_upload = tv;
}
public void doSomethig(){
printThis("I want to print this message to the UI")
}
public void printThis(String messsage) {
final String mess = message;
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),mess,Toast.LENGTH_LONG).show();// I want this to display on the main thread
txt_upload.setText(mess);// and this also
}
});
}
}
I assume that you create DataUpload in your MainActivity.
Everyone use so much library to be trendy as they forget built in functions in Android :)
For sure isn't any hard thing to use AsyncTask, beside it provides the doInBackground function it has the https://developer.android.com/reference/android/os/AsyncTask.html#publishProgress(Progress...) function too, what you have asked for.
Just create a class (UploadTask) which extends AsyncTask and override 1-2 function.

Android-Libgdx, Calling Another Activity after the Game starts on Button click

I faced a major problem when I need to call another activity when the button is clicked after the Game is started. The Game is called via initiate(game, ) method from AndroidApplication interface.
In normal Activity, I can easily call the another Activity but it seems to be difficult to call another Activity from Libgdx class that implements AndroidApplication.
Could anyone suggest a proper method to call the Activity from Libgdx class that implements AndroidApplication interface?
I tried to do this for a week but it seems that my method is totally wrong..
Thanks in advance.
Define a callback interface in you LibGdx class, and use it to notify your AndroidLauncher to start the new activity.
For example in your LibGdx game class:
// Your Game class in the core package
public class MyGame extends Game {
// Define an interface for your various callbacks to the android launcher
public interface MyGameCallback {
public void onStartActivityA();
public void onStartActivityB();
public void onStartSomeActivity(int someParameter, String someOtherParameter);
}
// Local variable to hold the callback implementation
private MyGameCallback myGameCallback;
// ** Additional **
// Setter for the callback
public void setMyGameCallback(MyGameCallback callback) {
myGameCallback = callback;
}
#Override
public void create () {
...
}
...
private void someMethod() {
...
// check the calling class has actually implemented MyGameCallback
if (myGameCallback != null) {
// initiate which ever callback method you need.
if (someCondition) {
myGameCallback.onStartActivityA();
} else if (someOtherCondition) {
myGameCallback.onStartActivityB();
} else {
myGameCallback.onStartSomeActivity(someInteger, someString);
}
} else {
Log.e("MyGame", "To use this class you must implement MyGameCallback!")
}
}
}
Then ensure your AndroidLauncher implements the required interface:
// Your AndroidLauncher
public class AndroidLauncher extends AndroidApplication implements MyGame.MyGameCallback {
#Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
AndroidApplicationConfiguration config = new AndroidApplicationConfiguration();
// create an instance of MyGame, and set the callback
MyGame myGame = new MyGame;
// Since AndroidLauncher implements MyGame.MyGameCallback, we can just pass 'this' to the callback setter.
myGame.setMyGameCallback(this);
initialize(myGame, config);
}
#Override
public void onStartActivityA() {
Intent intent = new Intent(this, ActivityA.class);
startActivity(intent);
}
#Override
public void onStartActivityB(){
Intent intent = new Intent(this, ActivityB.class);
startActivity(intent);
}
#Override
public void onStartSomeActivity(int someParameter, String someOtherParameter){
Intent intent = new Intent(this, ActivityA.class);
// do whatever you want with the supplied parameters.
if (someParameter == 42) {
intent.putExtra(MY_EXTRA, someOtherParameter);
}
startActivity(intent);
}
}

Abstract class issue

I am creating one parent Activity(Class) and then want to extends this class to another Activity(Class). I have some controls in all the Activities(Classes) so I decide to use Abstract class so that I need not write some common code in all the classes.I created below classes and one of it is abstract class.When I am calling my Welcomepage Activity this will display me a screen with all common controls(Radio buttons in my case).In Abstract class I had set checkedChangedListener listener and in onCheckedChanged() method I am creating a toast but It is not displaying.I am confused in this case.What is the reason to not displaying a toast?.
My Activity(Class) Welcomepage_pillReminder which extends CustomTabsActivity
public class Welcomepage_pillReminder extends CustomTabsActivity
#Override
public void mappingWidgets() {
super.mappingWidgets();
}
#Override
public void addCheckChangedListner() {
super.addCheckChangedListner();
}
CustomActivity
public abstract class CustomTabsActivity extends Activity {
protected RadioButton radHome;
public void mappingWidgets(){
radHome = (RadioButton)findViewById(R.id.radHome);
}
public void addCheckChangedListner() {
radHome.setOnCheckedChangeListener(onCheckedChangeListener);
}
OnCheckedChangeListener onCheckedChangeListener = new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked) {
if(buttonView.getText().equals("Home")) {
Toast.makeText(getApplicationContext(), "Home", 2000).show();
}
}
}
};
}
You can do it like this,
Your CustomActivity.java
public class CustomActivity extends Activity implements OnClickListener{
public void initLayout(Button button){
button.setOnClickListener(this);
}
public void simple_method(){
System.out.println("test in CustomActivity");
}
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "Button Clicked in Custom Activity", Toast.LENGTH_LONG).show();
}
}
Activity that extends CustomActivity
CustomClassDemoActivity.java
public class CustomClassDemoActivity extends CustomActivity{
Button button;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
button = (Button) findViewById(R.id.myTextView);
button.setText("This is a Custom Activity Example");
super.initLayout(button);
simple_method();
}
public void simple_method(){
super.simple_method();
System.out.println("test in mainClass");
}
#Override
public void onClick(View v) {
super.onClick(v);
Toast.makeText(getApplicationContext(), "Button Clicked in Main Activity", Toast.LENGTH_LONG).show();
}
}
For your purpose the using of an abstract class dosent make sense.
An abstract class only declares its methods and the concrete class can implement the method then depending on its purpose. It would make sense if you plan to write various classes which extend your activity and each of them would have another implementation purpose for mappingWidgets() and addCheckChangedListner().
In your case a simple class which will be extended would do the job.
Furthermore I see, that you use the #Override annotation in your sub class. With this annotation you override your methods.
At first, please remove the #Override in your methods of the sub class. I guess they will work then.
Maybe also reconsider when usin abstract classes and / or #Override.
I forgot to call function mappingWidgets() and addCheckChangedListner() after calling this two method my code works fine.Thanks all for help me.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.welcome_pillminder);
mappingWidgets();
addCheckChangedListner();
}

Categories

Resources