So here's my code:
public class MainActivity extends AppCompatActivity {
/* access modifiers changed from: protected */
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
setContentView(R.layout.activity_main);
}
public void onClick(View view) {
Intent intent;
switch (view.getId()) {
case R.id.button: // Text
intent = new Intent(this,"Faiz Ahmed \nLove music forever\nTCSS 450");
break;
case R.id.button2: // Image
intent = new Intent(this, ImageActivity.class);
break;
case R.id.button3: // Web
intent = new Intent("android.intent.action.VIEW");
intent.setData(Uri.parse("http://developer.android.com"));
break;
case R.id.button4: // Toast
Toast.makeText(this, "Here's to a new quarter!", Toast.LENGTH_SHORT)
.show();
break;
case R.id.button5: // Dialog
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("I am a dialog").setTitle("Some Title").create().show();
}
intent = null;
if (intent != null) {
startActivity(intent);
}
}
}
All the import's are there I just for some reason none of the buttons are working. The first 2 (Text & Image) I know I need a lot more code, but the last 3 should work & they're not for some reason. Any know what I'm doing wrong & how to fix it?
Nothing of the buttons will work because in the switch-case statement you initialize the intent according to which button was pressed.
After that you set intent to null and lastly you start the activity if the intent is not null, but it always is (since you set it before to null).
Short story delete intent = null; statement.
// intent = null; delete this line
if (intent != null) {
startActivity(intent);
}
Related
I'm new here and I think I have made a mistake in Java but I have no idea how to correct it. Most of the people with similar issue had much more complicated projects and I couldn't resolve my issue by looking at their code.
I want to use different buttons (9 of them) to start different activities, but when I started with adding the second, only the activity 1 (LeftArmActivity) popped up. Whatever I changed in the XML to call the proper method for HeadActivity to launch, only the LeftActivity launches. I've got a hint from other topics that it may be caused by overwriting of the intent, but I have no idea how to fix this. I tried to use getActivity() but it just crashed. Could you please help me with this?
#UPDATE
Okay, I used the switch recommended below, but now the app won't start at all :/
public class MainActivity extends AppCompatActivity {
Context context = this;
Button LeftArmOpener = (Button) findViewById(R.id.LeftArmOpener);
Button HeadOpener = (Button) findViewById(R.id.HeadOpener);
Button RightArmOpener = (Button) findViewById(R.id.RightArmOpener);
Button CreditsOpener = (Button) findViewById(R.id.CreditsOpener);
Button TrunkOpener = (Button) findViewById(R.id.TrunkOpener);
Button NextOpener = (Button) findViewById(R.id.NextOpener);
Button RightLegOpener = (Button) findViewById(R.id.RightLegOpener);
Button ExitOpener = (Button) findViewById(R.id.ExitOpener);
Button LeftLegOpener = (Button) findViewById(R.id.LeftLegOpener);
protected View.OnClickListener mClick;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mClick = new View.OnClickListener() {
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.RightArmOpener: {
Intent i1 = new Intent(context, LeftArmActivity.class);
startActivity(i1);
break;
}
case R.id.HeadOpener: {
Intent i2 = new Intent(context, HeadActivity.class);
startActivity(i2);
break;
}
case R.id.LeftArmOpener: {
Intent i3 = new Intent(context, LeftArmActivity.class);
startActivity(i3);
break;
}
case R.id.CreditsOpener: {
Intent i4 = new Intent(context, CreditsActivity.class);
startActivity(i4);
break;
}
case R.id.TrunkOpener: {
Intent i5 = new Intent(context, TrunkActivity.class);
startActivity(i5);
break;
}
case R.id.NextOpener: {
Intent i6 = new Intent(context, NextActivity.class);
startActivity(i6);
break;
}
case R.id.RightLegOpener: {
Intent i7 = new Intent(context, RightLegActivity.class);
startActivity(i7);
break;
}
case R.id.ExitOpener: {
Intent i8 = new Intent(context, ExitActivity.class);
startActivity(i8);
break;
}
case R.id.LeftLegOpener: {
Intent i9 = new Intent(context, LeftLegActivity.class);
startActivity(i9);
break;
}
//create this for all 9 buttons
}
}
};
LeftArmOpener.setOnClickListener(mClick);
HeadOpener.setOnClickListener(mClick);
RightArmOpener.setOnClickListener(mClick);
CreditsOpener.setOnClickListener(mClick);
TrunkOpener.setOnClickListener(mClick);
NextOpener.setOnClickListener(mClick);
RightLegOpener.setOnClickListener(mClick);
ExitOpener.setOnClickListener(mClick);
LeftLegOpener.setOnClickListener(mClick);
}
}
Update your Code with this
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void openHead(View view){
startActivity(new Intent(MainActivity.this, LessonOne.class));
//startActivity(t);
}
public void openLeftArm(View view){
Intent i = new Intent(MainActivity.this, LeftArmActivity.class);
startActivity(i);
}
}
//the problem is you are calling startActivity() two time and Passing getActivity() from Actvity.
You said you have 9 buttons so i think u should use switch case in such scenarios see the following code:-
Here is how my Button looks in xml no android:onClick is used here
<Button
android:id="#+id/btn1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Button 1" />
This part goes in Activity:-
Context context = this;
Button btn1 = (Button) findViewById(R.id.btn1);
Button btn2 = (Button) findViewById(R.id.btn2);
Button btn9 = (Button) findViewById(R.id.btn9);
btn1.setOnClickListener(mClick);
btn2.setOnClickListener(mClick);
btn9.setOnClickListener(mClick);
View.OnClickListener mClick = new View.OnClickListener() {
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn1: {
Intent i1 = new Intent(context, First.class);
startActivity(i1);
break;
}
case R.id.btm2: {
Intent i2 = new Intent(context, Second.class);
startActivity(i2);
break;
}
//create this for all 9 buttons
}
}
};
On the top declare your button; (before the oncreate method)
Button yourbuttonname;
Then on the oncreate method:
declare the view of the button:
yourbuttonname = (Button) findViewById(R.id.buttonNameInYourXML);
yourbuttonname.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(ActualActivity.this, ActivityYouWantToGo.class);
intent.putExtra("tag",valueassociatedtotag); // if you want to pass some data
startActivity(intent)
}
});
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'm working on a music sheet app, and have a bunch of songs in a ListView.
I'm using an onItemClick method, but the problem is, I don't know how to open an activity depending on what subitem is selected.
The array of songs is uta[], so I can find the specific String with uta[position], but how can I open a specific activity based off of the position that is picked by the user in the ListView?
You can make a switch/case statement on the String that you fetch with uta[position]
public void onItemClick(AdapterView parent, View v, int position, long id) {
String value = uta[position].getValue();
switch(value){
case "value1":
Intent intent = new Intent(this, activity1.class); startActivity(intent);
break;
case "value2":
Intent intent = new Intent(this, activity2.class); startActivity(intent);
break;
case "value3":
Intent intent = new Intent(this, activity3.class); startActivity(intent);
break;
}
}
Note: switch/case statement on Strings requires JDK 7, see the Oracle documentation.
Try in this manner in your onitemclick method
if (position == 0) {
Intent intent = new Intent(this, activity1.class);
startActivity(intent);
} else if (position == 1) {
Intent intent = new Intent(this, activity2.class);
startActivity(intent);
} else if (position == 2){
Intent intent = new Intent(this, activity3.class);
startActivity(intent);
}
Your ListView item-click listener provides the view that has been clicked:
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Song song = (Song) getItemAtPosition(position);
if (song.getId() == SOME_ID)
startActivity(new Intent(this, SomeActivity.class));
// you can then create the logic for all your activities
}
});
Also, you may pass the song to one activity that would load itself based on the song data. For that, I recommend you read about the Parcelable interface and how to put Extras in an Intent.
Can you use:
listView1.setOnItemClickListener(new AdapterView.onItemClickListener() {
#Override
public void onItemClick(AdapterView adapter, View view, int position, long arg) {
switch (position) {
case 0:
startActivity(new Intent(this, first_activity.class));
break;
case 1:
startActivity(new Intent(this, second_activity.class));
break;
// and more...
}
});
Cheers!
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 am trying to implement a side menu in my application it works fine for the most part, but the problem I have is that once I display de menu and try to scroll down the whole list turns white (background) and the text disappears.
http://i.imgur.com/6a6TgJJ.png
http://i.imgur.com/ykT7hCN.png
Above I attach two pictures showing the behavior of the menu, when I slide my finger from the left to the right the side menu shows, but if I scroll down in the menu, it becomes an empty white list, here is my code:
public class ControlApp extends SlidingActivity{
ArrayList<String> datos ;
ArrayAdapter<String> adaptador;
Intent intent;
private String[] mMenuLista;
// private MyCustomAdapter mAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_notificaciones);
setBehindContentView(R.layout.activity_menu);
Parse.initialize(this, "BqCCNsbb14MPgeWz3rznxO4DamuXUbsgiTug8P8I", "9j7GSLWnV46fkPsNMwnMD2FormAiclKlGitfDq2b");
ParseAnalytics.trackAppOpened(getIntent());
getSlidingMenu().setBehindOffset(100);
// mAdapter = new MyCustomAdapter();
PushService.setDefaultPushCallback(this, Notificaciones.class);
ParseInstallation.getCurrentInstallation().saveInBackground();
mMenuLista = getResources().getStringArray(R.array.lista_menu);
// for(int i=0; i<=9;i++){
// mAdapter.addItem(mMenuLista[i]);
// if(i == 9){
// mAdapter.addSeparatorItem(mMenuLista[i]);
// }
// }
ListView primario = (ListView) findViewById(R.id.left_drawer);
primario.setAdapter(new ArrayAdapter<String>(this,R.layout.drawer_list, mMenuLista));
primario.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> pariente, View view, int posicion, long id) {
selectItem(posicion);
}
});
}
public void selectItem(int posicion){
switch (posicion) {
case 0:
intent = new Intent(ControlApp.this, Notificaciones.class);
startActivity(intent);
break;
case 1:
intent = new Intent(ControlApp.this, Calificaiones.class);
startActivity(intent);
break;
case 2:
intent = new Intent(ControlApp.this, Mensajes.class);
startActivity(intent);
break;
case 3:
intent = new Intent(ControlApp.this, Citas.class);
startActivity(intent);
break;
case 4:
intent = new Intent(ControlApp.this, Permisos.class);
startActivity(intent);
break;
case 5:
intent = new Intent(ControlApp.this, Eventos.class);
startActivity(intent);
break;
case 6:
intent = new Intent(ControlApp.this, Horarios.class);
startActivity(intent);
break;
case 7:
intent = new Intent(ControlApp.this, Circulares.class);
startActivity(intent);
break;
case 8:
intent = new Intent(ControlApp.this, ProgramaDeEstudios.class);
startActivity(intent);
break;
case 9:
intent = new Intent(ControlApp.this, Ajustes.class);
startActivity(intent);
break;
case 10:
ParseUser.logOut();
ParseUser currentUser = ParseUser.getCurrentUser();
if (currentUser == null){
// sesion cerrada correctamente
Toast toast = Toast.makeText(getApplicationContext(), "Sesión cerrada correctamente", Toast.LENGTH_SHORT);
toast.show();
Intent regis = new Intent (ControlApp.this, MainActivity.class);
startActivity(regis);
finish();
}else{
Toast toast = Toast.makeText(getApplicationContext(), "No se logro cerrar sesion, intentelo de nuevo", Toast.LENGTH_SHORT);
toast.show();
}
break;
default:
break;
}
}
#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;
}
}
I hope someone can help me find my mistakes so I can correct the error. thank you!!!
I'm guessing you are manually setting the background color of a ListView in your menu to black, while the main activity theme has a white background?
You need to set the android:cacheColorHint attribute on the ListView to match the list background color. The white is appearing due to rendering optimization by Android which uses that cacheColorHint value to quickly redraw the list while scrolling.
I read a good blog post detailing this issue once. I can't find it right now but will link to it if I do :)