Calling an activity from a custom dialog - android

I guess this is just a simple question (I’m such a noob…)
I have this custom dialog box that has 3 buttons in it.
Now I want to call an activity from one of the buttons so
I tried this:
public class picturedialog extends Dialog implements OnClickListener {
Button Camera;
public picturedialog (Context context){
super (context);
setContentView(R.layout.picturedialog);
Camera = (Button) this.findViewById(R.id.pdButton1);
Camera.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
dismiss();
Intent myIntent = new Intent(view.getContext(), CameraActivity.class);
startActivity(myIntent);
}
});
...
}
Then the red squiggly line appears on startActivity(myIntent).
Upon hovering on it, eclipse tells me this: “The method startActivity(Intent) is undefined for the type new View.OnClickListener(){}”
Ehhh? Please orient me on how to do this properly.
Any help would be appreciated.

Suppose the name of your Activity is A, then you just do:
A.this.startActivity(myIntent);
The problem arises because "this" inside your inner class refers to the object of that inner class, when what you want is the object of the enclosing Activity. A.this will refer to that.
If you aren't enclosing this class in an Activity, then try calling the startActivity from method using the context that you passed into the method, e.g. context.startActivty(myIntent).
The startActivity method belongs to the Context class.

I am sure you are overcomplicating with subclassing from Dialog. Try to follow to the dialog tutorial - https://developer.android.com/guide/topics/ui/dialogs.html#ShowingADialog
Note that dialogs are created on the fly (in Activity.onCreateDialog()) without the need to have your own custom dialog classes. Since you set a listener being inside of the wrapping activity (if you follow the tutorial), then you are able to call startActivity(myIntent), because all the fields/methods of a wrapping class instance are available for an instance of an inner class.

Related

why am i getting error when trying to open new activity in android studio

I'm getting this error when I write the intent inside the onCreate method.
But when I write the intent inside an outer method and call it, it works.
Button click listener is an interface and you implemented it here as an anonymous class, so inside of that class this refers to that anonymous class, not your activity class, but Intent constructor needs activity class implementation, therefore as #ADITYA RANADE answered you need to change it to MainActivity.this.
However if you replace anonymous class with lambda you can avoid this:
Button button = new Button(context);
button.setOnClickListener(v -> {
Intent intent = new Intent(this, MainActivity.class);
});
Change it to MainActivity.this inside the intent
Well that is because of the place or more precisely "context" (not the androidish Context) of where you are calling it.
When you call it from the anonymously created inner class which implements the listener for a view click, so in this case the this represents something else - anonymous class.
But on the other side when you make the method e.g. openScheduleActivity() inside the activity itself, the this keyword represents the activity itself and in fact represents the androidish Context or in this particular case even the activity. So you can either stay with case that you have already had there and slightly edit it, or you can use lambda expression, or you can use the method inside the activity itself as you have already discovered.
edited case:
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, schedule.class);
startActivity(intent);
}
});
lambda expression:
button.setOnClickListener(v -> {
Intent intent = new Intent(MainActivity.this, schedule.class);
startActivity(intent);
});

How to go back from second screen to first screen

