I have an application where you can select an item from a AlertDialog spinner like, but I don't know how to make my app, to memorize the selected choice, and then behave my button to this. This is what I have now:
#Override
public void onClick(View v) {
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
mp = MediaPlayer.create(getApplicationContext(), R.raw.ais);
mp.start();
Intent myIntent = new Intent(MainActivity.this, Main2Activity.class);
MainActivity.this.startActivity(myIntent);
}
}, 9000);
Intent i = new Intent();
i.setAction(Intent.ACTION_MAIN);
i.addCategory(Intent.CATEGORY_HOME);
startActivity(i);
}
});
}
And somehow to this code, I want to add my last selected item button, for example:
If ( last selected item from AlertDialog was = dance)
do the code, that I wrote above.
One way to do it is with an interface. Define an interface in your Alert Dialog fragment and instantiate it like this:
public interface MyDialogListener {
//put whatever data you want to pass as a paramenter, below I have two examples
public void onDataSelectedEvent( String action);
}
MyDialogListener myListener;
The listener will have to be instantiated in the dialog by typecasting your activity to a MyDialogListener.
You could do it like this:
myListener = (MyDialogListener) MainActivity.this;
Or even better would be to use the activity parameter in the dialog's onAttach(...) method.
We are able to do this because later, we will make your activity implement the MyDialogListener interface, which will effectively make the activity a MyDialogListener.
Put this line in the method or listener, maybe an onClick() in your alert dialog. This is for a spinner:
myListener.onDataSelectedEvent(mySpinner.getSelectedItem().toString())
Implement the interface in your Activity that receives the data like this:
public class MyActivity extends Activity
implements MyAlertDialog.MyDialogListener{
Then, in the activity receiving the data, have the interface method look like this:
#Override
public void onDataSelectedEvent(String action) {
//probably better to use a switch statement
if(action == "dance") {
// dance()
} else if(action == "stand") {
.......etc
}
}
There is a good example here: http://developer.android.com/guide/topics/ui/dialogs.html#PassingEvents
Related
I'm new to Android development and Java and I'm having troubles with Toast:
I have a MainActivity with several buttons. Each one of this starts another Activity with typical setOnclickListener method like this:
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent();
intent.setClass(getApplicationContext(), secondaryActivity.class);
startActivity(intent);
}
});
Then, inside this secondaryActivity.class I have another button that make some stuff. Inside this Activity I wanna display a Toast on button's click but it doesn't work:
secondaryActivityBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(view.getContext(),"text",Toast.LENGTH_LONG).show();
}
});
As Toast's context I've tried: getApplicationContext(), getBasecontext(), view.getContext(), mySecondaryActivityClass.this... No one of this display the Toast, I don't know where's the mistake. Supposedly, view.getContext() might work but it doesn't display anything...
MainActivity extends AppCompactActivity and mySecondaryActivity extends Activity.
You can use secondaryActivity.this like:
Toast.makeText(secondaryActivity.this,"text",Toast.LENGTH_LONG).show();
It works only on secondaryActivity class
Try this:
Toast.makeText(getActivity().getApplicationContext(),"text",Toast.LENGTH_LONG).show();
If I want to design a button that all java can use it without need to write it in every java,
what should I do?
For Example:
I design a Button.OnClickListener function to search bluetooth devices.
but another java also need to use this Button.OnClickListener function,
I don't want to write same way on two java.
ledWrite.xml:
<Button android:id="#+id/btnScan" />
<ToggleButton android:id="#+id/tBtnWrite" />
bluetoothUtils.java
// Intent request codes
private static final int REQUEST_CONNECT_DEVICE = 1;
private Button button_scan;
button_scan = (Button)findViewById(R.id.button_scan);
button_scan.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
scanbt();
}
});
private void scanbt(){
Intent serverIntent = new Intent(this, DeviceListActivity.class);
startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE);
}
then I design LedWrite.java:
private ToggleButton digitalOutBtn; //LED On/OFF
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.ledwrite);
digitalOutBtn = (ToggleButton)findViewById(R.id.tBtnWrite);
digitalOutBtn.setOnClickListener(new OnClickListener()
public void onClick(View v){
if(digitalOutBtn.isChecked()){ //sendMessage("D1"); }
else{sendMessage("D0";}
}
How can I use button_scan in LedWrite.java?
If you want to call a method defined is some other Activity on press of a button, then you can make that method as static.
Let's assume that you have a method named searchBluetooth() in MainActvity and you want to call it from SecondActivity.
Define searchBluetooth() in MainActvity like,
public static void searchBluetooth()
Call this method from SecondActivity like,
MainActivity.searchBluetooth()
If you don't want to use static because of memory consumption then try with inheritance.
Create a class CommonActivity which extends Activity class
class CommonActivity extends Activity
{
// here define your searchBluetooth method
public void searchBluetooth()
{
// your code here
}
}
If you want to make use of it in Second Activity then
class SecondActivity extends CommonActivity
{
// here you can access `searchBluetooth()` method
}
enclosure a BluetoothListener class?
public BluetoothListener implements OnClickListener {
#Override
public void onClick(View v) {
do something you want...
}
}
then invoke the class in two different class, eg,
button.setOnClickListener(new BluetoothListener());
I recently started learning android and this answer may have some error, if so, please let me know, Thanks.
I'm new to android and trying to find out how to show a new screen when the user clicks something in the menu item.
I'm using ActionbarSherlock and looking at the sample github-android app.
When the user clicks on an item in the menu, I want to show them a new screen. Github code is doing that like so:
startActivityForResult(new Intent(getActivity(), CreateGistActivity.class), GIST_CREATE);
But I've seen some code samples do:
Intent i = new Intent(getApplicationContext(), SomeActivity.class);
My code looks like this:
public class MainActivity extends SherlockActivity {
....
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.create) {
//show createactivity class
return true;
}
return true;
}
What is the right way to do ?
You can do it just like that:
public class MainActivity extends SherlockActivity {
....
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.create) {
//show createactivity class
Intent i = new Intent(MainActivity.this, SomeActivity.class);
startActivity(i);
return true;
}
return true;
}
startActivityForResult is used when you have to return some value/data to the first screen like a user selection. More here
As far as the context to use getActivity() or getApplicationContext(), I prefer to use the context of current activity MainActivity.this its more straitforward similar to documentation example
/** Called when the user clicks the Send button */
public void sendMessage(View view) {
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);
}
Inside a fragment use getSherlockActivity() instead of getActivity() as getActivity() can cause crashes to older devices.
Of course getApplicationContext() would always work and not crash but I feel that it may mess the garbage collector and do not let activities to be cleared (but not sure about it)
Just use startActivityForResult
There is no 'right' way. The Github code doesn't first declare the variable. The onther does. I believe for a menu, you normally need to declare the Intent as a local variable, if not a field.
Create an intent: Intent i = new Intent(MainActivity.this, CreateGistActivity.class);
where MainActivity is the activity you're in, and CreateGistActivity is the class you want to launch.
Then use startActivity(Intent) to launch the new activity: startActivity(i);
Or just combine them:
startActivity(new Intent(MainActivity.this, CreateGistActivity.class));
Full code:
public class MainActivity extends SherlockActivity {
....
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.create)
{
Intent i = new Intent(MainActivity.this, CreateGistActivity.class);
startActivity(i);
return true;
}
return true;
}
startActivityForResult probably isn't needed in your case, unless you're expecting to send values between the classes.
I have some dump quastion. I have some Onclick Listener:
OnClickListener listener = new OnClickListener() {
public void onClick(View myView) {
...
if (gameInfo.isWin()){
//Dialogs.showWinWindow(FifteenActivity);
}
...
}
And i want to send My main activity to outer static method to show some Dialog. If I was outside the onClickListener i write:
if (gameInfo.isWin()){
Dialogs.showWinWindow(this);
}
But in this case i will send OnClickListener. What i must write in this method to send my activity?
Quatoin 2. The same problem with restarting Activity from external method.
In mainActivity Class i use
public void restart()
{
Intent intent = getIntent();
overridePendingTransition(0, 0);
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
finish();
overridePendingTransition(0, 0);
startActivity(intent);
}
It works. But how i can use this method as "static" from external class. Something like:
Dialogs.restart(/*Some info?*/);
Thanks in advice.
When you need to pass a reference of your activity when executing code in a listener or something similar, you must do this:
OnClickListener listener = new OnClickListener() {
public void onClick(View myView) {
...
if (gameInfo.isWin()){
Dialogs.showWinWindow(FifteenActivity.this);
}
...
}
Note the FifteenActivity.this, where this will return a reference to your activity.
About question 2 you must do this:
public static void restart()
{
Intent intent = getIntent();
overridePendingTransition(0, 0);
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
finish();
overridePendingTransition(0, 0);
startActivity(intent);
}
Which means, there's no way to call restart method in this way as you wish without declare it as static method.
I am developing an Android app, this app has a dozen of Activities, each one is for a corresponding screen. Now I have this common subtitle bar on top of the screens.
this subtitle bar has a button to display an alert dialog which shows link list to go to a different screen.
I could write a same function for each activity to call the alert dialog, but that would be tedious if I want to modify them, so I created this class:
public class MenuAlertDialog extends Activity {
/*
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
}
*/
public void createMenu(final Context context){
AlertDialog.Builder dlg = new AlertDialog.Builder(context);
dlg.setTitle("menu");
String[] items = {"pageA", "pageB", "pageC", "pageD", "pageE"};
dlg.setItems(items, new DialogInterface.OnClickListener(){
#Override
public void onClick(DialogInterface dialog, int which){
switch(which){
case 0:
Intent intent = new Intent(context, MainActivity.class);
startActivity(intent);
break;
default:
break;
}
}
});
dlg.show();
}
}
and call it from each activity, like this:
MenuAlertDialog menu = new MenuAlertDialog();
menu.createMenu(this);
from inside of onCreate.
It can display the alertDialog, but whenever I press pageA link, it fails with an unexpected error.
Logcat says its a nullpointererror and the cause seems
startActivity(intent);
What am I doing wrong?
Remove the code
extends Activity
as you have no need to extend your class that you are creating since it does not rely on any activity related functionality.
Where you call startActivity(intent); replace it with
context.startActivity(intent);
You should change the class to Extends Dialog and not activity.
Also for Try this:
Check out this tutorial on how to create a custom dialog. Custom Dialog
Also Here Another Tutorial
And Here