Can't switch between activities - java

sorry for asking dumb questions, java and Android are both new to me ;)
My problem: I can't switch between two activities in a very simple app. I tried solutions described in similar topics but it didn't work.
So this is my 1st Activity (I didn't paste the imports):
public class OneActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void OnStart(){
Button Btn = (Button)findViewById(R.id.btnNext);
Btn.setOnClickListener(new OnClickListener() {
public void onClick(View Button) {
Intent myIntent = new Intent(OneActivity.this, UserInput.class);
OneActivity.this.startActivity(myIntent);
}
});
}
}
The second Activity is very simple - it is just supposed to load a layout called userinput.xml:
public class UserInput extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.userinput);
}
}
The application part of the Manifest looks like following:
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name" >
<activity
android:name=".OneActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<activity
android:name=".UserInput"
android:label="#string/app_name" />
</activity>
</application>
When I run the app and click the button nothing happens. Where could be the problem?
// Alright, I have put the code into the onCreate() method so it now looks like following:
public class OneActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button Btn = (Button)findViewById(R.id.btnNext);
Btn.setOnClickListener(new OnClickListener() {
public void onClick(View Button) {
Intent myIntent = new Intent(OneActivity.this, UserInput.class);
OneActivity.this.startActivity(myIntent);
}
});
}
}
Now the app crashes (force close) anytime I click the Next button.

You define your onStart() function with a capital 'O'. That is why the function is never called.
Your onStart():
public void OnStart(){ ... }
How it should be:
// Note the lowercase 'o' in onStart
public void onStart(){ ... }
Also note that having an #Override above the function name when you want to override a method will help prevent making these mistakes, as Eclipse (or whatever IDE you use) will tell you that you are not actually overriding a function.

Write below code in onCreate() method:
Button Btn = (Button)findViewById(R.id.btnNext);
Btn.setOnClickListener(new OnClickListener() {
public void onClick(View Button) {
Intent myIntent = new Intent(OneActivity.this, UserInput.class);
startActivity(myIntent);
}
});
2nd correction for android manifest file:
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name" >
<activity
android:name=".OneActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity> <!-- closed here -->
<activity
android:name=".UserInput"
android:label="#string/app_name" />
</application>

You can move all the code in onCreate() and simplify like this
startActivity(new Intent(this, UserInput.class));
But I don't understand why you start another activity like this

Check it following line
Intent myIntent = new Intent(OneAvtivity.this, SecondActivity.class);
startActivity(myIntent);
Your Class name is UserIpnout and you write SecondActivity.class
Intent myIntent = new Intent(OneAvtivity.this, UserInput .class);
startActivity(myIntent);

Related

Broadcast receiver - send String between apps

I am trying to send string from app to app.
First app called "send" has only "MainActivity" class and layout:
private void sendMsg(){
final TextView msg = (TextView) findViewById(R.id.sendText);
Button snd = (Button)findViewById(R.id.sendButton);
snd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(!msg.getText().toString().trim().equals("")){
Intent intent = new Intent("Updated");
intent.setAction(Intent.ACTION_SEND);
intent.putExtra("TEXT", msg.getText().toString().trim());
intent.setType("text/plain");
intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
intent.setComponent(new ComponentName("com.example.rec","com.example.rec.broadcastReciver"));
getApplicationContext().sendBroadcast(intent);
}else{
Toast.makeText(getApplicationContext(), "Write text that You want to broadcast!", Toast.LENGTH_LONG).show();
}
}
});
}
Second app called "rec" has two classes "broadcastReciver" and "MainActivity".
MainActivity:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
zoviBroadCast();
}
private void zoviBroadCast(){
broadcastReciver brcv = new broadcastReciver();
registerReceiver(brcv,
new IntentFilter("action"));
}
}
broadcastReciver:
public class broadcastReciver extends BroadcastReceiver {
public void onReceive(Context context, Intent intent)
{
//String data = intent.getStringExtra("TEXT").trim();
if (intent != null)
{
String sIntentAction = intent.getAction();
if (sIntentAction != null && sIntentAction.equals("action"))
{
String data = intent.getStringExtra("TEXT").trim();
Toast.makeText(context, data, Toast.LENGTH_LONG).show();
}
else {
Toast.makeText(context,"Something went wrong",Toast.LENGTH_SHORT).show();
}
}
}
}
I also added lines between tag "receiver" in "AndroidManifest.xml":
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.rec">
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver
android:name=".broadcastReciver"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="action" />
</intent-filter>
</receiver>
</application>
</manifest>
What application should do is when I type something in first application and send it another over button it should "broadcast" (show) toast at second app.
My second application is not showing any data when run.
Nowadays it is essential to specify an action in intent filter of your broadcast receiver.
<receiver android:name="MyReceiver" >
<intent-filter>
<action android:name="android.intent.action.MY_ACTION">
</action>
</intent-filter>
</receiver>
When sending the broadcast, you need to set exactly the same action to the intent you send.
Intent i = new Intent();
i.setAction("android.intent.action.MY_ACTION");
context.sendBroadcast(i);
Notation of action name may be not very important to get your code working, but I recommend to give names related to the package of your sending app.
For example: "com.username.example.myApplication.ACTION_EXAMPLE"

