[Q] Open another screen on button click - Java for Android App Development

Hello, I'm extremely new to both android application developing, and this forum.
I am trying to open another screen ( activity ) when a button ( readyButton ) on the splash screen is pressed. I've tried at least ten different times with different tutorials to no avail, this is my current code which didn't work, and instead forces the app to crash.
Code:
public class MainActivity extends Activity {
// Called when the activity is first created.
[user=439709]@override[/user]
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
OnClickListener listener = new OnClickListener() {
[user=439709]@override[/user]
public void onClick(View v) {
Intent intent = new Intent("SecondActivity");
startActivity(intent);
}
};
Button btn = (Button) findViewById(R.id.readybutton);
btn.setOnClickListener(listener);
}
}
Please help.
The button's name is 'readybutton'
the second activity name is 'SecondActivity'
also, where am I supposed to put this code into the java class? Here is how it is currently set up:
Code:
package com.unchat;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.view.View.OnClickListener;
// Default Items
public class FirstActivity extends Activity {
[user=439709]@override[/user]
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
}
/** New button code start */
public class MainActivity extends Activity {
// Called when the activity is first created.
[user=439709]@override[/user]
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
OnClickListener listener = new OnClickListener() {
[user=439709]@override[/user]
public void onClick(View v) {
Intent intent = new Intent("SecondActivity");
startActivity(intent);
}
};
Button btn = (Button) findViewById(R.id.readybutton);
btn.setOnClickListener(listener);
}
}
/** new button code end */
[user=439709]@override[/user]
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.my, menu);
return true;
}
[user=439709]@override[/user]
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);
}
}
// End of Default Items

incorrectly announces intent
Try like this.
Code:
Intent intent = new Intent(this, SecondActivity.class) ;
startActivity(intent);
and check whether your Listener

1. you need to use the full name of your activity, including the package name.
2. you need to declare the activity in your AndroidManifest.xml file before calling it.

rhmsoft said:
2. you need to declare the activity in your AndroidManifest.xml file before calling it.
Click to expand...
Click to collapse
Unless he want's to run an activity that's not his, like opening the contact list, but I think you're right in assuming he's looking to launch a second one of his own activities.

bornander said:
Unless he want's to run an activity that's not his, like opening the contact list, but I think you're right in assuming he's looking to launch a second one of his own activities.
Click to expand...
Click to collapse
I thought you had to declare all your activities in the manifest?

Log
Post the error log please

Related

last tempt at asking for help

