Import common functions in all activities android - java

I am working on an android app that has a menu at the top (like we have in websites; home, aboutus etc). This menu is repeated in all the activities so I have to repeat the code for these in all activities. Is there a way that I can write the code once in some class and reuse it in all other activities using inheritance or something? (Just lice there is include function in php). Hope my question is straight forward. Here is the code for the menu that I have to repeat everywhere.
// menu items
menu_home.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i = new Intent(CurrentActivity.this, HomeActivity.class);
startActivity(i);
}
});
menu_help.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i = new Intent(CurrentActivity.this, HelpActivity.class);
startActivity(i);
}
});
menu_media.setOnClickListener(new OnClickListener() {;
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i = new Intent(CurrentActivity.this, MediaActivity.class);
startActivity(i);
}
});
menu_index.setOnClickListener(new OnClickListener() {;
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i = new Intent(HomeActivity.this, IndexActivity.class);
startActivity(i);
}
});

I have to repeat the code for these in all activities.
Java does not support multiple inheritances.
Don’t use inheritance just to get code reuse. If there is no is a relationship then use composition for code reuse. Overuse of implementation inheritance (aka extends) can break all the sub-classes, if the superclass is modified.
In you case I would use composition. Just create new class that implements above mentioned Listener logic.

Yes you can..for this take one MainActivty and write your menu code in that..after then all your activitys extend that MainActivity like below..
class MainActivty extend Activity{
}
class FirstActivity extend MainActivity{
}
class SecondActivity extend MainActivity{
}
Then menu will appear in your all activitys..

Yes you can create a layout and include it like this:
<include
android:id="#+id/headerLayout"
layout="#layout/login_header"
/>
It has its own class file where common functionality can be kept.

it's very easy you just create a class
class MenuActivty extend Activity{
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
((Button)findViewById(R.id.mymenu_home).setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i = new Intent(this, HomeActivity.class);
startActivity(i);
}
});
((Button)findViewById(R.id.mymenu_help).setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i = new Intent(this, HelpActivity.class);
startActivity(i);
}
});
//... same thing for the others
}
}
be careful to rename the menu "mymenu" in all the XML
and all the classes where you want to use the menu should be extended MenuActivty
and in the XML use
<include layout="#layout/menulayout "
android:id="#+id/mymenu"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
and create an XML file named menulayout where you put the layout of your menu.

Follow these steps:
Create a generic layout for menu and include it wherever you want to use it.
<include
android:id="#+id/headerLayout"
layout="#layout/login_header"
/>
Create a class CentralizedHeader. Create on constructor with one parameter of activity type.
Create a function here and initialize all views and perform all related functionality here.
public class CentralizedHeader {
private Button btnHome, btnContribute;
private Activity activity;
public CentralizedHeader(Activity activity) {
this.activity = activity;
}
public void headerActions() {
btnHome = (Button) activity.findViewById(R.id.btn_home);
btnContribute = (Button) activity.findViewById(R.id.btn_contribute);
btnHome.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(activity, MorePackagesActivity.class);
activity.startActivity(intent);
}
});
btnContribute.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(activity, ContributeActivity.class);
activity.startActivity(intent);
}
});
}
}
Create an object of this class in other activity and call its function. ie
public class MainActivity extends Activity {
private CentralizedHeader headerCentralized;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_home_tab);
headerCentralized = new CentralizedHeader(this);
headerCentralized.headerActions();
}
}

Use only one Activity that have all the menus and create Fragments for activity. Replace fragment on clicking to the menu. This is the good way to achieve your functionality as you want.

Steps to reuse function in java class:
make a Singleton class so that that instance is anywhere you can get
mention all your code in this class
use all method from this class
and if you use that layout also then just make one xml and include it in all layout where you want to add.

Related

How can I access a method from an activity and use it into another activity in Android?

I have the first class named iHave
public class iHave extends ActionBarActivity
{
//below is the instance for calling the method from the other activity.
(The name of the other activity is **iThank**)
**iThank thankYou = new iThank();**
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_i_have);
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
**//this is the method I want to access from iThank class** **strong text**
thankYou.display();
}
});
}
//The Next class is "iThank"
public class iThank extends ActionBarActivity
{
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_i_thank);
txtThank = (TextView) findViewById(R.id.textView3);
//this is the method I want to access/use from iHave Activity
public void display()
{
txtThank.setText ("Shine");
}
}
How can I use the method "public void display()" of iThank activity to the "iHave" activity? It always gives me an error of NullPointerException. Please help. Thank you very much!
How can I access a method from an activity and use it into another
activity in Android?
By creating object for other to access method from Activity is right way.
Use LocalBroadcastManager for communicating between application components.
1. Send broadcast from iHave on Button click:
#Override
public void onClick(View v)
{
Intent intent = new Intent("DISPLAY_EVENT");
LocalBroadcastManager.getInstance(v.getContext()).sendBroadcast(intent);
}
2. Register LocalBroadcastManager in iThank Activity:
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
LocalBroadcastManager.getInstance(this).registerReceiver(ReceiveMessage,
new IntentFilter("DISPLAY_EVENT"));
}
3. Create BroadcastReceiver object and call display() method in iThank Activity:
private BroadcastReceiver ReceiveMessage = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
display();
}
};
Also add null check in display method for TextView:
public void display()
{
if(txtThank !=null)
txtThank.setText ("Shine");
}
Please don't to this, it is not how activities are intended to work. You might want to have a look over the Activities Developer Guide to get started. If you want to launch a new activity (e.g. iThank) from the current foreground activity (e.g. iHave), you never instantiate the class yourself directly and always launch it using an intent. If you have data to pass along (such as a message to display), it needs to be bundled along with the intent as an extra (see same link).
Activities should never call methods on each other directly, because this requires them to have references to each other. The framework manages the life cycle of each activity independently, and those references can lead to leaks.