Android app opens after a few seconds after pressing home button during splash screen

I am having an issue I can't seem to figure out the reason for.
When you launch the app, a splash screen is first displayed for 2.5 seconds before finishing and starting a new activity. If you press the home or back button during this time the app will close as normal. However after a few seconds (longer than 2.5) the app will open and start from the activity that comes after the splash screen.
Any help on why this happens is appreciated!
Here is the implementation of the Splash screen (I do however not believe anything here causes this issue as I've tried different implementations)
`public class SplashScreenActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash_screen);
Thread myThread = new Thread(){
#Override
public void run() {
try {
sleep(2500);
Intent intent = new Intent(getApplicationContext(),MainActivity.class);
startActivity(intent);
finish();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
myThread.start();`
Here's the manifest
<?xml version="1.0" encoding="utf-8"?>
<uses-permission android:name="android.permission.VIBRATE" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity
android:name=".activities.MainActivity"
android:label="#string/app_name"
android:theme="#style/AppTheme.NoActionBar"
android:launchMode = "singleInstance">
</activity>
<activity android:name=".activities.SplashScreenActivity"
android:theme="#style/Theme.AppCompat.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name=".alert.BroadCaster" >
</receiver>
<service android:name=".timer.TimerService"
android:process=":timerservice" />
</application>
It happens because you are creating a new Thread and this thread will be still alive after you put your app in background. You can change your approach using an Handler. If you need that your next Activity won't start if the splash screen is in background, you have to store the current time before the delay starts.
private static final long SPLASH_SCREEN_MS = 2500;
private long mTimeBeforeDelay;
private Handler mSplashHandler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash_screen);
// Create a new Handler.
mSplashHandler = new Handler();
}
#Override
protected void onResume() {
super.onResume();
// The first time mTimeBeforeDelay will be 0.
long gapTime = System.currentTimeMillis() - mTimeBeforeDelay;
if (gapTime > SPLASH_SCREEN_MS) {
gapTime = SPLASH_SCREEN_MS;
}
mSplashHandler.postDelayed(new Runnable() {
#Override
public void run() {
Intent intent = new Intent(SplashScreenActivity.this, MainActivity.class);
startActivity(intent);
SplashScreenActivity.this.finish();
}
}, gapTime);
// Save the time before the delay.
mTimeBeforeDelay = System.currentTimeMillis();
}
#Override
protected void onPause() {
super.onPause();
mSplashHandler.removeCallbacksAndMessages(null);
}
Just use handler instead of thread sleep like this
new Handler().postDelayed(new Runnable(){
#Override
public void run() {
Intent intent = new Intent(SplashScreenActivity.this, MainActivity.class);
startActivity(intent);
SplashScreenActivity.this.finish();
}
}, SPLASH_DURATION);
You need to implement the onStop() method, only if you want to save data and memory.

How to exit of program on android

How to exit from my app on button click in Android app?
I've tried button click event method. Tell me the code or logic for it.
java file:
Button button;
button=(Button) findViewById(R.id.exit);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
}
});
Just make a finish(); as follows :
Button button;
button=(Button) findViewById(R.id.exit);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
What does finish() do?
Call this when your activity is done and should be closed. The ActivityResult is propagated back to whoever launched you via onActivityResult().
For more information read the finish() documentation
EDIT
Add this on your manifest.xml file :
<activity
android:autoRemoveFromRecents="true"/>
If you want to avoid finish(); just call an Intent like this :
Intent i = new Intent(Intent.ACTION_MAIN);
i.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
i.addCategory(Intent.CATEGORY_HOME);
startActivity(i);
EDIT with sample
My manifest.xml
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/app_name"
android:excludeFromRecents="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
My setOnClickListener()
btn = (Button)findViewById(R.id.button);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent1 = new Intent(Intent.ACTION_MAIN);
intent1.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
intent1.addCategory(Intent.CATEGORY_HOME);
startActivity(intent1);
//finish(); it can also be done
}
});
#Override
public void onClick(View paramView)
{
finish();
moveTaskToBack(true);
}
In Android is not recommended to close/kill applications, because that is already done by OS automatically when needed. As #33go user already recommended, calling finish() in your application should be enough. But if you really want to stop the process in an easy way you can try this, from everywhere in your app:
System.exit(0);
try
android.os.Process.killProcess(android.os.Process.myPid());
Just try to double back press to exit your application. Paste this code to your activity:
private static long back_pressed;
#Override
public void onBackpressed()
{
if (back_pressed + 2000 > System.currentTimeMillis()) {
super.onBackPressed();
} else {
Toast.makeText(getBaseContext(), "Press once again to exit!", Toast.LENGTH_SHORT).show();
}
this.back_pressed = System.currentTimeMillis();
}