Ok all i have tried for weeks now to get a simple webview app sorted. i have managed to get this up on the market but it needs a few more features like menu for refresh back forward etc.
It seems nobody really wants to helps so how much will it cost me for you to help with it?
explain a little more, you after someone to code it for you or design the ui ?
Well basically I got a basic webview made from tutorials, but that is about as far as my skills go. I need a few more features like options menu, stop the back button exiting app and go back a page instead and also if possible but not essential change loading bar for loading circle which spins in middle if screen while loading. I have tried to ask for help with what code I need and where to put it but no luck. I pretty much need it coded or at least to be told what code and exactly where in my code I need to fit it in.
Sent from my Desire HD using XDA App
Where have you tried asking? Tackle one issue at a time, and post some example code.
StackOverflow is a great site for programming questions and you should get some good answers there.
But before posting make sure you search first.
The back button shouldnt exit the app if there is a activity that was displayed before it.
cyberpedz said:
Ok finally i have a running webview in the market what i would like to do now is add a soft menu for a back, refresh and forward button what code do i need and where would i put it in my java below?
Code:
package com.windowcleaningforums;
import android.app.Activity;
import android.os.Bundle;
import android.view.Window;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class windowcleaningforums extends Activity
{
final Activity activity = this;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
this.getWindow().requestFeature(Window.FEATURE_PROGRESS);
setContentView(R.layout.main);
WebView webView = (WebView) findViewById(R.id.WebView);
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView view, int progress)
{
activity.setTitle(" Loading...");
activity.setProgress(progress * 100);
if(progress == 100)
activity.setTitle(R.string.app_name);
}
});
webView.setWebViewClient(new WebViewClient() {
@Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl)
{
// Handle the error
}
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url)
{
view.loadUrl(url);
return true;
}
});
webView.loadUrl("http://www.windowcleaningforums.co.uk");
}
}
Click to expand...
Click to collapse
Sent from my Desire HD using XDA App
Sent from my Desire HD using XDA App
I found this tutorial after a quick google search - http://kahdev.wordpress.com/2008/11/25/building-a-menu-for-your-android-v10-r1-app/
It seems quite simple to follow. Let me know if you have any issues and I try give you an example for your code tonight.
Ok I have edited your code to add a menu, and also to set the back button of the phone to go back to the previous page in the webview, instead of previous activity.
I found the code for this here
I have commented bits of the code so hopefully its understandable.
If you have any questions or it doesn't work let me know.
Don't just take what I have done and use it (although you can). Go through it and make sure you understand what I have done. That's the only way you will learn app development.
Code:
package com.windowcleaningforums;
import android.app.Activity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.Window;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class windowcleaningforums extends Activity {
final Activity activity = this;
//DECLARE webview variable outside of onCreate function so we can access it in other functions (menu)
public WebView webView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.getWindow().requestFeature(Window.FEATURE_PROGRESS);
setContentView(R.layout.main);
webView = (WebView) findViewById(R.id.WebView);
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView view, int progress) {
activity.setTitle(" Loading...");
activity.setProgress(progress * 100);
if (progress == 100)
activity.setTitle(R.string.app_name);
}
});
webView.setWebViewClient(new WebViewClient() {
@Override
public void onReceivedError(WebView view, int errorCode,
String description, String failingUrl) {
// Handle the error
}
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
});
webView.loadUrl("http://www.windowcleaningforums.co.uk");
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
//Add menu items, second value is the id, use this in the onOptionsItemSelected
menu.add(0,1, 0, "Back");
menu.add(0, 2, 0, "Forward");
return true;
}
@Override
public boolean onOptionsItemSelected (MenuItem item){
switch (item.getItemId()){
//If the ID equals 1 , go back
case 1:
webView.goBack();
return true;
//If the ID equals 2 , go forward
case 2 :
webView.goForward();
return true;
}
return false;
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK) && webView.canGoBack()) {
webView.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}
}
I have seen these tutorials but my problem is I don't know how to fit it into my webview where should I add this in my code
Sent from my Desire HD using XDA App
Have a look at the code I posted.
What we are basically doing is adding new functions (or methods) inside our activity class. When I first started app development I also got confused as to where to add things.
These new methods override methods built into the activity, so we don't want to put them inside our onCreate method (where everything goes for setting up the activity, and where all your current code resides).
So we put them at any position after the closing brace of our onCreate. I've put them at the end.
I also moved the declaration of the webView variable to outside the onCreate method, so we can access it in the other functions we added.
Thank you so much I will look at this properly when I next get chance on my pc. thanks again for the help and taking the time to explain.
Sent from my Desire HD using XDA App
Thank you have have looked over the code and even added another button!
I have also added icons for each menu item after looking over some other code but not sure if i have done it correctly. they dont show untill the menu item has been clicked once. how can i get them to show right away? i put the images in res/drawable and called then in the code below, is this the correct way to do it?
Code:
package com.windowcleaningforums;
import android.app.Activity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.Window;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class windowcleaningforums extends Activity {
final Activity activity = this;
//DECLARE webview variable outside of onCreate function so we can access it in other functions (menu)
public WebView webView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.getWindow().requestFeature(Window.FEATURE_PROGRESS);
setContentView(R.layout.main);
webView = (WebView) findViewById(R.id.WebView);
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView view, int progress) {
activity.setTitle(" Loading...");
activity.setProgress(progress * 100);
if (progress == 100)
activity.setTitle(R.string.app_name);
}
});
webView.setWebViewClient(new WebViewClient() {
@Override
public void onReceivedError(WebView view, int errorCode,
String description, String failingUrl) {
// Handle the error
}
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
});
webView.loadUrl("http://www.windowcleaningforums.co.uk");
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
//Add menu items, second value is the id, use this in the onOptionsItemSelected
menu.add(0,1, 0, "Back");
menu.add(0, 2, 0, "Forward");
menu.add(0, 3, 0, "Refresh");
return true;
}
@Override
public boolean onOptionsItemSelected (MenuItem item){
switch (item.getItemId()){
//If the ID equals 1 , go back
case 1:
webView.goBack();
item.setIcon(R.drawable.back);
return true;
//If the ID equals 2 , go forward
case 2 :
webView.goForward();
item.setIcon(R.drawable.forward);
return true;
//If the ID equals 3 , go back
case 3:
webView.reload();
item.setIcon(R.drawable.refresh);
return true;
}
return false;
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK) && webView.canGoBack()) {
webView.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}
}
Comments below (marked -->), I'm not going to give you the answer, you need to understand why more that how.
Code:
package com.windowcleaningforums;
import android.app.Activity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.Window;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class windowcleaningforums extends Activity {
final Activity activity = this;
//DECLARE webview variable outside of onCreate function so we can access it in other functions (menu)
public WebView webView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.getWindow().requestFeature(Window.FEATURE_PROGRESS);
setContentView(R.layout.main);
webView = (WebView) findViewById(R.id.WebView);
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView view, int progress) {
activity.setTitle(" Loading...");
activity.setProgress(progress * 100);
if (progress == 100)
activity.setTitle(R.string.app_name);
}
});
webView.setWebViewClient(new WebViewClient() {
@Override
public void onReceivedError(WebView view, int errorCode,
String description, String failingUrl) {
// Handle the error
}
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
});
webView.loadUrl("http://www.windowcleaningforums.co.uk");
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
//Add menu items, second value is the id, use this in the onOptionsItemSelected
menu.add(0,1, 0, "Back");
menu.add(0, 2, 0, "Forward");
menu.add(0, 3, 0, "Refresh");
//--> Here you have finished configuring the menu
return true;
}
@Override
public boolean onOptionsItemSelected (MenuItem item){
// -->This is called when you select/tap a menu item (look at the method name)
switch (item.getItemId()){
//If the ID equals 1 , go back
case 1:
webView.goBack();
// --> Hence this happens _after_ you have tapped on the back menu item
item.setIcon(R.drawable.back);
return true;
//If the ID equals 2 , go forward
case 2 :
webView.goForward();
item.setIcon(R.drawable.forward);
return true;
//If the ID equals 3 , go back
case 3:
webView.reload();
item.setIcon(R.drawable.refresh);
return true;
}
return false;
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK) && webView.canGoBack()) {
webView.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}
}
As SilentMobius' comments pointout, you need to set your icons in the onCreateOptionsMenu, not the onOptionsItemSelected.
That's why they are only showing when you select the button.
Ah great thanks i figured it, didn't want to be given correct code just you giving the correct info to sort my self is good i know these are most likely simple things but nobody learns unless they ask questions thanks again.
Check my apps out in the market Luvdroid and window cleaning forums
Would you mind sharing your back, forward and refresh icons with me? I'm looking for something very clean and standardized for use on 12 webview apps for the some of the local municipalities.
SilentMobius said:
Comments below (marked -->), I'm not going to give you the answer, you need to understand why more that how.
Code:
package com.windowcleaningforums;
import android.app.Activity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.Window;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class windowcleaningforums extends Activity {
final Activity activity = this;
//DECLARE webview variable outside of onCreate function so we can access it in other functions (menu)
public WebView webView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.getWindow().requestFeature(Window.FEATURE_PROGRESS);
setContentView(R.layout.main);
webView = (WebView) findViewById(R.id.WebView);
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView view, int progress) {
activity.setTitle(" Loading...");
activity.setProgress(progress * 100);
if (progress == 100)
activity.setTitle(R.string.app_name);
}
});
webView.setWebViewClient(new WebViewClient() {
@Override
public void onReceivedError(WebView view, int errorCode,
String description, String failingUrl) {
// Handle the error
}
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
});
webView.loadUrl("m.xxx.co.jp");
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
//Add menu items, second value is the id, use this in the onOptionsItemSelected
menu.add(0,1, 0, "Back");
menu.add(0, 2, 0, "Forward");
menu.add(0, 3, 0, "Refresh");
//--> Here you have finished configuring the menu
return true;
}
@Override
public boolean onOptionsItemSelected (MenuItem item){
// -->This is called when you select/tap a menu item (look at the method name)
switch (item.getItemId()){
//If the ID equals 1 , go back
case 1:
webView.goBack();
// --> Hence this happens _after_ you have tapped on the back menu item
item.setIcon(R.drawable.back);
return true;
//If the ID equals 2 , go forward
case 2 :
webView.goForward();
item.setIcon(R.drawable.forward);
return true;
//If the ID equals 3 , go back
case 3:
webView.reload();
item.setIcon(R.drawable.refresh);
return true;
}
return false;
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK) && webView.canGoBack()) {
webView.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}
}
Click to expand...
Click to collapse

