New Activity from ListView - java

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!

Related

Android put extra doesn't send extras to another activity

I try to send some values to another activity.
recyclerView.addOnItemTouchListener(new RecyclerTouchListener(getApplicationContext(), recyclerView, new RecyclerTouchListener.ClickListener() {
#Override
public void onClick(View view, int position) {
Intent intent = new Intent(GroupsMain.this, AboutGroup.class);
intent.putExtra("groupName", "Hello");
startActivity(intent);
}
#Override
public void onLongClick(View view, int position) {
}
}));
And so on AboutGroup activity I try to get extra.
1 way:
Bundle extras = getIntent().getExtras();
String name = extras.getString("groupName");
and second way:
Intent intent = new Intent();
String name = intent.getStringExtra("groupName");
But nothing works for me. On AboutGroup activity i get empty string. Please help me fix this problem.
try this
Send:
Intent intent = new Intent(MainActivity.this, Main2Activity.class);
intent.putExtra("groupName", "Hello Anna");
startActivity(intent);
get extra:
String name = getIntent().getStringExtra("groupName");
myTextview.setText(name);

Passing the selected object to an Another Activity

I have a news activity in which there is a list of news.I want a user to select a news from the list and direct him to the news_details page where I give the details about the selected news, however when the user selects the news, program goes quickly to news_details and comes back again to the news.
News:
public void Listen() {
list.setOnItemClickListener(new AdapterView.OnItemClickListener() { // ana sayfada herhangi bir item seçildiğinde
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
NewsItem selectedNews = (NewsItem) parent.getItemAtPosition(position);
Intent i = new Intent(MainActivity.this, News_Details_Activity.class);
i.putExtra("title", selectedNews.getTitle());
i.putExtra("date", selectedNews.getNewsDate().toString());
i.putExtra("image_id", selectedNews.getImageId());
i.putExtra("text", selectedNews.getText());
setResult(RESULT_OK, i);
startActivity(i);
}
});
}
News_Details:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_news__details);
Intent i = new Intent(this,MainActivity.class);
startActivityForResult(i, GET_NEWS);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == GET_NEWS) { // Check which request we're responding to
if (resultCode == RESULT_OK) { // Make sure the request was successful
title.setText(data.getStringExtra("title"));
date.setText(data.getStringExtra("date"));
news_img.setImageResource(data.getIntExtra("image_id", 0));
news_text.setText(data.getStringExtra("text"));
}
}
}
}
First of all, remove this line:
setResult(RESULT_OK, i);
Also, remove this line from newsdetails activity:
startActivityForResult(i, GET_NEWS);
Make changes as below:
public void Listen() {
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
NewsItem selectedNews = (NewsItem) parent.getItemAtPosition(position);
Intent i = new Intent(MainActivity.this, News_Details_Activity.class);
i.putExtra("title", selectedNews.getTitle());
i.putExtra("date", selectedNews.getNewsDate().toString());
i.putExtra("image_id", selectedNews.getImageId());
i.putExtra("text", selectedNews.getText());
startActivity(i);
}
});
}
Then, in your news details activity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_news__details);
Intent i = getIntent();
String title = i.getStringExtra("title");
String date = i.getStringExtra("date");
int imageId = i.getIntExtra("image_id");
String text = i.getStringExtra("text");
}
OnActivityResult method is not required so simply remove it.
FYI:
startActivity and startActivityForResult both of them start new activities , but startActivityForResult as the name suggests that you are expecting a result from the activity you are starting. And this result shall be obtained in onActivityResult method.
Say for example, you want to start Activity2 from Activity1, and you want to pass some data back to Activity1 while finishing Activity2. You simply set the Result in Activity2 using setResult() method. and while Activity1 resumes again, its onActivityResult() will be invoked, you will override onActivityResult() in Activity1 to receive the Result set by Activity2.
Hope you are now clear on this.
Remove these lines
setResult(RESULT_OK, i);
Intent i = new Intent(this,MainActivity.class);
startActivityForResult(i, GET_NEWS);
Use google Gson for serializing the object.
NewsItem selectedNews = (NewsItem) parent.getItemAtPosition(position);
String strNews = new Gson().toJson(selectedNews);
Intent i = new Intent(MainActivity.this, News_Details_Activity.class);
i.putExtra("news", strNews);
startActivity(i);
On other hand News details onCreate() do this
Bundle bundle = getIntent().getExtras();
String newsStr = bundle.getString("news");
Gson gson = new Gson();
Type type = new TypeToken<NewsItem>() {
}.getType();
NewsItem selectedNews = gson.fromJson(newsStr, type);
to send string value
NewsItem selectedNews = (NewsItem) parent.getItemAtPosition(position);
Intent i=new Intent(MainActivity.this, News_Details_Activity.class);
i.putExtra("title", selectedNews.getTitle());
i.putExtra("date", selectedNews.getNewsDate().toString());
i.putExtra("image_id", selectedNews.getImageId());
i.putExtra("text", selectedNews.getText());
startActivity(i);
to recieve in News_Details_Activity
Intent i = getIntent();
title = i.getStringExtra("title");
date= i.getStringExtra("date");
text= i.getStringExtra("text");
you can do it using Serializable by following way
public class News implements Serializable{
String title;
String desc;
String time,imageUrl;
}
Then News List activity
Intent i = new Intent(MainActivity.this, News_Details_Activity.class);
i.putExtra("news",newsObject);
and get it onCreate of NewsDetail
News news=(News) getIntent().getExtras().getSerializable("news");
and user it like title.setText(news.getTitle());
make News class that implements Serialazable
Create new Object of News class , and put into intent as putSerialazable();
in your second activity just getIntent().getSerialazable("key") and set your data to views.

