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);
Related
Immediate Disclaimer: I am not a programmer, I've been dumped with this as part of a group project, so apologies if the code is shabby.
I've got a main activity as the start-up page with several buttons that should open different activities, three of these buttons work perfectly with opening up their specific activities (Main2Activity, MOT and Garage), but the others, with the same structure being used, just close the app instead of opening the next screen.
public void defineButtons() {
findViewById(R.id.mot_button).setOnClickListener(buttonClickListener);
findViewById(R.id.enter_button).setOnClickListener(buttonClickListener);
findViewById(R.id.garage_button).setOnClickListener(buttonClickListener);
findViewById(R.id.profile_button).setOnClickListener(buttonClickListener);
findViewById(R.id.contact_button).setOnClickListener(buttonClickListener);
findViewById(R.id.settings_button).setOnClickListener(buttonClickListener);
}
private View.OnClickListener buttonClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.mot_button:
Intent intent = new Intent(MainActivity.this, MOT.class);
startActivity(intent);
break;
case R.id.garage_button:
Intent x = new Intent(MainActivity.this, garage.class);
startActivity(x);
break;
case R.id.profile_button:
Intent a = new Intent(MainActivity.this, Profile.class);
startActivity(a);
break;
case R.id.contact_button:
Intent b = new Intent(MainActivity.this, Contact.class);
startActivity(b);
break;
case R.id.settings_button:
Intent c = new Intent(MainActivity.this, Activity_Settings.class);
startActivity(c);
break;
case R.id.enter_button:
reg_input=findViewById(R.id.reg_input);
Intent i = new Intent(MainActivity.this, Main2Activity.class);
regNo = reg_input.getText().toString();
i.putExtra("Value", regNo);
startActivity(i);
finish();
break;
This is the relevant code for it, let me know if you want to see anything else.
I'm probably being really stupid, but I'd appreciate the help.
Your app is crashing, probably because the activities your want to start aren't in the manifest. Check your manifest and make sure that all your activities are declared there.
Im making a quiz game with questions on diferent topics
For Example i have activities for these topics: Flags, Capitals, Population, Economy, Continent, etc.
And i have one single ResultActivity to obtain the Score of the quiz.
The ResultActivity has a PLAY AGAIN button.
On the FlagsActivity i have this code:
Intent intent = new Intent(getApplicationContext(),ResultActivity.class);
intent.putExtra("RIGHT_ANSWER_COUNT", score);
intent.putExtra("NAME_ACTIVITY", "FlagsActivity");
startActivity(intent);
On the CapitalActivity i have this code:
Intent intent = new Intent(getApplicationContext(),ResultActivity.class);
intent.putExtra("RIGHT_ANSWER_COUNT", score);
intent.putExtra("NAME_ACTIVITY", "CapitalActivity");
startActivity(intent);
etc.....
On the ResultActivity i have this code:
activity = getIntent().getStringExtra("NAME_ACTIVITY");
public void playAgain(View view){
if(activity.equals("FlagsActivity")){
Intent intent = new Intent(getApplicationContext(), FlagsActivity.class);
startActivity(intent);
}
if(activity.equals("CapitalActivity")){
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
}
if(activity.equals("PopulationActivity")){
Intent intent = new Intent(getApplicationContext(), PopulationActivity.class);
startActivity(intent);
}
if(activity.equals("EconomyActivity")){
Intent intent = new Intent(getApplicationContext(), EconomyActivity.class);
startActivity(intent);
}
if(activity.equals("ContinentActivity")){
Intent intent = new Intent(getApplicationContext(), ContinentActivity.class);
startActivity(intent);
}
}
Basically im sending an Intent with a String containing the name of the activity, then on the Result Activity evaluating with "if" the String = That activity name, start the activity.
What i want to do is someting like this:
On the Flags Activity:
Intent(getApplicationContext(),ResultActivity.class);
intent.putExtra(FlagsActivity.class);
startActivity(intent);
On the CapitalActivity:
Intent(getApplicationContext(),ResultActivity.class);
intent.putExtra(CapitalActivity.class);
startActivity(intent);
On the Result Activity:
activity = getIntent();
public void playAgain(View view){
Intent intent = new Intent(getApplicationContext(), activity);
startActivity(intent);
}
So that i can create as many quiz activities without having to create an "if" statement on the ResultActivity for it to work.
You can pass the class name as a string and use reflection to look up a class object for that type. Something like this:
Class classToLoad = Class.forName(getIntent().getStringExtra("NAME_ACTIVITY"));
Intent intent = new Intent(getApplicationContext(), classToLoad);
startActivity(intent);
I would pass the fully qualified class name to avoid errors.
You could pass the String of activity name to the Result activity, and get its corresponding class name using reflection:
String strActivity = "com.package.FlagsActivity";
Intent intent = new Intent(getApplicationContext(),ResultActivity.class);
intent.putExtra("activity_name", strActivity );
startActivity(intent);
String activityName = getIntent().getStringExtra("activity_name");
Class<?> myClass = Class.forName(activityName );
Intent myIntent = new Intent(getApplicationContext(), myClass);
Something like this.
In the Results Activity
public static void toActivity(Context context, final Class ActivityToOpen){
//whatever awesome code you would like to perform
Intent intent = new Intent(context, ActivityToOpen);
startActivity(intent);
}
In the originating Activity (Flags Activity for example)
ResultsActivity.toActivity(FlagsActivity.this, FlagActivity.class);
Check for typos... I kinda winged this :)
You should be able to call from any originating Activity without if statement.
When you receive the data
String activity;
Bundle bundle = getIntent().getExtras();
if (bundle != null){
activity = bundle.getString("NAME_ACTIVITY");
}
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();
I want to make the ImageView work as button, because I want it be able to click and go to another activity. Each imageView(button) should contain its own value. The problem is, I don't know how to pass the value in the imageView(button) to another activity. This is what I have tried so far:
public class ButtonClickHandler implements View.OnClickListener {
public void onClick(View view) {
String value = " ";
switch(view.getId())
{
case R.id.imageView2:
value = "5";
break;
case R.id.imageView6:
value = "10";
break;
case R.id.imageView3:
value = "30";
break;
case R.id.imageView02:
value = "50";
break;
case R.id.imageView06:
value = "100";
break;
default:
break;
}
if(view.getId()==R.id.imageView2){
//get the value from switch case and send to other activity
}
Try this way,hope this will help you to solve your problem.
public class ButtonClickHandler implements View.OnClickListener {
public void onClick(View view) {
switch (view.getId()) {
case R.id.imageView2:
Intent intent = new Intent(YourCurrentActivity.this, YourOtherActivity.class);
intent.putExtra("YourKeyName", "5");
startActivity(intent);
break;
case R.id.imageView6:
Intent intent = new Intent(YourCurrentActivity.this, YourOtherActivity.class);
intent.putExtra("YourKeyName", "10");
startActivity(intent);
break;
case R.id.imageView3:
Intent intent = new Intent(YourCurrentActivity.this, YourOtherActivity.class);
intent.putExtra("YourKeyName", "30");
startActivity(intent);
break;
case R.id.imageView02:
Intent intent = new Intent(YourCurrentActivity.this, YourOtherActivity.class);
intent.putExtra("YourKeyName", "50");
startActivity(intent);
break;
case R.id.imageView06:
Intent intent = new Intent(YourCurrentActivity.this, YourOtherActivity.class);
intent.putExtra("YourKeyName", "100");
startActivity(intent);
break;
default:
break;
}
}
};
String valueFromIntent = getIntent().getStringExtra("YourKeyName");
Intent intent = new Intent(YourSecondActivity.this, YourThirdActivity.class);
intent.putExtra("YourKeyName", valueFromIntent);
startActivity(intent);
You can use :
Intent i = new Intent(MainActivity.this,SecondActivity.class);
i.putExtra("YourValueKey", value);
startActivity(i);
here
if(view.getId()==R.id.imageView2){
//here
}
then you can get it from your second activity by :
Intent intent = getIntent();
String YourtransferredData = intent.getExtras().getString("YourValueKey");
You can use Bundle to do the same in Android
//Create the intent
Intent i = new Intent(this, ActivityTwo.class);
AutoCompleteTextView textView = (AutoCompleteTextView) findViewById(R.id.autocomplete);
String getrec=textView.getText().toString();
//Create the bundle
Bundle bundle = new Bundle();
//Add your data to bundle
bundle.putString(“imagebuttonValue”, getrec);
//Add the bundle to the intent
i.putExtras(bundle);
//Fire that second activity
startActivity(i);
Now in your second activity retrieve your data from the bundle:
//Get the bundle
Bundle bundle = getIntent().getExtras();
//Extract the data…
String imagebuttonValue = bundle.getString(“imagebuttonValue”);
Using Intent you can call another activity and even send data with the help of putExtra from one activity to another activity, simply check below piece of code for understanding:
Intent intent= new Intent(currentActivity.this,nextActivity.class);
intent.putExtra("Key",yourvalue);
startActivity(intent);
On next acitivty to retrieve data:
Intent intent = getIntent();
String yourvalue= intent.getExtras().getString("Key");
Pass data trough Intent to your next activity and get your data in that activity like this
Intent intent = new Intent(Activity.this,SecondActity.class);
intent.putExtra("key",value);
startActivity(intent);
Get like this :
Intent intent = getIntent();
String value = intent.getStringExtra("key");
u want to launch a new activity and pass the label value to that ?
if yes then just create an Intent and add the value to it , and use this intent to launch other acitivty.
for example if your value is "5" then :-
Intent intent = new Intent(context) ;
intent.putExtra("key","5");
(refer here)
startActivity(intent);
and at onCreate() method of newly launched activity :-
String value= getIntent.getStringExtra("key"); (Refer here )
Get the values from the Image view. Use Extras and send it to the other Activity.
Lets Say first Activity is X and Next Activity is Y :-
//Include this in your code in the first activity inside your if condition
if(view.getId()==R.id.imageView2){
Intent main= new Intent(X.this, Y.class);
main.putExtra("key", value);
X.this.startActivity(main);
}
At Y Activity onCreate
Intent intent = getIntent();
String value= intent.getStringExtra("key");
Hope it helps.
Thanks!
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