guys, I'm pretty new to java android programming (that's the first app I'm making) and I have this question:
How can i refresh my Main Activity from another activity, which is called from the Main one?
I would also appreciate if you give me some examples, because I'm still not very orientated...
You can use startActivityForResult() for that purpose, instead of context.startActivity() call context.startActivityForResult() and then set result in launched activity before finishing it.
Here is the documentation for Context.startActivityForResult()
Sample code:
// Activity A
public class ActivityA extends Activity {
private static final int REQUEST_CODE_ACTIVITY_B_FOR_RESULT = 1; // or other int value
// sample code which starts Activity B
private void onSomeButtonClick() {
Intent intent = new Intent(this, ActivityB.class);
startActivityForResult(intent, REQUEST_CODE_ACTIVITY_B_FOR_RESULT);
}
// this method will be called when started activity finished
// and returned some result of its work
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent resultData) {
super.onActivityResult(requestCode, resultCode, resultData);
if (requestCode == REQUEST_CODE_ACTIVITY_B_FOR_RESULT) {
if (resultCode == RESULT_OK) {
// handle result ok and resultData here
} else {
// handle result canceled or other resultCode and its resultData here
}
}
}
}
// Activity B
public class ActivityB extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setResult(RESULT_CANCELED); // by default result of starting activity is negative
}
// some code which doing some action and setting result as ok
private void doSomething() {
Intent resultData = new Intent();
resultData.putExtra("SOME_EXTRA", "did it"); // or other result data
setResult(RESULT_OK, resultData);
finish(); // finishing this activity, result code and result data will be accessible in previous activity
}
}
How to call main activity from the sub activity. Use an interface.
1. Creata a public interface in the sub-activity
public class MapSettings extends DialogFragment implements
OnCheckedChangeListener {
public interface BestRidesSettingsDialogListener {
void onMapSettingsChange(int mapType);
}
2. Implement the interface in the main activity note right click on errors and select add imports add reference add unimplemented methods.
public class KmlReader extends ActionBarActivity implements
BestRidesSettingsDialogListener {
3. when the sub activity starts in the sub activity cast getActivity to the public interface
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// the activity may be null if this is called without implementing the
// BestRidesSettingsDialogListener (The settings object saves the
// setting so the
// call back may not be needed.
activity = (BestRidesSettingsDialogListener) getActivity();
4. Then in the sub activity when a button is clicked or some event happens call through to the interface method.
#Override
public void onCheckedChanged(RadioGroup rg, int checkId) {
// TODO Auto-generated method stub
int mapType = 0;
switch (checkId) {
case R.id.RDORoad:
mapType = GoogleMap.MAP_TYPE_NORMAL;
break;
case R.id.RDOHybrid:
mapType = GoogleMap.MAP_TYPE_HYBRID;
break;
case R.id.RDOSatelite:
mapType = GoogleMap.MAP_TYPE_SATELLITE;
break;
case R.id.RDOTerrain:
mapType = GoogleMap.MAP_TYPE_TERRAIN;
break;
}
// run the activity onchange
// if the activity is null there is no listener to take action on the
// settings
if (activity != null) {
activity.onMapSettingsChange(mapType);
}
5. if you've filled in the unimplemented methods stubs in your main activity your executing code directly in the main activity from the sub activity.
#Override
public void onMapSettingsChange(int mapType) {
if (mMap != null) {
mMap.setMapType(mapType);
}
}
sidebar for comments: The interface has always been my favorite part of java. You might call it a listener or a call back. Just right click on the errors and select add reference, add unimplemented methods there really are not too many keystrokes to do this. The interface is perhaps the easiest way to coordinate a team effort on making the next big thing.
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(); //
}
}
I have 2 activities ,activity A is having webview and activity B is having button with transparent layout. I want close the activity B and refresh or do something in activity A when I press button from activity B.
I tried shared preferences but that not working without restarting activity A.
Have a look at the docs for Getting a Result from an Activity
Updated to include example
static final int PICK_CONTACT_REQUEST = 1; // The request code
...
private void pickContact() {
Intent pickContactIntent = new Intent(Intent.ACTION_PICK, Uri.parse("content://contacts"));
pickContactIntent.setType(Phone.CONTENT_TYPE); // Show user only contacts w/ phone numbers
startActivityForResult(pickContactIntent, PICK_CONTACT_REQUEST);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// Check which request we're responding to
if (requestCode == PICK_CONTACT_REQUEST) {
// Make sure the request was successful
if (resultCode == RESULT_OK) {
// The user picked a contact.
// The Intent's data Uri identifies which contact was selected.
// Do something with the contact here (bigger example below)
}
}
}
create a method as refreshmethod in Activity A and call it from Activity B something like this:
ActivityA activitya:
//stuff
activitya = new ActivityA();
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
activitya.refreshmethod();
}
});
hope it helps.
Right now i'm having :-
1) 1 activity which is the main activity that extends from AppCompactActivity.
2) 1 fragment class that extends from fragment, this is the fragment that being called from main activity (1) - ProfileTeacherActivity.java
3) 1 fragment class that extends from DialogFragment, this dialog getting called from fragment (2) - ModalBox.java
So, basically, this is just a simple flow of execution. At start, the applications showing the main activity (1) having drawer that have a few links as example a profile link, when click this link, the application call the fragment (2) showing details of profile with one edit button. After clicking edit button, the applications will invoke DialogFragment (3) that contains some of EditText for editing user's profile.
What i want to achieve is, after editing user's profile and successful saved into database, i tried to send user's data back to fragment (2) just to show latest updated info, unfortunately it didn't work.
Here is what i'm tried :
1) Creating Interface inside DialogFragment (3) - ModalBox.java
public class ModalBox extends DialogFragment{
....
public interface EditProfileModalBoxInterface {
void onFinishEditProfile( HashMap<String, String> dataPassing );
}
...
...
}
2) Inside DialogFragment also i have .setPositiveButton function for OK button. - ModalBox.java
public class ModalBox extends DialogFragment{
...
...
public Dialog onCreateDialog(Bundle savedInstanceState ) {
...
builder
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(final DialogInterface dialog, int id) {
// At here i'm using retrofit2 http library
// to do updating stuff
// and inside success's callback of retrofit2(asynchronous)
// here i call the below function to send data
// dataToSend is a HashMap value
sendBackResultToParent( dataTosend );
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User cancelled the dialog
}
});
.....
}
// Function called inside success's callback of retrofit2
public void sendBackResultToParent( HashMap<String, String> data ) {
// instantiated interface
EditProfileModalBoxInterface ls=(EditProfileModalBoxInterface)getTargetFragment();
// declaring interface's method
ls.onFinishEditProfile( data );
}
}
3) Finally, i'm implements those interface inside fragment (2) - ProfileTeacherActivity.java
public class ProfileTeacherActivity extends Fragment
implements ModalBox.EditProfileModalBoxInterface{
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState ) {
.....
.....
}
// At here the interface's method did't triggered
#Override
public void onFinishEditProfile( HashMap dataPassedFromDialog ) {
Toast.makeText(getActivity(), "Testing...." , Toast.LENGTH_LONG).show();
}
}
What i'm confuses right now is, the problem happens only when i called this function sendBackResultToParent( dataTosend ); inside retrofit2 success's callback, it does triggered when calling outside of it. I'm assumed the async called caused this. If i could use Promise or something like that or is there any workaround on this?
The following existing solutions didn't work in my case :
Callback to a Fragment from a DialogFragment
How to send data from DialogFragment to a Fragment?
Send Data from DialogFragment to Fragment
Ask me for more inputs if above use case didn't clear enough or misunderstanding. Thanks for the helps. Regards.
This is a sample DialogFragment code used to send message to selected contact. I too required to capture the click event on the DialogFragment and redirect.
Ideally to achieve this , this is what needed to be done
Override the positive/negative button clicks of AlertDialog.Builder and do no action
After this , using getButton method mention AlertDialog.BUTTON_NEGATIVE or AlertDialog.BUTTON_POSITIVE and assign an action
public class SMSDialogFrag extends DialogFragment {
private static String one="one";
private EditText messageContent;
private AlertDialog dialog;
private String mobNumber;
public static SMSDialogFrag showDialog(String mobNumber){
SMSDialogFrag customDialogFrag=new SMSDialogFrag();
Bundle bundle=new Bundle();
bundle.putString(one, mobNumber);
customDialogFrag.setArguments(bundle);
return customDialogFrag;
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(getActivity());
View view = getActivity().getLayoutInflater().inflate(R.layout.sms_dialog, null);
alertDialogBuilder.setView(view);
setupUI(view);
alertDialogBuilder.setTitle("");
alertDialogBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//Do nothing here because we override this button later
}
});
alertDialogBuilder.setPositiveButton("Send", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//Do nothing here because we override this button later
}
});
dialog = alertDialogBuilder.create();
dialog.show();
dialog.getButton(AlertDialog.BUTTON_NEGATIVE).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
//else dialog stays open. Make sure you have an obvious way to close the dialog especially if you set cancellable to false.
}
});
dialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sendMessage();//IN YOUR USE CASE YOU CAN REDIRECT TO YOUR CALLER FRAGMENT
}
});
return dialog;
}
void setupUI(View view){
TextView textViewMob=(TextView)view.findViewById(R.id.mobNumber);
messageContent=(EditText)view.findViewById(R.id.messageContent);
mobNumber=getArguments().getString(one);
textViewMob.setText("Send message to : "+mobNumber);
}
void sendMessage(){
if( ! TextUtils.isEmpty(messageContent.getText())){
try {
SmsManager smsManager = SmsManager.getDefault();
Log.v(Constants.UI_LOG,"Number >>>>>>> "+mobNumber);
smsManager.sendTextMessage(mobNumber, null, messageContent.getText().toString(), null, null);
} catch (Exception e) {
e.printStackTrace();
}
Toast.makeText(getActivity(),"Message Sent!",Toast.LENGTH_SHORT).show();
dialog.dismiss();
}else{
Toast.makeText(getActivity(),"Please enter message to send!",Toast.LENGTH_SHORT).show();
}
}
}
Consider using eventBus, for example
Otto
The usage is very simple. All you need to do is create an evenbus:
public static Bus bus = new Bus(ThreadEnforcer.MAIN); //use Dagger2 to avoid static
Then create a receiver method (in fragment 2 in your case):
#Subscribe
public void getMessage(String s) {
Toast.makeText(this, s, Toast.LENGTH_LONG).show();
}
Send you message by calling(from DialigFramgent):
bus.post("Hello");
And don't forget to register your eventBus inside onCreate method(of your Fragment):
bus.register(this);
And that is!
From architectural standpoint, 2 fragments should not directly communicate with one another. Container Activity should be responsible for passing data between it's child fragments. So here's how i would do it:
Implement your interface in the container Activity and just attach your interface implementation in the Activity to the Dialog class and call that interface method when required. Something like this :
public static class ModalBox extends DialogFragment {
EditProfileModalBoxInterface mListener;
// Container Activity must implement this interface
public interface EditProfileModalBoxInterface {
void onFinishEditProfile( HashMap<String, String> dataPassing );
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (EditProfileModalBoxInterface) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString() + " must implement EditProfileModalBoxInterface");
}
}
}
Then call mListener.onFinishEditProfile(....) where ever it's required in the DialogFragment class.
This way you will receive the result back in your Activity class from where you can call your desired fragment's relevant method to pass the results to that fragment.
This whole flow has been described here
Finally the culprit founds. All the answers mentioned above were right. And my script also actually works, the problem is related with my API json's response that did't coming with right structure. In my case, i'm using retrofit2 with GSON converter for parsing into POJO. Found the info on log saying about :
Expected BEGIN_OBJECT but was BEGIN_ARRAY
Means that, GSON expecting the json object, which is my API was returned JSON array. Just change the API's structure then all goods to go. Thanks guys for your hard time. Really appreciated, as i'm right now knowing how to deal with eventBus, replacing default OK and Cancel button and the correct way for communicating between fragments.
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 two Activities A and B. B has a method searchDevices. I want to access that method from A 's onCreate method. How can I do it with Intent?
I tried this :
public void onCreate(Bundle savedInstanceState)
{
try{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MY_UUID= UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
//Function enbling Bluetooth
enableBluetooth();
///Function to initialize components
init();
//Calling AvailableDevices class's method searchDevice to get AvailableDevices
Intent intent=new Intent(this,AvailableDevices.class);
int x=10;
intent.putExtra("A", x);
}catch(Exception e){Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();}
}
You can also create a base activity that both ActivityA and ActivityB extends and put searchDevices() method in it.
For ex:
public class BaseActivity extends Activity{
public void searchDevices(){
}
}
public class ActivityB extends BaseActivity{
onCreate..
{
...
searchDevices();
}
}
public class ActivityA extends BaseActivity{
onCreate..
{
...
searchDevices();
}
}
if ActivityA is in a class called class1 make a method in class1 like this
public static void method1(){
}
then in activity 2 call the method by doing this ActivityA.method1()
Why don't use StartActivityForResult.
As per my understanding You can start AvailableDevices Activity for result with Intent having extra data and call searchDevice to get AvailableDevices and return the result to calling Activity.
[Edit]
In Class A
//Calling AvailableDevices class's method searchDevice to get AvailableDevices
Intent intent=new Intent(this,AvailableDevices.class);
int x=10;
intent.putExtra("A", x);
startActivityForResult(intent , searchDevicesRequestCode); //searchDevicesRequestCode = 100
Also override onActivityResult()
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// Check which request we're responding to
if (requestCode == searchDevicesRequestCode) {
// Make sure the request was successful
if (resultCode == RESULT_OK) {
// Manipulate searchDevicesResult from Intent data
}
}
}
In Class B
#override
onCreate()
{
//call searchDevices()
String result = searchDevices(); // save result to send in any form
// Create intent to deliver some kind of result data
Intent intentResult = new Intent("RESULT_ACTION");
intentResult.putExtra("key",result);
setResult(Activity.RESULT_OK, intentResult);
finish();
}