I am trying to get a method from the file Duality.java to be run in Min.Java when a button is clicked. Below are the two files and what I am currently trying to do, which is not working. How do I get the method duality() to run when the button is clicked within Min.java?
Duality.java
package com.android.control;
import android.util.Log;
import com.map.AppName.R;
public class duality {
public void duality(){
Log.e("Did It Run","Yes it ran");
}
}
Min.java
package com.android.control;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import com.map.AppName.R;
public class Min extends LinearLayout {
Button but;
private final int ELEMENT_HEIGHT = 60;
private final int ELEMENT_WIDTH = 80;;
private final int TEXT_SIZE = 30;
public Min( Context context, AttributeSet attributeSet ) {
super(context, attributeSet);
this.setLayoutParams( new LinearLayout.LayoutParams( LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT ) );
LayoutParams elementParams = new LinearLayout.LayoutParams( ELEMENT_WIDTH, ELEMENT_HEIGHT );
createBut( context );
addView( but, elementParams );
}
private void createButton( Context context){
but = new Button( context );
but.setTextSize( TEXT_SIZE );
but.setText( "Go" );
but.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Duality duality = new duality();
}
});
}
}
You're only constructing an instance of the duality class - you're not calling the duality() method on it.
This might be because you wanted that method to be a constructor - but it's not, because you specified a void return type, so it's just a conventional method.
(By the way, it's conventional in Java to give classes names that start with uppercase characters. If you called your class Duality, there may be less chance that you'd get the two confused; though the problem with accidental non-constructors would still stand.)
Both Min and duality are in the com.android.control package so they should be able to see eachother without imports.
It's recommended to capitalize class names. In fact, since your method has the same name as the class it might be conflicting with the constructor name. I suggest this:
public class Duality {
public void duality(){
Log.e("Did It Run","Yes it ran");
}
}
...
but.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Duality d = new Duality();
d.duality();
}
});
make sure that the class name and file name use same case combination in names.
if u want to call the constructor, remove the void from:
public void duality()
if it is supposed to b a function and not constructor, call it using:
object_name.duality();
u r calling createBut() and have given code for createButton().. is that a mistake in copy pasting?
Related
i followed a YouTube tutorial about programming a quiz app using java android studio
in the tutorial you put the question in array list then you get randomly question from it
this can cause a problem of getting the same question many time.
How can i fix that? i thought about instead of using random i use a function to get the next item in the list but it didn't work for me.
Yhis is my code
package com.example.quiz20;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.google.android.material.bottomsheet.BottomSheetDialog;
import java.util.ArrayList;
import java.util.Random;
public class MainActivity extends AppCompatActivity {
private TextView questionTV,questionNumberTV;
private Button option1Btn,option2Btn,option3Btn,option4Btn;
private ArrayList<QuizModel> quizModelArrayList;
Random random;
int currentScore = 0 , questionAttempted = 0, currentPos;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
questionTV= findViewById(R.id.idTVQuestion);
questionNumberTV=findViewById(R.id.idTVQuestionAttempted);
option1Btn=findViewById(R.id.idBtnOption1);
option2Btn=findViewById(R.id.idBtnOption2);
option3Btn=findViewById(R.id.idBtnOption3);
option4Btn=findViewById(R.id.idBtnOption4);
quizModelArrayList = new ArrayList<>();
random = new Random();
getQuizQuestion(quizModelArrayList);
currentPos = random.nextInt(quizModelArrayList.size());
setDataToViews(currentPos);
option1Btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(quizModelArrayList.get(currentPos).getAnswer().trim().toLowerCase().equals(option1Btn.getText().toString().trim().toLowerCase())){
currentScore++;
}
questionAttempted++;
currentPos = random.nextInt(quizModelArrayList.size());
setDataToViews(currentPos);
}
});
option2Btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(quizModelArrayList.get(currentPos).getAnswer().trim().toLowerCase().equals(option2Btn.getText().toString().trim().toLowerCase())){
currentScore++;
}
questionAttempted++;
currentPos = random.nextInt(quizModelArrayList.size());
setDataToViews(currentPos);
}
});
option3Btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(quizModelArrayList.get(currentPos).getAnswer().trim().toLowerCase().equals(option3Btn.getText().toString().trim().toLowerCase())){
currentScore++;
}
questionAttempted++;
currentPos = random.nextInt(quizModelArrayList.size());
setDataToViews(currentPos);
}
});
option4Btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(quizModelArrayList.get(currentPos).getAnswer().trim().toLowerCase().equals(option4Btn.getText().toString().trim().toLowerCase())){
currentScore++;
}
questionAttempted++;
currentPos = random.nextInt(quizModelArrayList.size());
setDataToViews(currentPos);
}
});
}
private void showBottomSheet(){
BottomSheetDialog bottomSheetDialog = new BottomSheetDialog(MainActivity.this);
View bottomSheetView = LayoutInflater.from(getApplicationContext()).inflate(R.layout.score_bottom_sheet,(LinearLayout)findViewById(R.id.idLLScore));
TextView scoreTV = bottomSheetView.findViewById(R.id.idTVScore);
Button restartQuizBtn = bottomSheetView.findViewById(R.id.idBtnRestart);
scoreTV.setText("you score is \n"+currentScore + "/4");
restartQuizBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
currentPos = random.nextInt(quizModelArrayList.size());
setDataToViews(currentPos);
questionAttempted = 0;
currentScore = 0;
bottomSheetDialog.dismiss();
}
});
bottomSheetDialog.setCancelable(false);
bottomSheetDialog.setContentView(bottomSheetView);
bottomSheetDialog.show();
}
private void setDataToViews(int currentPos){
questionNumberTV.setText("Question Attempted : "+questionAttempted + "/4");
if(questionAttempted == 4){
showBottomSheet();
}else {
questionTV.setText(quizModelArrayList.get(currentPos).getQuestion());
option1Btn.setText(quizModelArrayList.get(currentPos).getOption1());
option2Btn.setText(quizModelArrayList.get(currentPos).getOption2());
option3Btn.setText(quizModelArrayList.get(currentPos).getOption3());
option4Btn.setText(quizModelArrayList.get(currentPos).getOption4());
}
}
private void getQuizQuestion(ArrayList<QuizModel> quizModelArrayList) {
quizModelArrayList.add(new QuizModel("in which year google released?","1998","2000","2004","1995","1998"));
quizModelArrayList.add(new QuizModel("What does CPU stand for?","Core Processing Unit","Central Processing Unit","Command Processing Unit","Custom Processing Unit","Central Processing Unit"));
quizModelArrayList.add(new QuizModel("what is the name of the first internet search engine?","Google","Yahoo","AOL","Archie","Archie"));
quizModelArrayList.add(new QuizModel("Which Programming language is the most widely used?","JavaScript","JAVA","Python","PHP","JavaScript"));
}
}
To avoid getting the same selection multiple times, you may want to remove it from the list after it was chosen. The syntax could look something like this:
Random rand = new Random();
ArrayList <Type> list = new ArrayList<>();
int selection = rand.nextInt(list.size() + 1);
switch(selection)
{
case X:
do the X stuff;
list.remove(X);
break;
}
The ArrayList knows what index X is at, so calling it by name will remove the entry. Using the size of the ArrayList to create the bounds for Random numbers also helps keep it dynamic
NOTE this is NOT complete code
Information/examples about preserving contents of the ArrayList using list.clone()
https://www.tutorialspoint.com/clone-an-arraylist-in-java -- An ArrayList can be cloned using the java.util.ArrayList.clone() method. This method does not take any parameters but returns a shallow copy of the specified ArrayList instance. This means that the new ArrayList created using the ArrayList.clone() method refers to the same elements as the original ArrayList but it does not duplicate the elements.
If you want to maintain a list of questions, and then some method of identifying if those have been asked, there are multiple ways to do this.
You could add a boolean value inside QuizModel which holds whether the question has been asked or not in this round, and part of the process to starting a new round of the quiz would be to ensure they are all set to false. The value can be set to true when that question has been asked, and you'd check that value before deciding to use this question or getting another.
Alternatively, you could make the problem less specific to your usecase and more generalised. - for example, all you're really asking is how to get a random number, from a set of numbers, minimising the possibility of duplicates. This is a common software problem that has been solved many many times before.
see Creating random numbers with no duplicates for example. Then you could work this solution into your question selection code.
there are two ways to get the next item in the list:
Using the index:
list.get(list.indexOf(item)+1);
list - your list of questions
item - current question
use LinkedList and its methods
You can drop the question from the array list and make the random number 1 smaller each time. You have to make sure the list can be reset and is automatically reset when it gets to 0 if you do this.
I have this file as an example of a Pet app for Android that showcases profiles of cats or dogs (courtesy of a Udemy course). this is the base file:
package com.delta.generics;
import android.app.Activity;
import android.net.wifi.p2p.WifiP2pDevice;
import android.net.wifi.p2p.WifiP2pManager;
import android.os.Bundle;
import android.service.dreams.DreamService;
import android.util.StringBuilderPrinter;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
public class GenericsActivity extends Activity {
public TextView nameTextView = null;
public TextView descriptionTextView = null;
public RatingBar ratingView = null;
public ImageView portraitView = null;
public Button nextButton = null;
private int currentSelection = 0;
// CatAdapter catAdapter;
AdoptAdapter<Cat> catAdoptAdapter;
// AdoptAdapter<Dog> dogAdoptAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_generics);
nameTextView = (TextView) findViewById(R.id.nameTextView);
descriptionTextView = (TextView) findViewById(R.id.descriptionTextView);
ratingView = (RatingBar) findViewById(R.id.ratingView);
portraitView = (ImageView) findViewById(R.id.portraitView);
nextButton = (Button) findViewById(R.id.nextButton);
nextButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showNext();
}
});
// commenting this out in favour of AdoptAdapter objects
// catAdapter = new CatAdapter(this,nameTextView,descriptionTextView,ratingView,portraitView);
// catAdapter.set(AdoptData.mCatList.get(0));
catAdoptAdapter = new AdoptAdapter<Cat>(this, nameTextView, descriptionTextView, ratingView, portraitView);
// dogAdoptAdapter = new AdoptAdapter<Dog>(this, nameTextView, descriptionTextView, ratingView, portraitView);
catAdoptAdapter.set(AdoptData.mCatList.get(0));
// dogAdoptAdapter.set(AdoptData.mDogList.get(0));
// mCatList and mDogList is an object already exists in AdoptData.java
}
public void showNext(){
int random = currentSelection;
int animal_random = 0;
animal_random = (int )(Math.random() * 2;
while(random == currentSelection){
//avoid same selection twice.
random = (int )(Math.random() * AdoptData.mCatList.size());
random = (int )(Math.random() * AdoptData.mDogList.size());
}
currentSelection = random;
Cat c = AdoptData.mCatList.get(random);
// Dog d = AdoptData.mDogList.get(random);
// commenting in favour of AdoptAdapter object
// catAdapter.set(c);
catAdoptAdapter.set(c);
// dogAdoptAdapter.set(d);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.generics, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
The issue I see is that the way this is formatted, it can only either showcase Cat or Dog profiles, but not together, and I wanted to figure out a way of how to "mix" them so both Cats and Dogs shows up randomly when pressing the "Next" button. And so I figured within the context of Java and this file, I figured I can modify the showNext() method:
public void showNext(){
int random = currentSelection;
int animal_random = 0;
animal_random = (int )(Math.random() * 2);
Log.e("animal_random", String.valueOf(animal_random));
switch(animal_random){
case 0:
while(random == currentSelection){
//avoid same selection twice.
random = (int )(Math.random() * AdoptData.mCatList.size());
}
currentSelection = random;
Cat c = AdoptData.mCatList.get(random);
catAdoptAdapter.set(c);
break;
case 1:
while(random == currentSelection){
//avoid same selection twice.
random = (int )(Math.random() * AdoptData.mDogList.size());
}
currentSelection = random;
Dog d = AdoptData.mDogList.get(random);
dogAdoptAdapter.set(d);
break;
}
}
But I feel like there are way too many "repeated lines" here. If this were in Python I would probably utilize the getAttribute() method to determine which method to use in the object based on a string match. However when I tried to use the supposed Java equivalent getMethod() i keep getting a java.lang.NoSuchMethodException error when i try to use it.
Is there a better way to go about this in Java...? Or would it require a complete restructure for this specific example?
Once you've picked any of the two alternatives below, just update the rest of your code and you'll probably see less duplication across the board since the animals will have a common ground somewhere. :-)
The interface way
Create an Animal interface that gives you access to the common things for animals in your given case, and then implement the interface in both your Dog and your Cat class. Your code in question will probably mostly be talking about Animals instead, unless you explictly need to differentiate between a Dog or a Cat in some way.
One of the neat things about this approach is that while the interface will enforce a contract, it also gives you the wiggle room for if you example want the Dog class to be able to contain stuff that the Cat shouldn't. Maybe it already does?
The enum way
Consolidate your Dog and Cat classes into a single Animal class that carries an enum field called type or something like that. Less classes (hurray?), but with the caveat that the dogs, cats and whatever future animals you add kinda have to fit into the same data structure. Depending on how much weight and meaning the actual type of animal actually has, this may or may not be a really bad idea.
I have created my own class to mimick the Snackbar, lets call it CustomSnackbar. What I am trying to achieve is to customize the snackbar and be able to call CustomSnackbar from my main activity and for the usage to be very similar to calling the standard Snackbar. For the purpose of demonstrating my example without all the bulk code, here is my CustomSnackbar class:
package com.wizzkidd.myapp.helpers;
import android.content.Context;
import android.support.design.widget.Snackbar;
import android.util.Log;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;
public class CustomSnackbar {
Context _context;
Snackbar snackbar;
public CustomSnackbar(Context context) {
this._context = context;
}
public void make(View view, CharSequence text, int duration) {
snackbar = Snackbar.make(view, "", duration);
Snackbar.SnackbarLayout snackbarLayout = (Snackbar.SnackbarLayout) snackbar.getView();
TextView textView = (TextView) snackbarLayout.findViewById(android.support.design.R.id.snackbar_text);
textView.setVisibility(View.INVISIBLE); //hide the default snackbar textview
//Create my own textview instead
TextView myTextView = new TextView(_context);
myTextView.setText(text);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT); //Create layout params for some text
myTextView.setLayoutParams(params); //Apply the text layout params
snackbarLayout.addView(myTextView); //Add my text to the main snackbar layout. (Other widgets will also be added)
}
public void setAction(CharSequence text) {
snackbar.setAction(text, new View.OnClickListener() {
#Override
public void onClick(View view) {
//do something
Log.v("TAG", "You clicked the action");
}
});
}
public void show() {
snackbar.show();
}
}
In my MainActivity, I am using the class like this:
CustomSnackbar customSnackbar = new CustomSnackbar(activity);
customSnackbar.make(view, "This is my snackbar", Snackbar.LENGTH_INDEFINITE);
customSnackbar.setAction("HIDE");
customSnackbar.show();
You can see that I am using my .setAction method to pass a string/charsequence but I am unsure how to handle the onClickListener in the same call instead of handling the onClickListener inside the class
Please ignore the fact that the class may appear pointless (but this is because I have simplified it for the purpose of this question). I'm not sure that I am creating this class correctly, so any additional advice or suggestions would be appreciated. Thanks.
declare somewhere else your OnClickListener, e.g. in Activity in which you are calling your methods, and pass it to your class
final View.OnClickListener ocl = new View.OnClickListener() {
#Override
public void onClick(View view) {
//do something
Log.v("TAG", "You clicked the action");
}
}
CustomSnackbar customSnackbar = new CustomSnackbar(activity);
customSnackbar.make(view, "This is my snackbar", Snackbar.LENGTH_INDEFINITE);
customSnackbar.setAction("HIDE", ocl);
customSnackbar.show();
and inside your custom class:
public void setAction(CharSequence text, final View.OnClickListener ocl) {
snackbar.setAction(text, ocl);
}
now inside OnClickListener you may call methods from Activity
you have to provide it as parameter to your setAction method. E.g.
public void setAction(CharSequence text, final View.OnClickListener listener) {
and either pass the provided instance, or proxy the call to the other object
Do a class extends Snackbar.
Then addMouseListener(classWithExtendedSnackbar)
I am exactly not clear about your question. But,if you want to make a custom Snackbar which will display all your message, and give functionality on click of it. Then you can try this code.
just call this method to make a snackbar.
//Here I am sending one as code
showMessage("Snackbar Opened","Close",1)
//send different code based on which you can set something to be done, or identify a button click
private void showMessage(String msg, String action_name, final int code) {
progress.cancel();
final Snackbar snackbar = Snackbar.make(findViewById(android.R.id.content), msg, Snackbar.LENGTH_INDEFINITE);
snackbar.setAction(action_name, new View.OnClickListener() {
#Override
public void onClick(View v) {
clearDataForListView();
if (code == 1) {
//do something if code is one/if a particular button is clicked
//you can dismiss anwhere else also.
snackbar.dismiss();
} else if (code == 2) {
//do something if another button is pressed
snackbar.dismiss();
}
}
});
snackbar.show();
}
I wonder how Android OnClik Listener works? What Pattern is it? Observer?
I cant imagine how I can Implement it in my App! It needs to be a custom implementation because I want to do it with my Objects not with views.
So how can I achieve to call obj.setOnClickListener(new Class(){});
in my code?
I mean ok I could have a methode in my baseclass from which the derived classes implement and then just havin a static ArrayList or so. But how can I add new Classes to this List at runtime?
The definiton of this class OnClickListener(){} is strange.
How is it possible to define an existing class and overriding a method?
My Java is not that good never done this...
EDIT: THIS QUESTION IS NOT ABOUT HOW TO USE ONCLICKLISTENER. I KNOW HOW TO USE THAT...
What i want:
I want a Super Class having an implementation of a method like this:
public void setMyOnclickListener(MyOnClickListener myListener)
{
//magic code
}
and now I want to have an Object of this class lets call it
Subclass obj;
and now I want to do this:
obj.setMyOnClickLister(new MyOnClickListener()
{
//defined method at runtime
public void aDefinedMethod()
{
//here goes in some code
}
});
how can I have a method with a class as a parameter which only exist as an anonymous class?
EDIT2:
Ok I get it OnClickListener is just an Interface -.- not a class defintion
That was my confusion!!!
Each View contains ListenerInfo static class which holds callbacks, OnClickListener too actually.
How it works?
System always holds all views on screen.
When user tap on screen we have a recursive foreach cycle :
switch(event) {
...
case ON_CLICK:
process(ViewRoot);
}
void process(View view) {
for(View view : view.getChilds()) {
if(view instanceOf ViewGroup && ((ViewGroup)view).getChildCount() > 0) {
process(view);
}
if(view.getListenerInfo().mOnClickListener != null)
view.getListenerInfo().mOnClickListener.onClick(view)
}
}
When you call setOnClickListener you actually say "hey Android! here it callback. And when user make click, please use it."
View.class also have getListenerInfo method which returns ListenerInfo object.
System use this method to dispatch events.
So no Observer pattern here. It just simple check of existing callback.
you need to initialize your object (button) first
public class SomeActivity {
...
private Button subButton1, subButton2;
...
protected void onCreate(Bundle savedInstanceState) {
...
init();
}
private void init() {
subButton1 = (Subclass) findViewById(R.id.home_button1);
subButton2 = (Subclass) findViewById(R.id.home_button2);
}
// next is the onClickListener
private void init() {
...
subButton1.setOnClickListener(new MyOnClickListener() {
#Override
public void myOnClick(View v) {
System.out.println("Your own on click 1");
Toast.makeText(HomeActivity.this, "Your own on click 1", Toast.LENGTH_SHORT).show();
}
});
subButton2.setOnClickListener(new MyOnClickListener() {
#Override
public void myOnClick(View v) {
System.out.println("Your own on click 2");
Toast.makeText(HomeActivity.this, "Your own on click 2", Toast.LENGTH_SHORT).show();
}
});
}
private void methodCall() {
// some more code...
}
// Subclass
import android.content.Context;
import android.util.AttributeSet;
import android.widget.Button;
/**
* Created by roelsuntjens on 01-10-15.
*/
public class Subclass extends Button {
public Subclass(Context context) {
super(context);
}
public Subclass(Context context, AttributeSet attrs) {
super(context, attrs);
}
public Subclass(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
public Subclass(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
}
public void setOnClickListener(MyOnClickListener l) {
super.setOnClickListener(l);
}
#Override
public void setOnClickListener(OnClickListener l) {
super.setOnClickListener(l);
}
}
// MyOnClickListener
import android.view.View;
/**
* Created by roelsuntjens on 01-10-15.
*/
public abstract class MyOnClickListener implements View.OnClickListener {
public MyOnClickListener() {
}
public abstract void myOnClick(View v);
#Override
public void onClick(View v) {
myOnClick(v);
}
}
// In XML I used this:
<View3D.Subclass
android:id="#+id/home_button1"
android:layout_width="match_parent"
android:text="Button1"
android:layout_height="wrap_content" />
<View3D.Subclass
android:id="#+id/home_button2"
android:layout_width="match_parent"
android:text="Button2"
android:layout_height="wrap_content" />
You can implement onClickListener like that by implementing interface OnClickListener.
Set to your button on setOnClickListner(this) in your activity will listening the click event on the onClick method.
You can also create your on listener by declaring a private OnClickListener like that :
private OnClickListener listener = new OnClickListener() {
#Override
public void onClick(View view) {
// Click occurs, do something
}
};
Then set button.setOnClickListener(listener);
It's very easy...just in your activity_main.xml layout create a button
like this
<Button
android:id="#+id/btnTake"
android:layout_width="wrap_content"
// android:onClick="onClick" (It will automatically create the method if u use onclic)//
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
/>
Now just call the button with its id(IF u r not writing android:onClick="onClick" )
now in Main Activity do this
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnTack = (Button) findViewById(R.id.btnTakePic);
btnTack.setOnClickListener(this);
//call intent or do what u want
Now do what ever you want to do..
This is probably a duplicate, but i can't find any thing on this so here goes.
I want to call a function in a class from file B.java into A.java with the onClick. Problem is, i get an error every time I add the line in. Here is my code and I'll give the error at the bottom.
A.java
import com.example.app.B;
public class MainService extends Service
{
private CallFunc callFunc;
private Button btn;
public void onCreate()
{
callFunc = new CallFunc();
btn = new Button(this);
//Code for setOnClickListener
#Override
public void onClick(View v)
{
callFunc();
}
}
}
B.java
public class CallFunc
{
public CallFunc()
{
//Stuff to do
}
}
Error I get
The method callFunc() is undefined for the type new View.OnClickListener(){}
//you are not calling your function:
import com.example.app.B;
public class MainService extends Service
{
private CallFunc callFunc;
private Button btn;
public void onCreate()
{
callFunc = new CallFunc();
btn = new Button(this);
//Code for setOnClickListener
#Override
public void onClick(View v)
{
callFunc.callFunc();//It is a good idea to use better method names. it looks like you are calling your constructor, not a method.
}
}
}
In your CallFunc class,
public CallFunc()
{
//Stuff to do
}
means it's constructor. It get called when you create it. In here callFunc = new CallFunc();.
You can include it to onClick method.
#Override
public void onClick(View v)
{
callFunc = new CallFunc();
}
Better way is to do this is add a method to CallFunc class because method means you do something. You do your stuff in that method. Class means a object like a car. Car can be drive. so it should have dirve() method. Then car.drive() means you drive the car. :)
#Override
public void onClick(View v)
{
callFunc.someMethod();
}
What you have in your B.java is a constructor not a method. A constructor is a special case method that gets invoked when an instance of that class is created. It is used to correctly initialise and populate new instances of a class.
What you were probably trying to do is:
public class CallFunc
{
public CallFunc()
{
// this is the constructor
// initialise the class instance here
}
public void someMethod()
{
// a method you can call
// perform actions here
}
}
Then in the onCreate() of your MainService you should:
#Override
public void onClick(View v)
{
callFunc.someMethod();
}
However, you are extending Service and using UI components (Button and onClick) when a Service does not have a UI. Are you sure you didn't want to use an Activity?