The constructor Intent(new View.OnClickListener(){}, Class<ChangePasswordActivity>) is undefined

Hi have error The constructor Intent(new View.OnClickListener(){}, Class) is undefined, I'm created the Util class in that class create popup layout in that layout screen logout, chanage password like created textview that text view onClick i have to call the another activity. that time its showing this error.
public class Util {
public static void initPopWindow(Activity a, Button button)
{
final Context context = a;
// popupWindow
View contentView = LayoutInflater.from(a).inflate(R.layout.my_list, null);
// popupWindow
contentView.setBackgroundColor(Color.LTGRAY);
popupWindow = new PopupWindow(contentView, 340, 249, true);
contentView.setFocusableInTouchMode(true);
popupWindow.setBackgroundDrawable(new BitmapDrawable());
popupWindow.showAtLocation(button, Gravity.TOP|Gravity.RIGHT, 2, 127);
change_passwrod_activity.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
startActivity((new Intent(this, ChangePasswordActivity.class)));
}
});
}
}
main Activity call
public void onSetting(View v) {
Util.initPopWindow(this, menubutton)
}
Normally this keyword is pointing to the current class, here your current class is Util.java.
Use activity **context** instead of **this**, because Intent need reference of activity class. It will not accept any other class reference.
startActivity((new Intent(context, ChangePasswordActivity.class)));
change_passwrod_activity.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
context.startActivity(new Intent(context, ChangePasswordActivity.class));
}
});
startActivity() is a method within Context, and not within your OnClickListener or Util class.
context.startActivity((new Intent(context, ChangePasswordActivity.class)));

Define generic method can open all activities

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);

Handle all click methods in one class?

Well lets say that I have an app that have like 50-60 buttons all around and I want to handle all click methods inside other package. How could I handle click for package app.test; class one in package app.test.clicks class clicks?
Create a class which implements OnClickListener,
public class ClickHandler implements OnClickListener
{
public void onClick(View v) {
//This method will be automatically implemented once OnClickListener is implemented.
}
}
Now set the onClickistener to your button like this,.
button.setOnClickListener(new ClickHandler());
And now inside the onClick() just do this,
public void onClick(View v) {
if(v.getId()==R.id.button)
{
//your stuff here.
}
}
If you need context object then,try v.getContext();. "v" is the parameter form the onClick().
make sure you import the package name of your ClickHandler class into your Activity.
But it would be much better if you had this as an inner class for each Activity.
public class HeaderActivity extends Activity implements OnClickListener{
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
((Button)findViewById(R.id.home)).setOnClickListener(this);
((Button)findViewById(R.id.search)).setOnClickListener(this);
((Button)findViewById(R.id.list)).setOnClickListener(this);
((Button)findViewById(R.id.filter)).setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch(v.getId()){
case R.id.home:
Intent home=new Intent(this,HomeScreen.class);
startActivity(home);
finish();
break;
case R.id.search:
Intent search=new Intent(this,SearchScreen.class);
startActivity(search);
finish();
break;
case R.id.list:
Intent list=new Intent(this,ListScreen.class);
startActivity(list);
finish();
break;
case R.id.filter:
Intent filter=new Intent(this,FilterScreen.class);
startActivity(filter);
finish();
break;
default : break;
}
}
Well I don't think it will be a great idea to implement. However you need to pass the Context to clicks class. From context object you'll be able to get to the control which has been clicked and you can write your logic accordingly.

How to navigate from one screen to another screen

