Android new activity not starting - java

I wrote this code following the skeleton of Reto Meier's "Professional Android 4 Application Development" and some slide of my professor, but i can't understand why the new activity (PreferencesActivity, fully coded) is not starting and is not raising any kind of errors: in the VM it just won't do anything when i press "Preferences" in the standard android menu I created.
I added the new activity in app's manifest correctly (just name, label, theme and screen orientation).
Here's the code
public class MainActivity extends Activity implements OnClickListener, OnValueChangeListener {
static final private int MENU_PREFERENCES = Menu.FIRST+1;
...
#Override
public boolean onCreateOptionsMenu(Menu menu){
super.onCreateOptionsMenu(menu);
menu.add(0, MENU_PREFERENCES, Menu.NONE, "Preferences");
return true;
}
public boolean onOptionsitemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
switch(item.getItemId()) {
case (MENU_PREFERENCES): {
Intent i = new Intent(this, PreferencesActivity.class);
startActivity(i);
return true;
}
}
return false;
}
...
}
The only strange thing I get is this warning in Logcat
06-20 14:50:49.760: W InputManagerService(699): Window already focused, ignoring focus gain of: com.android.internal.view.IInputMethodClient$Stub$Proxy#41219950

You can use both of them
Intent i = new Intent(getApplicationContext(), PreferencesActivity.class);
Intent i = new Intent(MainActivity.this, PreferencesActivity.class);
But it's better to use 1st one because in 2nd one memory leakage problem may occour and also just add this line in your manifest file.
<activity android:name=".PreferencesActivity" />

Your Code :
Intent i = new Intent(this, PreferencesActivity.class);
startActivity(i);
return true;
Instead of this you need to pass MainActivity.this
Intent i = new Intent(MainActivity.this, PreferencesActivity.class);
startActivity(i);
return true;
Issue is Proper context is not passing so its not starting Activity.

Instead of using this you could use getApplicationContext(), it gets you the context of the application object for the currents process.
Try this....
Intent i = new Intent(getApplicationContext(), PreferencesActivity.class);
startActivity(i);
This May Help You..