Android not starting other activity

I'm pretty new to Android programming, but i have never encountered this problem before. When i click the button, the emulator is just not doing anything, when it's supposed to start another activity. Here's my intent within the button:
public class StartScreen extends Activity implements OnClickListener {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_start_screen);
}
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()){
case R.id.bStartQuiz:
Intent a = new Intent(StartScreen.this, QuizMenu.class);
startActivity(a);
break;
Here follows some more cases which are not defined yet.
onCreate method from the class i try to start:
public class QuizMenu extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.categories);
Here is the manifest:
<activity
android:name="com.ultimatequiz.StartScreen"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="com.ultimatequiz.QuizMenu"
android:label="#string/app_name" >
<intent-filter>
<action android:name="com.ultimatequiz.QuizMenu" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
</application>
What i really don't understand is that i get no errors in the log. It's just not "responding", but the button do change into state_pressed.
If I understood correctly you want to open a new activity by clicking a Button. Then all you have to do is to have a Button in your activity_start_screen.xml:
<Button
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:id="#+id/your_button"/>
After that you have to add this in your StartScreen:
public class StartScreen extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_start_screen);
Button button = (Button) findViewById(R.id.your_button);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent activityChangeIntent = new Intent(StartScreen.this,QuizMenu.class);
StartScreen.this.startActivity(activityChangeIntent);
}
});
and only this in your manifest:
<activity
android:name="com.ultimatequiz.StartScreen"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="com.ultimatequiz.QuizMenu"
android:label="#string/app_name"/>
I dont know if your case works well.Try this.
public class StartScreen extends Activity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_start_screen);
Button myBtn = (Button) findViewById(R.id.btn);
myBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent a = new Intent(StartScreen.this, QuizMenu.class);
startActivity(a);
}
});
}
}
I always use this way, I find it easy to handle.
if you got your layout defined onlick delete it
Try to do a function for it :
public static void LaunchIntent(){
Intent a = new Intent(StartScreen.this, QuizMenu.class);
startActivity(a);
and in the click listener call the function :
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()){
case R.id.bStartQuiz:
LaunchIntent();
break;
}

Intent issue (display new form) Android

Ok I've been looking around for hours. I've tried just about everything and I'm not sure what is going on but I'm getting the issue where it can't find the activity. The activity is in my manifest file. I've tried with .ActivityName and com...ActivityName. I've saved, I've cleaned, I've closed/opened eclipse. It just can't seem to find it. Here's code, maybe I'm missing something?
Manifest file:
<activity android:name=".Activity2"></activity>
Listener in MainActivity:
View.OnClickListener test = new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this,Activity2.class);
startActivity(intent);
}
};
Activity2:
public class Activity2 extends Activity {
ImageButton btnTest;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// TODO Auto-generated method stub
btnTest= (ImageButton)findViewById(R.id.btnDepressed);
btnTest.setOnClickListener(GoTest);
}
...etc.
I've read so many articles on this from here and other sites. I've watched videos.. I simply don't see what I'm doing wrong. The activity is defined in the manifest, I've tried the intent with the above code, as well as with:
new Intent("com.blah.blah.Activity2");
Neither is working. Any ideas?
try this
<activity android:name=".Activity2"
android:label="#string/app_name">
<intent-filter>
<action android:name="com.blah.blah.Activity2" />
</intent-filter>
</activity>
from activity code you have to do some thing like this
Intent intent = new Intent();
intent.setAction("com.blah.blah.Activity2");
intent.addCategory(Intent.CATEGORY_DEFAULT);
startActivity(intent);`
Check your package com.blah.blah for Activity2.
Inside your AndroidManifest.xml you should define your package as:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.blah.blah"
...
And define your activity as:
<activity
android:name="com.blah.blah.Activity2">
</activity>
OR
<activity
android:name=".Activity2">
</activity>

Categories