how to use activity context from other activity? - java

I want to use activity context from another activity simple code example below Any idea ?
public class Activity_A extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_Activity_A);
}
}
public class Activity_B extends AppCompatActivity {
Dialog dialog1 ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_Activity_B);
dialog1 = new Dialog(I want Activity_A Context) ; // Is this possible ??
}
}
Thanks

Tamim you can definitely achieve this using a different class by making a public static function in that other class
public class Utils {
public static void showDialog(Context context){
//// your code here
}
now you use it wherever you want...
Utils.showDialog(this);

Related

How can I do not use constructor in MainActivity in Android Studio?

I'm a beginner.
I'm trying to make Locale project with Android Studio.
So I made a class regard with Context.
In MainActivity required a constructor.
But, I'm heard that MainActivity do not need constructor but onCreate.
Here is my code.
BaseContextWrapper
public class BaseContextWrapper extends AppCompatActivity {
//AppCompatActivity-FragmentActivity-ComponentActivity-Activity-ContextThemeWrapper-ContextWrapper-Context
public BaseContextWrapper(Context base) {
super.attachBaseContext(base);
}
#RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
#NonNull
public static ContextWrapper wrap(Context context) {
Resources resources = context.getResources();
Configuration newConfig = new Configuration();
DisplayMetrics metrics = resources.getDisplayMetrics();
newConfig.setToDefaults();
newConfig.densityDpi = metrics.densityDpi;
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.JELLY_BEAN_MR1) {
context = context.createConfigurationContext(newConfig);
} else {
resources.updateConfiguration(newConfig, resources.getDisplayMetrics());
}
return new BaseContextWrapper(context);
}
}
MainActivity
public class MainActivity extends BaseContextWrapper {
public MainActivity(Context base) {
super(base);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
It all depends on what you inherit from. If from "extends Base ContextWrapper", then the constructor is required, it is included in the class. But if from "extends AppCompatActivity" then nothing but the onCreate() method is needed
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
Rewrite your MainActivity as
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}

why I can not use create method out side a function in AppCompatActivity

My app is crashing when I launch when I write code like this
public class MainActivity extends AppCompatActivity {
MediaPlayer mplayer= MediaPlayer.create(this,R.raw.song);
public void playMusic(View view){
mplayer.start();
}
public void pauseMusic(View view){
mplayer.pause();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
but when I write above code like this then it's working perfectly fine
public class MainActivity extends AppCompatActivity {
MediaPlayer mplayer;
public void playMusic(View view){
mplayer= MediaPlayer.create(this,R.raw.song);
mplayer.start();
}
public void pauseMusic(View view){
mplayer.pause();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
please anybody tell me what is wrong with first code
Thanks
because the player must be initialized at the moment when the context is not empty. That is, in the upper code, context == null in player. Therefore, the application crashes.

how to change actionBar title of Activity1 from a button of Activity2

I am trying to make a button in activity2(settings page), when the button is clicked, then the title of activity1(MainActivity) will change to what I set to. I have been trying to use interface to carry out the function but it gives me a null pointer exception error.
MainActivity
#Override
public void changeActionBarTitle(String editText){
actionTitle = editText;
setTitle(actionTitle);
};
Interface
public interface ActionBarInterface {
void changeActionBarTitle(String editText);
}
Setting page (activity 2)
public class SettingsPage extends AppCompatActivity {
ActionBarInterface actionBarInterface;
Button editCompanyNameButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings_page);
setTitle("Settings");
editCompanyNameButton = findViewById(R.id.editCompanyNameButton);
editCompanyNameButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
actionBarInterface.changeActionBarTitle("test");
}
});
}
}
Thanks.
You can try this code without using the interface
MainActivity:
#Override
protected void onResume() {
setTitle(Main2Activity.title);
super.onResume();
}
activity2:
public class SettingsPage extends AppCompatActivity {
Button editCompanyNameButton;
static String title;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
setTitle("Settings");
editCompanyNameButton = findViewById(R.id.editCompanyNameButton);
editCompanyNameButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
title = "test";
}
});
}
}
It gives a null pointer exception error because actionBarInterface was not initialised.
Check out topics on 'Getting a Result from an Activity', making use of classes and functions such as Intent, startActivityForResult, onActivityResult.
Android: how to make an activity return results to the activity which calls it?

