Classes
Let's say I have my main activity A that is a AppCompactActivity, I want in this class A (for example in OnCrete) to do:
new B().show();
Class B would have a method show like :
private void show(){
Intent c = new Intent(A.this, C.class);
startActivity(c);
}
How can I make this work?
I tried to do the implementation above.
I suggest you to add a parameter to the show() method passing a reference to the activity A:
new B().show(myActivityA);
private void show(AppCompactActivity myActivityA){
Intent c = new Intent(A.this, C.class);
myActivityA.startActivity(c);
}
Related
I'm a new to java and android. I was working on my own app but I'm having a problem in passing a method from Activity A to Activity B.
Here is what I did :
ActivityA has Demo() method.
public class ActivityA extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
protected void demo() {
// Do something
}
}
I created the below class to access the method of ActivityA to ActivityB:
public class External {
private ActivityA activitya;
private static External instance = null;
public External(ActivityA activitya) {
this.activitya = activitya;
}
static public External getInstance(ActivityA activitya) {
if (instance == null) {
instance = new MyntraExternal(activitya);
return instance;
} else {
return instance;
}
}
}
Now how can I proceed further? I'm having lots of problem in getting the method which is in ActivityA from ActivityB.
Please anybody help.
Edit :
ActivityB is my launcher class and I want some access from ActivityA's method in ActivityB. What to do ?
Since you are new to Android, I will tell you it's a bad practice call methods from Activity A to B or vice versa, you can pass parameters from one activity to another using intents and bundles and if you need to pass parameters from the second activity to the first you need to use the override method onActivityResults
Here are some usefull link about passing parameters from one activity to another:
https://www.dev2qa.com/passing-data-between-activities-android-tutorial/
In this link you can see a example of how things work.
Hope it helps.
--EDIT (if you need to call a function from B to A in case you want to change something in A upon creation this is the best and simplest way to do it):
In Activity B:
Intent intent = new Intent(this, ActivityA.class);
intent.putExtra("Work","doJump");
startActivity(intent);
In Activity A:
onCreate:
String extra = getIntent().getStringExtra("Work");
if(extra != null && extra.equals("doJump")){
jump();
}
make that method public and static and then access it using class name. e.g. In your 2nd activity, use ActivityB.demo()
Try using startActivityForResult
To start activity B from activity A
startActivityForResult(intent, SOME_CODE)
And to be called back on result you will need to add the following code the also in activity A
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
when(code){
SOME_CODE -> if (resultCode == Activity.RESULT_OK) doSomething()
}
}
To tell Activity A to call the method, in activity B you can say:
setResult(Activity.RESULT_OK)
finish()
After B is finished, onActivityResult in A will be executed
To go back to A without executing the "doSomething()" method,
setResult(Activity.RESULT_CANCELED)
finish()
Please try this way
public class ActivityA extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void demo() {
// Do something
}
}
public class ActivityB extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ActivityA activityA = new ActivityA(); // create object
activityA.demo(); //
}
}
There are two Activities..
1. Open SecondActivity from MainActivity
2. When event comes into MainActivity, call testMethod of SecondActivity
But how to do call this testMethod?
public class MainActivity extends Activity implements someListener {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Launch SecondActivity here!!
Intent intent = new Intent();
intent.setClass(MainActivity.this, SecondActivity.class);
startActivityForResult(intent, ID_PlayerActivity);
}
//trigger by JNI, it's in the other thread, not main thread.
void onEventCome() {
//How to call testMethod() in SecondActivity?
}
}
public class SecondActivity extends Activity {
void testMethod() {
//execute something...
}
}
If you open the SecondActivity, your MainActivity becomes inactive. I don't believe it is a good idea to call some activity method from other inactive/stopped activity.
I suggest to use observer pattern. Create a global long-lived object like EventProducer and register all activities as observer. So your EventProducer can inform all Activities about new event.
Example:
public class SecondActivity extends Activity implements MyEventListener {
#Override
public void onResume(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
EventProducer.instance().register(this);
}
#Override
public void onPause(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
EventProducer.instance().unregister(this);
}
void testMethod(){
//just doit
}
#Override
void onMyEventCome() {
testMethod();
}
}
First you need an event aware listener that will capture such an event happening. Your class seems ill equipped to do so.
Since you have a valid question, here goes:
void onEventCome() {
SecondActivity secondActivity = new SecondActivity();
secondActivity.testMethod();
}
There are many ways.
For eg:
Create the method as static and use class name and call it.
public static void onEventCome() {
}
In MainActivity:
MainActivity.onEventCome();
This is one method. Another method is create an object for MainActivity.
public void onEventCome() {
}
MainActivity main;
main = new MainActivity();
main.onEventCome();
You don't have a content view for your second activity. If you don't need to see the operation happen, you could remove your
Intent intent = new Intent();
intent.setClass(MainActivity.this, SecondActivity.class);
startActivityForResult(intent, ID_PlayerActivity);
remove extends Activity in SecondActivity and add a constructor public SecondActivity(Context context) and invoke the test method from your first activity like #Dragan example:
void onEventCome() {
SecondActivity secondActivity = new SecondActivity(MainActivity.this);
secondActivity.testMethod();
}
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;
}
}
});
}
}
I have a problem as explained here. I have a Class A, ClassB. Both have Intents to navigate to Class C. Now, I want to know from Which class i have navigated to Class C so that i will navigate to previous screen either A or B. Calling finish() in Class C doesnt help me because i need to update the data in Class A and Class B differently. Can anybody please help me. How to use Intent here? Can i know from which class i have to navigated to Class C?
you should use startActivityForResult and override the onActivityResult callback. This way you can safetly update your data without know from wich activity you came from.
public class A extends Activity {
private final static int REQUEST_CODE= 1000;
public void onCreate(BUndle b) {
...
Intent intent = new Intent(this, C.class);
startActivityForResult(intent, REQUEST_CODE);
}
#override
void onActivityResult(int requestCode, int resultCode, Intent data) {
// here through data you will receive new data
}
}
public class C extends Activity {
public void onCreate(BUndle b) {
// modify same data
Intent intent = new Intent();
// pute data inside intent
setResult(Activity.RESULT_OK, intent);
finish();
}
}
in your intents in class A and B, put a parameter like a boolean "isclassA" and make tests on it to know.
in intent of classe A :
intent.putExtra("isfromclassA",true);
in intent of class B :
intent.putExtra("isfromclassA",false);
therefor in your class C :
boolean isfromclassA = intent.getBoolExtra("isfromclassA");
This question already has answers here:
How do I pass data between Activities in Android application?
(53 answers)
How to pass a value from one Activity to another in Android? [duplicate]
(7 answers)
Closed yesterday.
i have this code but it doesnt work (Force Close)
,i use this in C# but its not working in java
ClassA c = new ClassA();
c.TextView1.setText("test");
i need to set the text view from ClassB can it be done
without using the Intent
because the Intent need to start the Activity all over and all the data will be lost
can anyone suggest a code for this
also can i set the int x value in ClassA from ClassB
Yes, you can do -
Intent i = new Intent(classA.this, classB.class);
Bundle bundle = new Bundle();
bundle.putExtra("name For Identification", "Value);
i.putExtras(bundle);
startActivity(i);
In your second class, i mean Class B
Bundle bundle = getIntent().getExtras("name for Identification");
String text = bundle.getString("name For Identification");
Simply set this text to your TextView And, the Class B also should extends the Activity Otherwise, the getIntent() code will not work.
Within ClassA
Define your TextView
private TextView1 txtView1;
Load it during onCreate
txtView1 = (TextView) findViewById(R.id.txtView1);
Write a setter
public void setTextOnTextView1(String text) {
txtView1.setText(text);
}
In your other class you can now
c.setTextOnTextView1("Hello");
Try this
add this in activity 1
Intent myIntent = new Intent(Activity1.this, Activity2.class);
myIntent.putExtra("UserId",UserId);
myIntent.putExtra("UserName",UserName);
startActivity(myIntent);
add this in activity 2
Intent intent = getIntent();
UserId=intent.getStringExtra("UserId");
UserName=intent.getStringExtra("UserName");
intent to class B from class A
Intent toClassB = new Intent(classA.this,classB.class);
toClassB.putExtra("StringId","value");
startActivity(toClassB);
//get value
Intent intent = getIntent();
String getValue = intent.getStringExtra("StringId");
//set text
textView.setText(getValue);
hope this helps
To Pass value between two activites you can use shared Preferenceas follow
In Activity A:
public class activityA extends Activity{
private final String MY_value = "value";//variable used for shared preference
#Override
public void onCreate(Bundle savedInstanceState)
{
SharedPreferences myPrefs = getBaseContext().getSharedPreferences("myPrefs", MODE_WORLD_READABLE);
SharedPreferences.Editor prefsEditor = myPrefs.edit();
prefsEditor.putString(MY_value, "xyz");
prefsEditor.commit();
}
}
In Activity B you can retrive that value as follow:
public class activityB extends Activity{
private final String MY_value = "value";//variable used for shared preference
#Override
public void onCreate(Bundle savedInstanceState)
{
SharedPreferences myPrefs1 = this.getSharedPreferences("myPrefs", MODE_WORLD_READABLE);
roadworthynumber = myPrefs1.getString(MY_value, "value");
}
}
Yup it can be done without using intent, use static methods/members of class
Get the TextView object from a static method from ClassA and similarly define a static method setX(int x) method in ClassA
So for example
class ClassA{
static TextView tv; //this should be intialized in your code via findViewByID or by code depneds
static int x;
static public TextView getTextView(){
return tv;
}
static public void setX(int xP){
x = xP;
}
}
from ClassB you can invoke ClassA.getTextView() and ClassB.setX(12)
Create a function returnThis() in Class A
ClassA returnThis()
{
return this;
}
In classB call this function and by using returned reference set textView of classA