You need to pass MainActivity
Intent i = new Intent(MainActivity.this, PreferencesActivity.class);
startActivity(i);
return true;
Better to use menu
#Override
public boolean onOptionsItemSelected(MenuItem item) {
Log.d(TAG, "onOptionsItemSelected()");
switch (item.getItemId()) {
case android.R.id.yourId:
finish();
return true;
case R.id.Yourid:
return true;
default:
return super.onOptionsItemSelected(item);

You can also write
startActivity(new Intent(getApplicationContext(),NextActivity.class));
write your activity name in NextActivity.class

Related

SharedPreferences. how do I make sure that the account remains the same?

I have already created users, a name and password in my database. Then the user name is passed to the next activity. And with the next activity from the menu, you can click the logout button and it should display the registration window. But nothing works for me, the "exit" button does not flip to another screen, but just goes into the same one...
mSettings = getSharedPreferences("my_storage", Context.MODE_PRIVATE);
editor = mSettings.edit();
if(mSettings.getBoolean("is_logged", true)){
startActivity(new Intent(Authorisation.this, Menu.class));
finish();
}
editor.putBoolean("is_logged", false).apply();
and after that, I pass the name and password to the editor, set the value to true. Where did I go wrong?
Boolean checkuserpass = DB.checkusernamepassword(user, pass);
if(checkuserpass == true){
Intent intent = new Intent(getApplicationContext(), Menu.class);
intent.putExtra("name", user);
NAME = user;
editor.putString(NAME, user).apply();
editor.putString("PASSWORD", pass).apply();
editor.putBoolean("is_logged", true).apply();
startActivity(intent);
The code of another menu activity. Here I am trying to pass the values to the header (username - name during registration).
#Override
public boolean onCreateOptionsMenu(android.view.Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
int id = item.getItemId();
Intent intent = new Intent(Menu.this, Authorisation.class);
Authorisation authorisation = new Authorisation();
authorisation.log_out();
startActivity(intent);
finish();
return true;
}

How can I launch a new Activity to a Fragment that is not the initial fragment?

How can I launch a new Activity to a Fragment that is not the initial fragment? For example, the following code is wrong. I want to launch the MainActivity.class AT the SecondFragment.class. Seems simple enough but cannot find an answer anywhere. All help is greatly appreciated!
public void LaunchSecondFragment(View view) {
view.startAnimation(AnimationUtils.loadAnimation(this, R.anim.image_click));
Intent intent = new Intent(this, SecondFragment.class);
startActivity(intent);
}
So, before starting an activity you have to do something like:
Intent intent = new Intent(this, MainActivity.class);
intent.putExtra("launchSecondFragment", true)
startActivity(intent)
and in your MainActivity onCreate()
if(getIntent().getBooleanExtra("launchSecondFragment", false)) {
//do fragment transaction to second fragment
} else {
//do fragment transaction to the first fragment
}
UPDATE
So, here is the clever way to do it.
First of all create enum in your MainActivity.class
public enum FragmentNames {
FIRST_FRAGMENT,
SECOND_FRAGMENT
}
then define a string constant for getting and putting this extra(also in MainActivity)
public static final String FRAGMENT_EXTRA = "fragmentExtra";
So now when you start an activity you should do it like this:
Intent intent = new Intent(this, MainActivity.class);
intent.putExtra(MainActivity.FRAGMENT_EXTRA, MainActivity.FragmentNames.SECOND_FRAGMENT);
startActivity(intent);
And catch in your MainActivity onCreate() method:
FragmentNames name = getIntent().getSerializableExtra(FRAGMENT_EXTRA);
switch(name) {
case FIRST_FRAGMENT:
//do stuff
break;
case SECOND_FRAGMENT:
//do stuff
break;
default:
//load default fragment(FirstFragment for example)
}
What else is cool about enums? You mentioned that you are using this intents to define current item of your ViewPager. Well, good news, enums have ordinal().
Basically you can do something like:
mViewPager.setCurrentItem(name.ordinal());
In this case ordinal() of the FIRST_FRAGMENT is 0 and ordinal of SECOND_FRAGMENT is 1.
Just don't forget to check for nulls :)
Cheers.
Try this to start the activity:
Intent intent = new Intent(this, MainActivity.class);
int fragmentIndex = 2;
intent.putExtra("fragment_index", fragmentIndex);
startActivity(intent);
and this for the MainActivity's onCreate
Bundle extras = getIntent().getExtras();
int fragmentIndex;
if(extras != null) {
fragmentIndex = extras.getInt("fragment_index",1);
}
switch(fragmentIndex) {
case 1:
//display fragment 1
break;
case 2:
//display fragment 2
break;
case 3:
//display fragment 3
break;
}
When user clicks button and your MainActivity opens, its onCreate() will be get called.
You should add fragment transaction in onCreate() to launch SecondFragment :
FragmentTransaction ft = getFragmentManager().beginTransaction();
SecondFragment secondFragment = new SecondFragment();
ft.replace(R.id.content_frame, secondFragment);
ft.commitAllowingStateLoss();

Error when starting new activity from menu click

I am new to android development so there is probably something simple that is wrong. If you need any more info I will be glad to give that to you. Thanks in advance.
I am trying to add a button in my navdrawer.class. This is what I have.
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
switch (item.getItemId()) {
case R.id.new_account:
Intent intent = new Intent(this, AddAccountActivity.class);
this.startActivity(intent);
break;
}
return super.onOptionsItemSelected(item);
}
}
I get an error.
since you´re into a fragment you must use:
Intent intent = new Intent(getActivity(), AddAccountActivity.class);
or
Intent intent = new Intent(getActivity().getApplicationContext(), AddAccountActivity.class);
for example see the context used in your Toast (getActivity())
Toast.makeText(getActivity(), "This Will Create A New Account.", Toast.LENGTH_SHORT).show();
You should write
Intent intent = new Intent(AddAccountActivity.this, AddAccountActivity.class);
instead of
Intent intent = new Intent(this, AddAccountActivity.class);
Am I right that this is the fragment instance? If this is the case, thats your problem. The intent constructor needs a context and an activity class to work.
Fragment does not inherit from context. You can get the underlying activity with the getActivity() method.
try this:
Intent intent = new Intent(getActivity(), AddAccountActivity.class);

Android How to prevent back button from quitting application (after home button pressed)

I have an issue whereby, the back button works fine. Unless you push the home button, then re-enter the application, then push the back button again. It then quits the App, because their is no task trail (of activities)
Here is my colleagues code, of which I am trying to fix. Android.R.id.home is the problematic soft back button, although same thing is happening with OS back button.
#Override
public boolean onOptionsItemSelected(MenuItem item) {
Intent intent;
switch (item.getItemId()) {
case android.R.id.home:
activity.finish();
return true;
case R.id.menu_paymentLocs:
intent = new Intent(activity, PaymentLocationsPage.class);
intent.addFlags(Intent.FLAG_ACTIVITY_PREVIOUS_IS_TOP);
activity.startActivity(intent);
return true;
case R.id.menu_feedback:
intent = new Intent(activity, FeedbackPage.class);
intent.addFlags(Intent.FLAG_ACTIVITY_PREVIOUS_IS_TOP);
activity.startActivity(intent);
return true;
case R.id.menu_about:
intent = new Intent(activity, AboutPage.class);
intent.addFlags(Intent.FLAG_ACTIVITY_PREVIOUS_IS_TOP);
activity.startActivity(intent);
return true;
case R.id.menu_changeconsumer:
new SelectConsumerDialogFragment().show(getFragmentManager(), "select_consumer");
return true;
case R.id.menu_logout:
intent = new Intent(activity, SplashPage.class);
myMeter.logout();
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
activity.startActivity(intent);
return true;
}
return true;
}
To prevent the back button from doing anything predefined you need to override the onbackpressed() method
try this if you are using api level 2.0 or higher
#Override
public void onBackPressed() {
// Do Here what ever you want do on back press;
}
Remove all intent.addFlags(Intent.FLAG_ACTIVITY_PREVIOUS_IS_TOP);

can I make ringtone in preferences

How can I make ringtone activity (that always appear in setting) so the user can choose her ringtone from system ringTones I googled it but I didn't find complete tutorial, I am really confused, please give me tutorial or some codes.
Also, if I want the user to choose the special ringtone to Notification in my application should i use Shared preference or preference?
I already did the Menu:
// Menu Code Part#2
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.about:
startActivity(new Intent(this, About.class));
return true;
case R.id.help:
startActivity(new Intent(this, Help.class));
return true;
case R.id.setting:
startActivity(new Intent(this, Setting.class));
return true;
default:
return super.onOptionsItemSelected(item);
}
Full code:
res/xml/preferences.xml
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<PreferenceCategory
android:title="Second Category">
<RingtonePreference
android:name="Ringtone Preference"
android:summary="Select a ringtone"
android:title="Ringtones"
android:key="ringtonePref" />
</PreferenceCategory>
</PreferenceScreen>
Preferences.class
public class Preferences extends PreferenceActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
}
}
Your code go here:
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.about:
// startActivity(new Intent(this, About.class));
return true;
case R.id.help:
startActivity(new Intent(this, Help.class));
return true;
case R.id.setting:
Intent settingsActivity = new Intent(getBaseContext(),
Preferences.class);
startActivity(settingsActivity);
return true;
default:
return super.onOptionsItemSelected(item);
}
To read these preferences from code, we should create a getPrefs() method, which we can call in the onStart() method. When we call it in the onStart() method instead of onCreate(), we can be sure that the preferences load when we have set them and returned to our main activity,
The getPrefs() method could look like this:
String ringtonePreference;
// Get the xml/preferences.xml preferences
SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(getBaseContext());
ringtonePreference = prefs.getString("ringtonePref",
"DEFAULT_RINGTONE_URI");
androidmanifest.xml
<activity
android:name=".Preferences"
android:label="#string/set_preferences">
</activity>
Yes, you can use SharedPreferences to store the URI of the ringtone the user selected. You can let the user select a ringtone using this:
Intent intent = new Intent(RingtoneManager.ACTION_RINGTONE_PICKER);
intent.putExtra(RingtoneManager.EXTRA_RINGTONE_TYPE, RingtoneManager.TYPE_NOTIFICATION);
intent.putExtra(RingtoneManager.EXTRA_RINGTONE_TITLE, "Select Ringtone");
if (mRingtoneUri != null) {
intent.putExtra(RingtoneManager.EXTRA_RINGTONE_EXISTING_URI, Uri.parse(mRingtoneUri));
} else {
intent.putExtra(RingtoneManager.EXTRA_RINGTONE_EXISTING_URI, (Uri) null);
}
startActivityForResult(intent, RINGTONE_REQUEST);
The above code will prompt the user to select a ringtone from the system. When they select one, you will need to handle the Activity result:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == RINGTONE_REQUEST && resultCode == RESULT_OK) {
Uri uri = data.getParcelableExtra(RingtoneManager.EXTRA_RINGTONE_PICKED_URI);
SharedPreferences preferences = getSharedPreferences(PREF, MODE_PRIVATE);
Editor editor = preferences.edit();
if (uri == null)
editor.putString(RINGTONE, null);
else
editor.putString(RINGTONE, uri.toString());
editor.commit();
if (uri == null)
mRingtoneUri = null;
else
mRingtoneUri = uri.toString();
}
}
}
This code will save the URI of the ringtone to SharedPreferences.

Categories

Resources