Android studio creating new intent - java

I find myself trying to create a new intent to use it for switching activities in my android app using the android studio IDE.
However, I get an error saying cannot resolve constructor when I try to do so.
Here is what my code looks like.
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Intent intent = new Intent(MainActivity.this, Menu.class);
}
});
}
}
Where Menu.class is another java class empty activity

It looks like you have imported wrong menu class. Just import the one you made and it will fix this error.
How I came to this conclusion ?
Android has Menu class inbuilt , so you must have imported that class. which will throw this error.
It is a good practice to add Activity after the name of activities. for example : MenuActivity

You could call postDelayed(#NonNull Runnable r, long delayMillis) method instead. Like below:
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Intent intent = new Intent(getBaseContext(), Menu.class);
startActivity(intent);
}
},0);

if you use explicit intent, make your code like this.
Intent i = new Intent(getApplicationContext(), Menu.class);
startActivity(i);

You can also make intent in single line,
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
startActivity(new Intent(getBaseContext(), Menu.class));
}
},1000);

Related

how I process NullPointerException on android? [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I want
when I click the button.
showing Connectingreceiver.class
but NullpointerException.
I think I not well use context.
advice for me
thanks android senior developer.
private OnClickListener mConnectOnClick = new OnClickListener() {
Context context= ConfiguredNetworkContent.this;
#Override
public void onClick(View v) {
Intent intent = new Intent(context,Connectingreceiver.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
public class Connectingreceiver extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.connecting_dialog);
}
}
Check this :
private View.OnClickListener mConnectOnClick = new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(v.getContext(), Connectingreceiver.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
v.getContext().startActivity(intent);
}
Update :
Straight forward explanation is you need a Context to start a Activity. And in Onclick() there is a passing View in which Context already existed. So, I only used it to start activity.
where this context? Context context;
fix Context context = getApplicationContext;
Try this
// Add this line after Main class
Button yourButton;
In below code don't forget to edit "yourButtonIDfromXML"
// Add below code in OnCreate method after setContentView
Button yourButton = (Button) findViewById(R.id.yourButtonIDfromXML);
yourButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(ConfiguredNetworkContent.this, Connectingreceiver.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish();
}
});
The "context" - is null. You need to do null check s to avoid Null Pointer Crash. It is the easiest exception to resolve.
If your are doing OnClick event in
Activity:- Use these lines.
public static void startReceiver() {
Intent intent = new Intent(YourActivityName.this, Connectingreceiver.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
Fragment :-
Use these lines
private OnClickListener mConnectOnClick = new OnClickListener() {
Context context;
#Override
public void onClick(View v) {
if(getActivity() != null) {
startActivity(getActivity());
}
}
And use same the startActivity() method
Also, rename your startActivity method. It is an inbuilt android method.
Prefer using camel cases for your class name. Connectingreceiver --> ConnectingReceiver.
I think I not well use context.
You have to use it if needed, But as per your codes there is no initialization of context.
First initialize your context either with ApplicationContext or ActivityContext like here
Context context = YourActivity.this;
then you can use startActivity(intent);. You don't need to write context.startActivity(intent);. only startActivity will be enough at all.
UPDATE :
Do not pass any context their just simply do
customstartActivity();
And inside customstartActivity() method
public static void customstartActivity (){
// Intent intent = new Intent(yourActivity.this, Connectingreceiver.class);
// Intent intent = new Intent(ContextWrapper.getBaseContext(), Connectingreceiver.class);
Intent intent = new Intent(getApplicationContext(), Connectingreceiver.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}

Go to an activity from anywhere

I am implementing a login system. The user needs to be redirected to the login activity from any previous activity if the token is no longer valid. I can go to the login activity with this
new Intent(CurrentActivity.this, NextActivity.class);
But this needs the current activity. I just want to go to the login activity no matter where I am. I cannot know where I am because this is inside an entirely different package.
you should probably register in the Application class to ActivityLifecycleCallbacks and if the user is not registered send them to the correct Activity.
just be sure to not endlessly send them from the login page to itself
EDIT:
adding some code and explanation.
In order to figure out if an Activity that shouldn't be alive is going through lifecycle events you'll need to implement some sort of a gate keeper. Previously it used to be some sort of static state that is kept in the Application class and holds the current activity and sometime even the stack of current activities.
This was far from a complete solution and had issues due to different tasks and even isolated procesies.
In API 14 Android introduced the Activity lifecycle callbacks which can be passed into the method registerActivityLifecycleCallbacks int the Application class.
What you want to do basically is the following:
class ThepooshApplication extends Application {
private static sIsRegistered = false;
public static setIsRegistered(boolean isRegistered) { sIsRegistered = isRegistered; }
public void onCreate() {
registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks(){
#Override
void onActivityCreated(Activity activity, Bundle savedInstanceState){
if (!sIsRegistered && !(activity instanceof LoginActivity)) {
Intent loginIntent = new Intent(this, LoginActivity.class);
loginIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(loginIntent);
}
}
#Override
void onActivityStarted(Activity activity) { /*empty method*/ }
#Override
void onActivityResumed(Activity activity) { /*empty method*/ }
#Override
void onActivityPaused(Activity activity) { /*empty method*/ }
#Override
void onActivityStopped(Activity activity) { /*empty method*/ }
#Override
void onActivitySaveInstanceState(Activity activity, Bundle outState) { /*empty method*/ }
#Override
void onActivityDestroyed(Activity activity) { /*empty method*/ }
});
}
}
You must add FLAG_ACTIVITY_NEW_TASK flag to your intent
myIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Try some like this
Intent i = new Intent();
i.setClass(this,TestActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);
Replace TestActivity.class for your target activity

How to update Activity from thread started in another activity?

I have a Main activity and after click on button I start thread (but the thread is hidden in library and I have only callback in Main activity.
Now I want to start another activity (call A) where I want to put results from the thread.
Below is simplified code:
public class Main extends Activity {
XManager.ResultsCallback xResultsCallback = new XManager.ResultsCallback() {
// the method is called every 10 sec.
#Override
public void onResult(ArrayList<String> texts) {
}
};
XManager xManager = new xManager(xResultsCallback);
View.OnClickListener onClick = new View.OnClickListener() {
#Override
public void onClick(View arg0) {
XManager.start();
Intent i = new Intent(Main.this, A.class);
startActivity(i);
}
};
}
I want to update the content of A activity each time when onResult() method is called. How to do that?
Use LocalBroadcastManager,
In your Main Activity create function :
private void sendResult() {
Log.d("sender", "Broadcasting message");
Intent intent = new Intent("custom-event-name");
// You can also include some extra data.
intent.putExtra("message", "This is my result!");
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}
and add BroadcastReceiver in your A Activity
private BroadcastReceiver onResult= new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Log.d("jazzy","onReceive called");
}
};
add on OnCreate
#Override
public void onCreate(Bundle savedInstanceState) {
// Register to receive messages.
LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver,
new IntentFilter("custom-event-name"));
}
add onDestroy
#Override
protected void onDestroy() {
LocalBroadcastManager.getInstance(this).unregisterReceiver(mMessageReceiver);
super.onDestroy();
}
I have a suggestion that you should do as follows:
Start Your Activity A on button click
Inside Activity A declare your XManager instance with a callback present in A itself
Then start your XManager as XManager.start(); that way you would be getting all the callbacks in your desired activity.
Have a great day!
I think if you want to decouple the logic, beside you can use the Android BroadcastReceiver, the another flexible choice is to use the Bus
And you can integrate it with gradle easily
dependencies {
compile 'com.squareup:otto:+'
}

Android: How do you go to another activity on click?

I'm trying to move onto the third activity in a sequence.
Going from the main activity to the second one works fine but when I try to go to the third activity from the second I the application crashes.
Here's my code for the second activity:
package com.example.helloandroid;
import android.app.Activity;
//other imports here
public class Game extends Activity implements OnClickListener {
private static final String TAG = "Matrix";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.matrix);
View doneButton = findViewById(R.id.done_button);
doneButton.setOnClickListener(this);
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.done_button:
Intent k = new Intent(this, GameTwo.class);
startActivity(k);
//finish();
break;
}
}
}
And the code for the third activity:
package com.example.helloandroid;
import android.app.Activity;
//other imports here
public class GameTwo extends Activity {
private static final String TAG = "Matrix";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.matrixtwo);
View donetwoButton = findViewById(R.id.donetwo_button);
}
}
Try the following code in the switch:
try {
Intent k = new Intent(Game.this, GameTwo.class);
startActivity(k);
} catch(Exception e) {
e.printStackTrace();
}
Tell me is this helpful.....
Intent k = new Intent(Game.this, GameTwo.class);
startActivity(k);
This works, but you also want to make sure that you specify this in your manifest.
Try this
Intent intent = new Intent(getApplicationContext(), GameTwo.class);
startActivity(intent);
Be sure to have the three Activities declared in the manifest. Is a common error to create the Activity and not declare it.
Call the new Activity using:
Intent k = new Intent(Game.this, GameTwo.class);
startActivity(k);
It's a long shot but...
Your problem could also be caused by a NullPointerException
which is thrown if donetwo_button isn't declared in matrixtwo.xml...
(Copy-paste errors are quite common)

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