[Q] how to change the starting activity

Hi there,
I would like some advice on what I should look for if I want to implement the following basic scenario:
the app starts with an activity (call it Activity_1) which contains a button
on clicking the button, takes me to a different activity (call it Activity_2)
next time i start the app, it takes me directly to Activity_2
and Activity_1 won't be seen again
So how can I change the startup activity?
What's happening is that Android is not closing your app in between starts, it's only backgrounding it. One thing you could do is to override the onResume() method in your Activity_2 to call finish() if for instance you have set some variable, let's call it appPaused and it would act just like you had pressed the back button (which will also take you back to Activity_1).
Like below:
Code:
package com.test.example;
import android.app.Activity;
import android.os.Bundle;
public class Activity_2 extends Activity
{
boolean appPaused = false;
[user=439709]@override[/user]
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
}
[user=439709]@override[/user]
public void onPause()
{
appPaused = true;
}
[user=439709]@override[/user]
public void onResume()
{
if(appPaused)
finish();
}
}
thanks for the answer. i want to consider that the app is closed, like after restarting the device. i don't want it to be able to start with Activity_1 unless, let's say, i re-install the app.
i also had an idea about having a 3rd activity as the main one defined in the manifest, which on create changes to one of the other activities. but i don't know how that would be implemented. would it work?
octobclrnts said:
What's happening is that Android is not closing your app in between starts, it's only backgrounding it. One thing you could do is to override the onResume() method in your Activity_2 to call finish() if for instance you have set some variable, let's call it appPaused and it would act just like you had pressed the back button (which will also take you back to Activity_1).
Like below:
Code:
package com.test.example;
import android.app.Activity;
import android.os.Bundle;
public class Activity_2 extends Activity
{
boolean appPaused = false;
[user=439709]@override[/user]
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
}
[user=439709]@override[/user]
public void onPause()
{
appPaused = true;
}
[user=439709]@override[/user]
public void onResume()
{
if(appPaused)
finish();
}
}
Click to expand...
Click to collapse
Oh, I'm sorry, I misunderstood your question the first time. If you don't want an activity to be shown except for say the first time after an install (maybe it's a login screen or similar), I would in my main activity, use the SharedPreferences class to see if I have a preference set like below:
Code:
package com.test.example;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
public class Activity_Start extends Activity
{
boolean appPaused = false;
[user=439709]@override[/user]
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
if(!prefs.contains("loggedIn"))
{
//run activity only if never run before
startActivity(new Intent(this,Activity_Logon.class));
}
else
{
//do something else every other time
}
}
}
Code:
package com.test.example;
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
public class Activity_Logon extends Activity
{
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
doLogon();
finish();
}
private void doLogon()
{
//logon code
SharedPreferences.Editor edit = PreferenceManager.getDefaultSharedPreferences(this).edit();
edit.putBoolean("loggedIn",true);
}
}
oh, ok. so from what I get SharedPreferences is a db where you can quickly save variables between sessions. great, I'll try it
octobclrnts said:
Oh, I'm sorry, I misunderstood your question the first time. If you don't want an activity to be shown except for say the first time after an install (maybe it's a login screen or similar), I would in my main activity, use the SharedPreferences class to see if I have a preference set like below:
Code:
package com.test.example;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
public class Activity_Start extends Activity
{
boolean appPaused = false;
[user=439709]@override[/user]
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
if(!prefs.contains("loggedIn"))
{
//run activity only if never run before
startActivity(new Intent(this,Activity_Logon.class));
}
else
{
//do something else every other time
}
}
}
Code:
package com.test.example;
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
public class Activity_Logon extends Activity
{
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
doLogon();
finish();
}
private void doLogon()
{
//logon code
SharedPreferences.Editor edit = PreferenceManager.getDefaultSharedPreferences(this).edit();
edit.putBoolean("loggedIn",true);
}
}
Click to expand...
Click to collapse
K-RAD said:
oh, ok. so from what I get SharedPreferences is a db where you can quickly save variables between sessions. great, I'll try it
Click to expand...
Click to collapse
That's absolutely right. You can store Strings and primitive values indexed by String keys.
octobclrnts said:
That's absolutely right. You can store Strings and primitive values indexed by String keys.
Click to expand...
Click to collapse
in the second activity, doLogon() needed an edit.apply() at the end. it works somehow, but the problem is when i press the back button, it still takes me to the first activity, and i don'twant to see it anymore after i press the button. here's my code
Code:
package com.example.onetimeactivity;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity {
[user=439709]@override[/user]
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
if(!prefs.contains("loggedIn"))
{
//run activity only if never run before
Button b = (Button) findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener() {
[user=439709]@override[/user]
public void onClick(View arg0) {
startActivity(new Intent(MainActivity.this, SecondActivity.class));
}
});
}
else
{
//do something else every other time
startActivity(new Intent(this,SecondActivity.class));
}
}
}
Code:
package com.example.onetimeactivity;
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
public class SecondActivity extends Activity
{
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
doLogon();
}
private void doLogon()
{
//logon code
SharedPreferences.Editor edit = PreferenceManager.getDefaultSharedPreferences(this).edit();
edit.putBoolean("loggedIn",true);
edit.apply();
}
}
i managed to resolve it by adding android:noHistory="true" to the manifest. however, now i really can't see the first activity, not even if i rebuild the code ))
K-RAD said:
in the second activity, doLogon() needed an edit.apply() at the end. it works somehow, but the problem is when i press the back button, it still takes me to the first activity, and i don'twant to see it anymore after i press the button. here's my code
Click to expand...
Click to collapse
K-RAD said:
in the second activity, doLogon() needed an edit.apply() at the end. it works somehow, but the problem is when i press the back button, it still takes me to the first activity, and i don'twant to see it anymore after i press the button. here's my code
Click to expand...
Click to collapse
Thanks for catching my mistake. You're right that it does need an apply (or before API level 9, commit()) call.
If you don't want to see the activity MainActivity anymore, then you have to make some changes to your structure. You should make an Activity that will be the one that always shows when the user opens the app. That activity is the one who should check the SharedPreferences for your entry. If the entry does not exist, it should call the one-time-activity. Then the one-time-activity should do it's work and save the entry and call finish() to go back to the main activity (the one you usually want to be shown). This way the activity stack will be correct for the back key functionality.
what it sounds like you want is something like a splash/logon screen
like previously said use sharedprefs.
in the splash/logon call the sharedpref and make the default false (I use booleans, you can use ints or strings):
so it would be like this
Code:
SharedPreferences settings;
SharedPreferences.Editor editor;
boolean splash;
[user=439709]@override[/user]
public void onCreate() {
settings = getSharedPreferences("settings", 0);
splash = settings.getboolean("splash", false);
editor = settings.edit();
if(splash == false){
setContentView(//the view you are using);
//do everything else you need to do
button.setonclicklistener(new OnClickListener(){
editor.putboolean("splash", true);
editor.commit();
finish();
});
}else{
//open up your second activity
finish();
}
if its a login screen, when the user clicks logout you would do the editor and change "splash" to false.

Switching to and from layouts using buttons

import android.app.*;
import android.os.*;
import android.view.*;
import android.widget.*;
public class MainActivity extends Activity
{
/** Called when the activity is first created. */
@override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button display = (Button) findViewById(R.id.button);
TextView tv = (TextView) findViewById(R.id.textView);
display.setOnClickListener( new View.OnClickListener(){
public void onClick(View p1)
{
setContentView(R.layout.main2);
// TODO: Implement this method
}
});
Button ba = (Button) findViewById(R.id.buttonBac);
ba.setOnClickListener(new View.OnClickListener(){
public void onClick(View p1)
{
setContentView(R.layout.main);
// TODO: Implement this method
}
});
}
}
Anyway, the first button works and when clicked, displays main2 makin 2 whoum d have a textview and a button that switches back 2 main but when the onclick listener whTever is aplyed to the code it wont even disllag the first layout and simply crashes... hitting the wall again
Focusedrelaxaation87 said:
import android.app.*;
import android.os.*;
import android.view.*;
import android.widget.*;
public class MainActivity extends Activity
{
/** Called when the activity is first created. */
@override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button display = (Button) findViewById(R.id.button);
TextView tv = (TextView) findViewById(R.id.textView);
display.setOnClickListener( new View.OnClickListener(){
public void onClick(View p1)
{
setContentView(R.layout.main2);
// TODO: Implement this method
}
});
Button ba = (Button) findViewById(R.id.buttonBac);
ba.setOnClickListener(new View.OnClickListener(){
public void onClick(View p1)
{
setContentView(R.layout.main);
// TODO: Implement this method
}
});
}
}
Anyway, the first button works and when clicked, displays main2 makin 2 whoum d have a textview and a button that switches back 2 main but when the onclick listener whTever is aplyed to the code it wont even disllag the first layout and simply crashes... hitting the wall again
Click to expand...
Click to collapse
You can't do a second setContentView call in an activity. What you can do is define two Layouts within a LinearLayout in the XML, set the first one to "android:visibility="gone"", the second one to "visible" and switch between them onClick
Code:
[user=439709]@override[/user]
public void onClick(View v) {
switch (v.getId()){
case R.id.btnOne:
mLayoutFirst.setVisibility(View.GONE);
mLayoutSecond.setVisibility(View.VISIBLE);
break;
case (R.id.btnTwo):
mLayoutFirst.setVisibility(View.VISIBLE);
mLayoutSecond.setVisibility(View.GONE);
break;
}
}
Zatta said:
You can't do a second setContentView call in an activity. What you can do is define two Layouts within a LinearLayout in the XML, set the first one to "android:visibility="gone"", the second one to "visible" and switch between them onClick
Click to expand...
Click to collapse
Alternatively you could use a ViewSwitcher and call it's .next() and .previous() methods. This would probably be necessary when you have more than 2 views.
octobclrnts said:
Alternatively you could use a ViewSwitcher and call it's .next() and .previous() methods. This would probably be necessary when you have more than 2 views.
Click to expand...
Click to collapse
Thanks, never heard of before. I use that method for hiding/unhiding complete ViewGroups, Buttons and what not but I'll look into that, might be more easy.
Try naming the activity other than the "main" attribute, that is only for the first or "parent" activity. You need it to be a child activity.
Sent from my HUAWEI-M835 using xda app-developers app
Cool, learned something new