Android Studio - How to open specific activities from a ListView?

I´ve got problems to finish my code to open activities from a list that I made. I´m making an app of equations and I want to have a list of the subjects and when you click on one, it starts the .xml file that have the equations that I already have. I got already the activities stringed to java classes.
Here is my code:
MainActivity.java:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_principal);
//get list view from xml
temasListView = (ListView) findViewById(R.id.temasListView);
String[] Temas = {
"Conversion",
"Suma",
"Trigonometria",
"Primera",
"Momento",
"Centro",
"Segunda1",
"MRU",
"MRUA",
"Tiro",
"Segunda2"};
ListAdapter temasAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, Temas);
ListView temasListView = (ListView) findViewById(R.id.temasListView);
temasListView.setAdapter(temasAdapter);
temasListView.setOnItemClickListener(
new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String temas = String.valueOf(parent.getItemAtPosition(position));
Toast.makeText(Temas.this, temas, Toast.LENGTH_LONG).show();
if (position == 0) {
Intent intent = new Intent(this, Conversion.class);
startActivity(intent);
}
else if (position == 1) {
Intent intent = new Intent(this, Suma.class);
startActivity(intent);
}
else if (position == 2) {
Intent intent = new Intent(this, Trigonometria.class);
startActivity(intent);
}
else if (position == 3) {
Intent intent = new Intent(this, Primera.class);
startActivity(intent);}
else if (position == 4) {
Intent intent = new Intent(this, Momento.class);
startActivity(intent);
}
else if (position == 5) {
Intent intent = new Intent(this, Centro.class);
startActivity(intent);
}
else if (position == 6) {
Intent intent = new Intent(this, Segunda1.class);
startActivity(intent);
}
else if (position == 7) {
Intent intent = new Intent(this, MRU.class);
startActivity(intent);
}
else if (position == 8) {
Intent intent = new Intent(this, MRUA.class);
startActivity(intent);
}
else if (position == 9) {
Intent intent = new Intent(this, Tiro.class);
startActivity(intent);
}
else if (position == 10) {
Intent intent = new Intent(this, Segunda2.class);
startActivity(intent);
}
});
}
strings.xml:
<resources>
<string name="app_name"></string>
<string-array name="temas">
<item>Conversión de Unidades</item>
<item>Suma de Vectores</item>
<item>Trigonometría</item>
<item>Primera Ley de Newton</item>
<item>Momento de Fuerzas</item>
<item>Centro de Gravedad</item>
<item>Componente de Velocidad</item>
<item>Segunda Ley de Newton</item>
<item>Movimiento Rectilíneo Uniforme</item>
<item>MRUA</item>
<item>Tiro Vertical</item>
<item>Segunda Ley de Newton (DCL)</item>
</string-array>
And my principal activity:
<LinearLayout
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:entries="#array/temas"
android:id="#+id/temasListView"
android:layout_weight="1.05"
android:background="#dadada" />
</LinearLayout>
I need help to finish this please!
When you are inside anonymous inner class this will not refer to your current activity class.
You should use MainActivity.this instead of this
i.e
Intent intent = new Intent(MainActivity.this, Conversion.class);
startActivity(intent);
You can refactor your code like this, to get rid of switch case.
String className= parent.getItemAtPosition(position).toString();
Class myClass=Class.forName("yourpackagename"+className);
Intent intent = new Intent(MainActivity.this, myClass);
startActivity(intent);
No need to use many switch conditions.
Also as pointed in above answer use MainActivity.this instad of Temas.this in your toast message
Change this line from
Toast.makeText(Temas.this, temas, Toast.LENGTH_LONG).show();
to
Toast.makeText(MainActivity.this, temas, Toast.LENGTH_LONG).show();

How to assign value in button and display the value at other activity?

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!

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);

Categories

Resources