How to switch layouts? First, I have a class Main where is onCreate (setContentView(R.layout.main);) and then I call, another class with command:
setContentView(secondClass);
In this class, I draw with Canvas and this work just fine. I also create button to go back in first "class" (R.layout.main), but I don't know how to do it.
Now my program is basic a graph shower. In first class you type your function and them second class draw it. But how to go back in first class to type another function. This "back" button or arrow witch every Android phone have, send me out of program not back on insert part.
In secondClass I can't create onCreate method, but I also tried the following and they didn't work:
Intent abc = new Intent("bla.bla.bla.FIRSTCLASS");
startActivity(abc);
and
Intent abc = new Intent(SecondClass.this,FirstClass.class);
startActivity(greNaPrvoOkno);
If you want to use a custom view (as I understood, you are extending the View class), you can do it in the following way;
Consider you are showing the second class from your Main activity like this;
setContentView(new SecondClass(getApplicationContext(), MainActivity.this));
And you Second class is this (suppose);
// I am using onClickListener to go back to main view. You do whatever you like.
public class SecondClass extends View implements OnClickListener {
// This is needed to switch back to the parent activity
private Activity mParentActivity = null;
public SecondClass(Context context, Activity parentActivity) {
super(context);
mParentActivity = parentActivity;
setOnClickListener(this);
}
#Override
public void onClick(View v) {
// Set the Main view back here.
mParentActivity.setContentView(R.layout.main);
}
}
Disclaimer: This code will do what you have asked for, but may cause other problems.
As advised by #Mudassir, you should use two different activities for two screens. It will give you better control, and your code will be easy to understand and maintain.
On the Onclick event of the button you have to write finish(); that's it..
Both of your classes are Activities yes? IF so then in your second activity you will simply call finish() and your activity will close revealing your first activity again.
When I have used multiple intents in my android application, I have created a new activity through:
Intent abc = new Intent(this, SecondClass.class);
startActivity(abc);
When the button is pressed in your second class, I would then either call finish(); on the class, or create a new intent like so:
Intent abc = new Intent(this, FirstClass.class);
startActivity(abc);
However, this method has the disadvantage that if a user wanted to use the back button, they may have to scroll through many layers of activities.
You should create another activity for your second class but not just set the main activity to a new view setContentView(secondClass).
For an easier modification, You could try to set the view back to setContentView(R.layout.main) first.
You still need to configure the widgets(e.g. TextView) on it when you set it back.
You don't have to startActivity again to go back.
Just call finish() in your second activity when you want to finish the current activity and go back:
e.g. When user press the back button in your second activity
mButtonBack.setOnClickListener(new Button.OnClickListener()
{
public void onClick(View v)
{
finish();
}
}

SendBroadcast issue inside onCLickllistener

btn2=(Button) rowView.findViewById(R.id.button1);
btn2.setText("Find");
btn2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent Message1=new Intent();
Message1.setAction("map");
sendBroadcast(Message1);}
The error says the method of broadcast is undefined inside the oclicklistener. why is that?
Should be context.sendBroadcast(Intent). You can do CurrentActivity.this.sendBroadcast(Intent)
Inside of OnClickListener there is no context instance that's why it cannot execute method of Context
You've created an OnClickListener as an anonymous class. Inside of this anonymous instance, you're trying to call sendBroadcast() and the compiler is trying to find such a method in OnClickListener, but there is no such method. What you need is to reference the enclosing class, namely the Activity by doing ThisActivity.this.sendBroadcast(intent), where ThisActivity is the actual name of your Activity.
sendBroadcast can only be done under an Activity, BroadcastReceiver, or Service context, but you are trying to sendBroadcast in the onClick, which is not any of the previously mentioned contexts.
The easiest thing to do is:
CurrentActivity.this.sendBroadcast(Message1);
Another option is to create a class variable Context context and then in the onCreate (if it's an activity or service), put context = this, and then do context.sendBroadcast(Message1);. Or, if it's in a BroadcastReceiver, just do context.sendBroadcast(Message);
In Fragments
Intent signalIntent = new Intent("updateBTN");
signalIntent.putExtra("key", "value");
getActivity().sendBroadcast(signalIntent);

Starting an Android Activity from an Listener defined in an external class file

I have an Activity MyActivity with a Button MyButton.
I want to attach a MySpecialOnClickListener to MyButton.
I write MySpecialOnClickListener in an external class file.
public class MySpecialOnClickListener extends ButtonHandler implements OnClickListener {
public OnClickListenerWithSpeech (Context context)
{ super.context = context; }
#Override
public void onClick(View view) { handleClick(view); }
}
and ButtonHandler looks like this
public abstract class ButtonHandler {
protected Context context;
protected void handleClick (View view){
if (view.getid()==R.id.button_B) {
context.startActivity (new Intent(context, ActivityC.class));
}
}
}
I basically want to store all logic for Buttons in the ButtonHandler.
SO...as I said, I have the MySpecialOnClickListener defined in an external class file.
When I click MyButton I get the following fatal error.
Calling startActivity() from outside of an Activity context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want?
So I can't start an activity normally from within a non-Activity. Fair enough.
However, if I change MySpecialOnClickListener to be an inner class in 'MyActivity' it works fine. Remember 'ButtonHandler' is still an external class file. So it (where ActivityC is ultimately started from) doesn't change.
My question (finally) is: can someone explain the logic of why one is allowed and the other isn't. I presume its a scoping thing or something but I'm a bit confused. It seems the code to start the process of starting an activity has to literally be inside another Activity.
EDIT - PROBLEM SOLVED
See below. The location of the class is irrelevant. I just didn't pass in the context properly.
because the ButtonHandler 'context' field isn´t associated with any activity context. So, when you attach the MySpecialOnClickListener instance to a button you create it passing the context parametener, isn´t???
something like this:
MySpecialOnClickListener listener = new MySpecialOnClickListener(MyActivity.this);
aButton.setOnClickListener( listener );
in this way you´re constructing the Button with the correct context...
It's likely that you are not passing the Activity context to MySpecialOnClickListener. Could you show me the difference in the way you invoke the inner-class approach?
Apologies to those of you who tried to answer. It was my fault (and I didn't include the following info initially for people)
When I was passing in the context to the 'MySpecialOnClickListener' I would do:
view.setOnClickListener(new MySpecialOnClickListener(getApplicationContext()));
when I should have done:
view.setOnClickListener(new MySpecialOnClickListener(this));
So getApplicationContext() doesn't seem to get the "correct" context for the app.
Which leads me to my next question as to what getApplicationContext() actually returns :)

New Activity nullpointerexception

I have a beginners problem. Here is my situation:
I want to start a new activity from the main activity. The code to launch the new activity is found in a separate class file. I seem to be passing the wrong arguments and I am ending up in a nullpointerexception when trying to launch the new activity. The new activity launches fine when I place the code in the main activity class file, therefore the second activity and the manifest are fine. Here is a sample of my code:
In my main activity class where I instanciate the second class (THIS IS MY MAIN ACTIVITY. I OMITTED THE REST BECAUSE I DO NOT THINK IT IS RELATED TO THE PROBLEM):
Tester mytest = new Tester();
mytest.test(this);
In my second class file (THIS IS NOT AN ACTIVITY; IT IS A CLASS THAT IS INSTANTIATED IN THE ACTIVITY):
public class Tester extends Activity {
Intent myIntent;
public void test (Context context) {
myIntent = new Intent (Intent.ACTION_VIEW);
myIntent.setClass(context, newActivity.class);
thebutton.setOnClickListener(
new OnClickListener() {
public void onClick(View v) {
startActivity(myIntent);
}
}
):}
When I perform the click I receive a nullpointerexception at startactivity. Can anyone enlighten me on this please?I am sure that I am wrongly using the context.
Activities are started with Intents. Please read the Android Application Fundamentals first and try the Hello World app :)
I understood that you will use your separate Tester class at all cost ;) so I'm trying to adapt and help you out there.
First of all, don't let your class inherit from Activity. This won't help you, cause this calls will probably not have any valid context. Activity somehow implements the template pattern, providing you key method like onCreate(...), onPause(...) etc and is instantiated by the Android OS.
If you still want to use the class, you have to pass in the context. Probably you're aiming for some MVC/MVP pattern structure, anyway.
public class Tester {
private Context context;
public Tester(Context context){
this.context = context;
}
public void test () {
final Intent myIntent = new Intent(context, NewActivity.class);
//guess this comes from somewhere, hope through a findViewById method
thebutton.setOnClickListener(
new OnClickListener() {
public void onClick(View v) {
context.startActivity(myIntent);
}
}
)};
}
}
This would be a proposed solution from my side. A problem I still see here is on how you retrieve the button in that test() method. In order to have that work properly you have to retrieve it from some View class (with view.findViewByid(R.id.myButton)) or to create it dynamically and associate it with the view during the onCreate(...) of your Activity (probably using an Inflater).

Categories

Resources