[Q] Explanation of code (super function)

Code:
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle presses on the action bar items
switch (item.getItemId()) {
case R.id.action_search:
openSearch();
return true;
case R.id.action_settings:
openSettings();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
Doesn't the default case create an infinite loop if item is not action search or action settings?
saliceman said:
Code:
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle presses on the action bar items
switch (item.getItemId()) {
case R.id.action_search:
openSearch();
return true;
case R.id.action_settings:
openSettings();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
Doesn't the default case create an infinite loop if item is not action search or action settings?
Click to expand...
Click to collapse
super.onOptionsItemSelected will execute the onOptionsItemSelected function with parameter item in the "super" class your class extends from, eg Fragment/Activity/ActionBarActivity/FragmentActivity etc
Jonny said:
super.onOptionsItemSelected will execute the onOptionsItemSelected function with parameter item in the "super" class your class extends from, eg Fragment/Activity/ActionBarActivity/FragmentActivity etc
Click to expand...
Click to collapse
Thanks for your response.
With the code below what does that mean? and could you provide an example of what would happen if I selected an option other than search or settings? I am having trouble with what this all means in the grand scheme of things. I might be missing something basic so try to keep that in mind - I have little knowledge of java.
Again, thanks for your help
Code:
package com.salmanshahid.myfirstapp;
import android.support.v7.app.ActionBarActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
public class MainActivity extends ActionBarActivity {
public final static String EXTRA_MESSAGE = "com.example.myfirstapp" +
".MESSAGE";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle presses on the action bar items
switch (item.getItemId()) {
case R.id.action_search:
openSearch();
return true;
case R.id.action_settings:
openSettings();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void openSettings() {
// TODO Auto-generated method stub
}
private void openSearch() {
// TODO Auto-generated method stub
}
/** Called when the user clicks the Send button */
public void sendMessage(View view) {
// Do something in response to button
Intent intent = new Intent(this, DisplayMessageActivity.class);
EditText editText = (EditText) findViewById(R.id.edit_message);
String message = editText.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message);
startActivity(intent);
}
}
saliceman said:
I have little knowledge of java.
Click to expand...
Click to collapse
No problem, you just need to know programming in general to understand.
saliceman said:
With the code below what does that mean? and could you provide an example of what would happen if I selected an option other than search or settings?
Click to expand...
Click to collapse
replace
Code:
super
with
Code:
this
and you will get infinite loop.

App crashes when when calling a method

Hello,
So I am new to Java programming and I want to develop a small and simple app for plant identification. But the app crashes when I call a function wich set the text of a TextView. It happens in the OnCreate when I switch to a second activity. I tried to call the method with only comments in it. It also works when I create a new instance of the MainActivity class. It crashes when I try to set the text of a TextView from the MainActivity layout. It is probably a simple and basic problem, but I've been searching for my error for hours now and I still can't get it. I want to understand what's wrong and move on the the next step
I use the layout of MainActivity in Morphe activity.
Code:
package com.gobtron.cleidfougeres;
import android.content.Intent;
import android.graphics.Color;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
public class Morphe extends MainActivity {
TextView MorphTextTop;
TextView LongFrondeTextTop;
TextView FormeLimbeTextTop;
TextView DisposFrondeTextTop;
TextView DescTextTop;
TextView EspeceTextTop;
TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TopText topText = new TopText();
topText.SetText();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_morphe, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
And this is the code for the method in TopText method (located in TopText.java)
Code:
public class TopText {
public void SetText() {
MainActivity mainac = new MainActivity();
mainac.MorphTextTop.setText("eeeee");
}
}
gobtron said:
Hello,
So I am new to Java programming and I want to develop a small and simple app for plant identification. But the app crashes when I call a function wich set the text of a TextView. It happens in the OnCreate when I switch to a second activity. I tried to call the method with only comments in it. It also works when I create a new instance of the MainActivity class. It crashes when I try to set the text of a TextView from the MainActivity layout. It is probably a simple and basic problem, but I've been searching for my error for hours now and I still can't get it. I want to understand what's wrong and move on the the next step
I use the layout of MainActivity in Morphe activity.
Code:
package com.gobtron.cleidfougeres;
import android.content.Intent;
import android.graphics.Color;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
public class Morphe extends MainActivity {
TextView MorphTextTop;
TextView LongFrondeTextTop;
TextView FormeLimbeTextTop;
TextView DisposFrondeTextTop;
TextView DescTextTop;
TextView EspeceTextTop;
TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TopText topText = new TopText();
topText.SetText();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_morphe, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
And this is the code for the method in TopText method (located in TopText.java)
Code:
public class TopText {
public void SetText() {
MainActivity mainac = new MainActivity();
mainac.MorphTextTop.setText("eeeee");
}
}
Click to expand...
Click to collapse
Though you haven't posted a stack trace but I'm pretty sure a NullPointerException is being thrown in your code and this is because
Code:
public class TopText {
public void SetText() {
MainActivity mainac = new MainActivity();
mainac.MorphTextTop.setText("eeeee");
}
}
Is creating a new instance of Activity class MainActivity in which the field "MorphTextTop" is not initialized.......
All the fields in your main activity must be initialized in the onCreate method of the Activity after you have called " setContentView(R.layout.activity_main);"
The initialization would look something like
Code:
MorphTextTop = (TextView) findViewById(R.id."THIS_VIEWS_ID");
put your activity_main.xml here if you then I could give you the complete code.
What does your log say after the app crashes? And where's your actual MainActivity class?
Ok I finally found out the problem. Turns out that I was creating an instance of the TextView before setting the ContentView. Yay!

Categories

Resources