Calling a method of MainActivity from other class

I am developing an Android app and thus, I have a MainActivity class. Inside of that MainActivity class, I have a method, let's call it doSomething():
public class MainActivity extends AppCompatActivity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void doSomething(){
// bla bla bla
}
}
I also have a different class (with different layout) that is called OtherActivity. I want to use the doSomething method inside it:
public class OtherActivity extends AppCompatActivity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.other_activity_layout);
// Let's use doSomething()
}
}
I tried this:
public class OtherActivity extends AppCompatActivity {
MainActivity main;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.other_activity_layout);
// Let's use doSomething()
MainActivity main = new MainActivity();
main.doSomething();
}
}
But it does not work. I also tried to make OtherActivity to extend the MainActivity, doing the following:
public class OtherActivity extends MainActivity{
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.other_activity_layout);
// Let's use doSomething()
super.doSomething();
}
}
But it does not allow me to initialize the layout...
How can I do?
Thanks in advance.
To communicate between to Activity Broadcast is the best way, and for the same application, we can use local broadcast using LocalBroadcastManager.
First, we should register one broadcast in MainActivity,
public class MainActivity1 extends AppCompatActivity {
public static final String INTENT_FILTER = "do_some_action";
public static final String INTENT_BUNDLE_VALUE = "value1";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main1);
LocalBroadcastManager.getInstance(this).registerReceiver(
mChangeListener, new IntentFilter(INTENT_FILTER));
}
#Override
protected void onDestroy() {
super.onDestroy();
LocalBroadcastManager.getInstance(this).unregisterReceiver(mChangeListener);
}
private BroadcastReceiver mChangeListener = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intentData) {
// you can do anything here
if (intentData != null && intentData.hasExtra(INTENT_BUNDLE_VALUE)) {
String value = intentData.getStringExtra(INTENT_BUNDLE_VALUE);
doSomeAction(value);
}
}
};
private void doSomeAction(String value) {
}
}
Then to do some action in MainActivity from OtherActivity, we can send Local broadcast from OtherActivity it will reach the receiver of Which we register in MainActivity,
public class OtherActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_other);
// You can call MainActivity to do some actions
Intent intent = new Intent(MainActivity1.INTENT_FILTER);
intent.putExtra(MainActivity1.INTENT_BUNDLE_VALUE, "Any string or any value");
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}
}
Done!!!.
Something like this should do the trick, I'm going to make a static navigator to handle your navigation logic. If you are opposed to static methods you could also make them on your Application object to make it easier to manage dependencies, I'm just making it static for simplicity.
//Making this fully static for simplicity, this is fine for a small app
//you can make it a singleton on the application class for more flexibility
public class Navigator {
//static member vars that determine navigation
// pass in Context if needed for navigation purposes
public static void doSomething(Context context){
// bla bla bla
}
}
public class MainActivity extends AppCompatActivity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity_layout);
}
private void doSomething() {
Navigator.doSomething(this);
}
}
public class OtherActivity extends AppCompatActivity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.other_activity_layout);
}
private void doSomething() {
Navigator.doSomething(this);
}
}

Need Modified Code Structure for MainActivity.java

I want to insert code in MainActivity of 'Webview' Project To code in MainActivity of 'Push Notification' project.
As I'm new to Android & Java, I have spent hell lot of time but unable to produce a solution.
Suggest solution for following code structure:
'Push Notification' Project
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//------Code for push notification---------------------
}
'Webview' Project
public class MainActivity extends Activity{
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//-----------Code for WebView------------
}
private class CustomWebViewClient extends WebViewClient {
public boolean shouldOverrideUrlLoading(WebView view, String url) {
//----------code-----------------
}
}
}
I have found solution myself. Hope others find it useful.
NOTE: Put push notification code before WebView code else it will not run push notification.
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//------Code for push notification---------------------
//-----------Code for WebView------------
}
private class CustomWebViewClient extends WebViewClient {
public boolean shouldOverrideUrlLoading(WebView view, String url) {
//----------code-----------------
}
}
}

Categories