How to navigate from one Activity screen to another Activity screen? In the first screen I'm having one button if I click the button it has to move to another Activity screen.
The most trivial case (called from activity):
startActivity(new Intent(this, ActivityToLaunch.class));
More details here: http://developer.android.com/guide/topics/fundamentals.html
OnClickListener onClickListener = new OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(action));
}
};
Button button = (Button) findViewById(id);
button.setOnClickListener(onClickListener);
Button x.setOnClickListener(new View.OnClickListener() {
public void onClick(View v)
{
Intent i = new Intent(y.this, Activity.class);
startActivity(i);
}
});
Here we've defined a listener for Button x. The OS will call this method and start the Activity referenced in Intent i.
Here's the official tutorial example:
http://developer.android.com/guide/tutorials/notepad/notepad-ex2.html
Button btn = (Button)findViewById(R.id.button1);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(TestActivity.this,second.class));
}
});
public void onClick(View v)
{
Intent myintent = new Intent(currentclass.this, nextactivity.class);
startActivity(myintent);
}
This task can be accomplished using one of the android's main building block named as Intents and One of the methods public void startActivity (Intent intent) which belongs to your Activity class.
An intent is an abstract description of an operation to be performed. It can be used with startActivity to launch an Activity, broadcastIntent to send it to any interested BroadcastReceiver components, and startService(Intent) or bindService(Intent, ServiceConnection, int) to communicate with a background Service.
An Intent provides a facility for performing late runtime binding between the code in different applications. Its most significant use is in the launching of activities, where it can be thought of as the glue between activities. It is basically a passive data structure holding an abstract description of an action to be performed.
Refer the official docs -- http://developer.android.com/reference/android/content/Intent.html
public void startActivity (Intent intent) -- Used to launch a new activity.
So suppose you have two Activity class and on a button click's OnClickListener() you wanna move from one Activity to another then --
PresentActivity -- This is your current activity from which you want to go the second activity.
NextActivity -- This is your next Activity on which you want to move.
So the Intent would be like this
Intent(PresentActivity.this, NextActivity.class)
Finally this will be the complete code
public class PresentActivity extends Activity {
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.content_layout_id);
final Button button = (Button) findViewById(R.id.button_id);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
Intent activityChangeIntent = new Intent(PresentActivity.this, NextActivity.class);
// currentContext.startActivity(activityChangeIntent);
PresentActivity.this.startActivity(activityChangeIntent);
}
});
}
}
This exmple is related to button click you can use the code anywhere which is written inside button click's OnClickListener() at any place where you want to switch between your activities.
final Context cont = this;
Button btnClickABC =(Button)findViewById(R.id.btnClickABC);
btnClickABC.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(cont, NextActivity.class));
}
});
Use following code..I hope this will help you.
Button button = (Button)findViewById(R.id.xxx);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent=new Intent(CurrentActivity.this,NextActivity.class);
startActivity(intent);
}
});
xxx is id from your xml of your Button.
startActivity(new Intent(this,newActivity.class));
Switching from one activity to another is really simple, but tricky for a new one.
Your next class must be defined in AndroidManifest.xml. This is tester class:
<activity
android:name=".Tester"
android:label="#string/title_activity_tester" >`enter code here`
</activity>
final Button button = (Button) findViewById(R.id.btnGo);// btnGo is id
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent i = new Intent(CurrentClass.this, Tester.class);
startActivity(i);
}
You can navigate to the next screen using these code snippets:
Kotlin
startActivity(Intent(this, LoginActivity::class.java))
Java
startActivity(new Intent(this, LoginActivity.class))
Here's a reference: Android Developers - Starting another activity
Intent intentobj=new Intent(FromActivity.this,ToActivity.class);
startActivity(intentobj);
or you can simply use
startActivity(new Intent(FromActivity.this,ToActivity.class));
For Kotlin (if you are in an activity)
buttonToClick.setOnClickListener{ startActivity(this,YourDestinationActivity::class.java)
}
If you are in a fragment
buttonToClick.setOnClickListener{
startActivity(requireActivity, YourDestinationActivity::class.java)
}
In your method fun onCreate(savedInstanceState: Bundle?) add this.
your_btn_id.setOnClickListener{
val intent = Intent(this, yourpagename::class.java)
startActivity(intent)
}
Until now if it doesn't work then, check if these two files are added or not,
import android.content.Intent
import kotlinx.android.synthetic.main.activity_otp.*
Try this code:
Button my_btn;
my_btn = findViewById(R.id.submit_btn);
my_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setContentView(R.layout.activity_2);
}
});
Button navigate;
navigate = findViewById(R.id.button);
navigate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(),"Navigate another Activity",Toast.LENGTH_LONG).show();
Intent intent = new Intent(MainActivity.this,MainActivity2.class);
startActivity(intent);
}
});
Just go to XML file and add Onclick = "opennewactivity" in button xml.
Then go to java code and create class opennewactivity you can just make it my clciking alt+Enter in xml code's "opennewactivity". in that just write
Intent intent = new Intent(this, newacivity.class);
startActivity(intent);
and if you want user to not get back to first activity again then just write this
Intent intent = new Intent(this, newactivity.class);
startActivity(intent);
finish();
Cartoon_card.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
newActivity();
}
});
}
public void newActivity()
{
Intent selectClass= new Intent(getApplicationContext(), com.example.fyp.videoplayer.class);
startActivity(selectClass);
}

Categories

Resources