Im new to app development and im having trouble adding a menu to my app. Im using eclipse. I don't get any errors but when I start the app and press the menu button on my phone nothing happens.
Code:
package com.JEB.mybills;
import android.annotation.TargetApi;
import android.app.ListFragment;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
public class ReminderListFragment extends ListFragment {
[user=439709]@override[/user]
public void onActivityCreated (Bundle savedInstanceState){
super.onActivityCreated (savedInstanceState);
setEmptyText (getResources() .getString(R.string.no_reminders));
}
private ListAdapter mAdapter;
[user=439709]@override[/user]
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
String[] items = new String[] {"Foo", "Bar", "Fizz", "Bin"};
mAdapter = new ArrayAdapter<String>(getActivity(),
R.layout.reminder_row, R.id.text1, items);
setListAdapter(mAdapter);
}
public void onListItemClick(ListView l, View v, int position, long id){
super.onListItemClick(l, v, position, id);
Intent i = new Intent(getActivity(), ReminderEditActivity.class);
i.putExtra(ReminderProvider.COLUMN_ROWID, id);
startActivity(i);
}
public void onViewCreate(Bundle savedInstanceState){
super.onViewCreated (getView(), savedInstanceState);
registerForContextMenu(getListView());
setHasOptionsMenu(true);
}
[user=439709]@override[/user]
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater){
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.list_menu, menu);
}
[user=439709]@override[/user]
public boolean onOptionsItemSelected(MenuItem item){
switch (item.getItemId()){
case R.id.menu_insert:
editReminder(0);
return true;
}
return super.onOptionsItemSelected(item);
}
[user=439709]@override[/user]
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo
menuInfo){
super.onCreateContextMenu(menu, v, menuInfo);
MenuInflater mi = getActivity().getMenuInflater();
mi.inflate(R.menu.list_menu_item_longpress, menu);
}
public void editReminder(long id){
Intent i=new Intent(getActivity(), ReminderEditActivity.class);
i.putExtra(ReminderProvider.COLUMN_ROWID, id);
startActivity(i);
}
public boolean onCrontextItemSelected(MenuItem item){
switch(item.getItemId()){
case R.id.menu_delete:
//Delete the task
return true;
}
return super.onContextItemSelected(item);
}}
jeb192004 said:
Im new to app development and im having trouble adding a menu to my app. Im using eclipse. I don't get any errors but when I start the app and press the menu button on my phone nothing happens.
Click to expand...
Click to collapse
First I have to say that using the "CODE /CODE" tags (obviously with "[ ]") would be a good idea, when posting so that it looks better
Code:
@override
public void onActivityCreated (Bundle savedInstanceState){
super.onActivityCreated (savedInstanceState);
setEmptyText (getResources() .getString(R.string.no_reminders));
}
Your not very clear but I assume, you want something to happen when you press the physical menu key on your device ? If so I don't see anything that captures the event of this key ? Or am I missing something ? If I wanted to close my app by pressing a physical menu key I would probably do something like
Code:
@Override
public boolean onKeyDown(int keycode, KeyEvent e) {
switch(keycode)
{
case KeyEvent.KEYCODE_MENU:
this.finish();
break;
}
return super.onKeyDown(keycode, e);
}
But not all devices have physical menu keys. My answer is based on assumptions and guess work of what your wanting
My phone has the menu button on the screen.(LG g flex)
Sent from my LG-LS995 using xda app-developers app
deanwray said:
Code:
@Override
public boolean onKeyDown(int keycode, KeyEvent e) {
switch(keycode)
{
case KeyEvent.KEYCODE_MENU:
this.finish();
break;
}
return super.onKeyDown(keycode, e);
}
But not all devices have physical menu keys. My answer is based on assumptions and guess work of what your wanting
Click to expand...
Click to collapse
where you have
Code:
return super.onKeyDown(keycode, e);
I get an error saying its "undefined for the type ListFragment"
jeb192004 said:
where you have
Code:
return super.onKeyDown(keycode, e);
I get an error saying its "undefined for the type ListFragment"
Click to expand...
Click to collapse
I never said your phone didn't have a menu key (I obviously assumed it did, was just saying not all do)
The error is because your inside a fragment, that while has access to Context does not have direct reference. Overriding a key is for Activity/FragmentActivity/Application context
deanwray said:
I never said your phone didn't have a menu key (I obviously assumed it did, was just saying not all do)
The error is because your inside a fragment, that while has access to Context does not have direct reference. Overriding a key is for Activity/FragmentActivity/Application context
Click to expand...
Click to collapse
So...Everything for my menu go into the activity? Not my fragment?
I been trying to learn form "Android Application Development For Dummies" and its telling me to put it all in my fragment...
Ok...I got your code to work and it exited the app but now I'm having trouble getting it to open my options menu
jeb192004 said:
Ok...I got your code to work and it exited the app but now I'm having trouble getting it to open my options menu
Click to expand...
Click to collapse
well thats unrelated, you mean you dont know in android how to open the options menu ? There are simple tutorials on it on d.android.com you should have a read, lots of good info there
Related
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
Hey guys,
I'm new to android development and have been working through the Android Development guides on Google's site. I'm using what I've learned so far to create a simple app that enables the user to press a button and enter a second screen. I'm incredibly confused at this point and any help would be much appreciated. I have a class Project001.java with a button and would like class Project002.java to be launched when Button 1 is pressed. I have main.xml providing the layout for Project001 and main2.xml providing the layout for Project002. Here is what I have so far in Project001 (which I know is wrong).
package com.smith.Project001;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import com.smith.Project002;
public abstract class Project001 extends Activity implements OnClickListener {
Button button = (Button)findViewById(R.id.Button01);
abstract void setOnClickListener(View v);
// Implement the OnClickListener callback
public void onClick(View v) {
//do something when the button is clicked
}
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Intent myIntent = new Intent();
myIntent.setClassName("com.smith.Project001", "com.smith.Project002");
startActivity(myIntent);
}}
I've been searching through the Google archives and can't seem to put all the pieces together. Thanks in advance for your help!
Try the tutorial here. The second one, called menus and intents, I think, shows starting one activity from another.
http://www.vogella.de/articles/Android/article.html
________________________________
Unrevoked forever
SkyRaider Sense 3.5
Radio 2.15.00.09.01
Try something like this in your main activity:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button startNewActivityBtn = (Button) findViewById(R.id.newactivitybtn);
startNewActivityBtn.setOnClickListener(new Button.OnClickListener() {
public void onClick (View v) {
// put your intent and start activity here; should work fine
}
});
}
Click to expand...
Click to collapse
You really don't need abstract or implements. And there is no reason to import "Project2" into "Project1". Project2 should handle all that goes on in the new window. If you need to pass data to Project2 you can do that too
Thanks for the help so far guys,
I'm still having troubles with this code (new to development and very much appreciative of your help). I've done a lot of reading and I don't think I need to use intents because I have to data to pass from Project001 to Project002. All I need is to click the button and to move from Project001 to Project 002. My problem right now is that as soon as I run the app in the emulator, I get a force close. I've been trying to find a solution but haven't been able to. I've tried to implement the method you gave me and took the entire tutorial two posts up. Here is the new code. Again, any help is much appreciated.
package com.smith.Project001;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class Project001 extends Activity implements OnClickListener {
Button button = (Button)findViewById(R.id.Button01);
void setOnClickListener(View v) {
}
// Implement the OnClickListener callback
public void onClick(View v) {
setContentView(R.layout.main2);
//do something when the button is clicked
}
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button startNewActivityBtn = (Button) findViewById(R.id.Button01);
startNewActivityBtn.setOnClickListener(new Button.OnClickListener() {
public void onClick (View v) {
// put your intent and start activity here; should work fine
}
});
}
Always look into logcat, it's REALLY helpful. Anyway, here's a couple of things I see wrong;
1) I'm not sure why you're having two layouts for one activity, just put them into one layout file
2) setContentView() needs to be in onCreate()
3) You can't call findViewById() before the layout file has been processed by setContentView()
Try this example. I think it does exactly what you want. It has two xml files (screen 1 and screen 2). When you press the button on the first screen, it displays the second screen.
http://www.warriorpoint.com/blog/2009/05/24/android-how-to-switch-between-activities/
________________________________
Unrevoked forever
SkyRaider Sense 3.5
Radio 2.15.00.09.01
Yep, that should work.
Please note that on the second Activity, a "Previous" or "Return" type button is not required; the hard Back Key on Android phones does the exact same thing as the code.
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.
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
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.