Ive searched for this all over the internet and there seems to be no simple explanation or tutorial on how to do this.
Basically, I want a layout that has a ListView where the user can click on an object and it will take them to the next layout.
In other words, using the listview as links to other layouts.
Everything Ive found on the internet has the end result of using a Toast... However I dont want a toast, i want to link to the next page.
Your question is slightly confusing so I'm going to make an assumption.
Is [LinearLayout1 LinearLayout2 Breadcrumb] suppose to be navigation or tabs that when selected insert their corresponding content into the Main Content?
If so I would suggest using fragments for each piece of content. Then when you click the navigation/tab, perform an animation of the fragment which slides the content in and out.
See the google docs for how to use fragments: http://developer.android.com/guide/components/fragments.html
See another stackoverflow answer for how to do the slide animation: Android Fragments and animation
or
http://android-developers.blogspot.com/2011/08/horizontal-view-swiping-with-viewpager.html
Here is some code that outlines how to invoke an activity following a click on a list row. Hopefully you can adapt the Toast example you mention to make this work for you.
The basic idea is that you launch a new Activity with a new Intent. You can pass any data you need from the listView row as an extra in the Intent.
final static String[] months = new String[] {"Jan","Feb","Mar"};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_layout);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
R.layout.row_layout, R.id.text1, months);
setListAdapter(adapter);
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
int intItem = (int)id;
Intent intent= new Intent(this, SecondaryActivity.class);
intent.putExtra("MONTH", intItem);
startActivity(intent);
}
Why using ListView for it?
Each row must lead to different layout?
Its main benefits is in displaying dynamically changing data, but in your case data is constant, right?
Use vertical LinearLayout, fill it programmatically with "list elements", and add
leListComponent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(YourActivity.this, TargetActivity.class));
}
});
to each.
If i didn't get it, and you feel good of using some adapter, it can be like this:
public class LeWrapper {
private String caption;
private Class<? extends Activity> target;
...POJO here...
}
v.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
//get leWrapper object from adapter
startActivity(new Intent(MenuActivity.this, leWrapper.getTarget()));
}
});
but its kinda overkill
Thanks for all the help guys. Sorry ive took my time replying. My solution is below :)
public class FP_WL1_ListView extends Activity {
private ListView lv1;
private String lv_arr[]={"Exercise Bike", "Treadmill", "Cross Trainer", "Squats", "Lunges"};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.fitnessprograms_wlday_one);
lv1=(ListView)findViewById(R.id.list);
lv1.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1 , lv_arr));
lv1.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
final TextView mTextView = (TextView)view;
switch (position) {
case 0:
Intent newActivity0 = new Intent(FP_WL1_ListView.this,FitnessPrograms_Wlone_sp.class);
startActivity(newActivity0);
break;
case 1:
Intent newActivity1 = new Intent(FP_WL1_ListView.this,FitnessPrograms_Wlone_Treadmill.class);
startActivity(newActivity1);
break;
case 2:
Intent newActivity2 = new Intent(FP_WL1_ListView.this,FitnessPrograms_Wlone_Crosstrainer.class);
startActivity(newActivity2);
break;
case 3:
Intent newActivity3 = new Intent(FP_WL1_ListView.this,FitnessPrograms_Wlone_Squats.class);
startActivity(newActivity3);
break;
case 4:
Intent newActivity4 = new Intent(FP_WL1_ListView.this,FitnessPrograms_Wlone_Lunges.class);
startActivity(newActivity4);
break;
}
}
});
} }
Related
What I want to do is set the texts depends on the spinner item selected by users. But there is nothing that showed up when running the app and there is no errors either. Did I miss any steps that cause the outcome didn't come out?? I'm still new to android.
UPDATE:
I forgot to say that I have three different spinners depending on which button users liked in 1st activity so I think its because I only declare for the spinner's item but didn't declare which spinner is "Japan" referring to.
So this is my code for 1st activity, I will just put only one first :
btnAsia.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(),MainActivity2.class);
intent.putExtra("continent", "asia");
startActivity(intent);
}
});
This is the string array in strings.xml:
<string-array name="asia">
<item>Japan</item>
<item>Thailand</item>
<item>Vietnam</item>
<item>South Korea</item>
</string-array>
and this is the code in 2nd activity:
private void DestinationSpinner()
{
Bundle bundle=getIntent().getExtras();
if(bundle!=null) {
String continent = bundle.getString("continent");
switch (continent) {
case "asia":
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(MainActivity2.this, R.array.asia, android.R.layout.simple_spinner_item); // Create an ArrayAdapter using the string array and a default spinner layout
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // Specify the layout to use when the list of choices appears
spinnerDestination.setAdapter(adapter); // Apply the adapter to the spinner
break; }
and lastly this is the code for retrieve selected item from spinner:
public void AvailableAirlines()
{
spinnerDestination.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String selected=spinnerDestination.getItemAtPosition(position).toString();
if (continent.equals("asia") && selected.equals("Japan"))
{
availableAirlines.setText("Available airports");
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
and I also want to pass the keyidentifer from 1st activity to 2nd activity but I tried using getExtras and it didn't work maybe I do it wrongly or what.
I think the issue is this line if(selected=="Japan")
In Java you will need to use equals instead of the == operator.
The == checks if the two pointers are pointing to the same memory location.
Equals will compare their content.
I have a Fragment inside the mainActivity, the fragment contains fragmentcontainerView which can be replaced by multiple child fragments with spinner onselectedListener. I want to able to pass those values from the child fragment via eg: Do something with: fragmentevent.TogetFName(); with a button in Mainactivity. In the parent fragment , I get the value from the child fragment(fragment_Birthday) with fragment_fr_event_birthday = (fragment_fr_event_Birthday) getChildFragmentManager().findFragmentById(R.id.fragment_event_child_fragment); and other value from other childfragment with frag_fr_event_wed = (fragment_fr_event_wedding) getChildFragmentManager().findFragmentById(R.id.fragment_event_child_fragment);, I know that they cannot be assigned with the different fragment class at once, but is there a clever way to do this or is there any other way I can pass value from child -> parent fragment->mainActivity
MainActivity:
public void onClick(View view){
case "Event":
Fragment_fr_Event fragment_fr_event = (Fragment_fr_Event) getSupportFragmentManager().findFragmentById(R.id.fragment_generated_mainView);
if(fragment_fr_event.TogetWedChildFcoupleName() !=null && fragment_fr_event.TogetEventType().equals("Wedding")){
testThis.setText(fragment_fr_event.TogetWedChildFcoupleName());
}if( fragment_fr_event.TogetEventType().equals("Birthday") && fragment_fr_event.TogetBirthdayFName() !=null){
testTat.setText(fragment_fr_event.TogetBirthdayFName());
}
}
ChildFragment(BirthdayFragment):
public String TogetEventBirthdayFName (){
EditText FBirthdayName = rootView.findViewById(R.id.Edittext_birthDay_FirstName);
return FBirthdayName.getText().toString();
}
ChildFragment(Wedding fragment):
public String toGetFcoupleName(){
EditText FCoupleName = rootView.findViewById(R.id.textView_wedding_Name);
return FCoupleName.getText().toString();
}
ParentFragment(EventFragment):
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
Spinner TypeEventSpinner = rootview.findViewById(R.id.type_event);
TypeEventSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String tag_items = parent.getItemAtPosition(position).toString();
switch (tag_items){
case "Wedding":
frag_fr_event_wed = new fragment_fr_event_wedding();
FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
transaction.replace(R.id.fragment_event_child_fragment, frag_fr_event_wed).disallowAddToBackStack().commit();
break;
case "Birthday":
fragment_fr_event_birthday = new fragment_fr_event_Birthday();
transaction = getChildFragmentManager().beginTransaction();
transaction.replace(R.id.fragment_event_child_fragment , fragment_fr_event_birthday).disallowAddToBackStack().commit();
break;
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
public String TogetWedChildFcoupleName(){
if(frag_fr_event_wed !=null){
frag_fr_event_wed = (fragment_fr_event_wedding) getChildFragmentManager().findFragmentById(R.id.fragment_event_child_fragment);
return frag_fr_event_wed.toGetFcoupleName();
}return "Empty";
}
public String TogetBirthdayFName(){
if(fragment_fr_event_birthday != null){
fragment_fr_event_birthday = (fragment_fr_event_Birthday) getChildFragmentManager().findFragmentById(R.id.fragment_event_child_fragment);
return fragment_fr_event_birthday.TogetEventBirthdayFName();
}
return "Empty";
}
To be honest , I couldn't understand what you did there , but i got what you want , you want to communicate with parent's parent class , the way you are doing it made it so complicated even it's not readable , BUT of course there are always a good way to do something , in your case there are Android Navigation Component , which give you the simplicity and power to do make it much more easy to handle , You can put all your fragment in one graph and from within the destinations "fragment are called destinations here" you can communicate with other fragment and the parent using actions and global actions "going from one fragment to another is called action here" parameters, but there are no need to a parent's parent here , all destinations and its parent can share one ViewModel which will allow you to share data all around your app .
You can read more if it sound good to you here
Hello I want to have an Add function that allows me to input items to my GridView
For Background: I have a standard GridView and an XML activity (which contains 2 TextView) that I want to convert to my GridView. I also have a custom ArrayAdapter class and custom Word object (takes 2 Strings variables) that helps me do this.
My problem: I want to have an Add button that takes me to another XML-Layout/class and IDEALLY it input a single item and so when the user goes back to MainActivity the GridView would be updated along with the previous information that I currently hard-coded atm. This previous sentence doesn't work currently
Custom ArrayAdapter and 'WordFolder' is my custom String object that has 2 getters
//constructor - it takes the context and the list of words
WordAdapter(Context context, ArrayList<WordFolder> word){
super(context, 0, word);
}
#Override
public View getView(int position, View convertView, ViewGroup parent){
View listItemView = convertView;
if(listItemView == null){
listItemView = LayoutInflater.from(getContext()).inflate(R.layout.folder_view, parent, false);
}
//Getting the current word
WordFolder currentWord = getItem(position);
//making the 2 text view to match our word_folder.xml
TextView title = (TextView) listItemView.findViewById(R.id.title);
title.setText(currentWord.getTitle());
TextView desc = (TextView) listItemView.findViewById(R.id.desc);
desc.setText(currentWord.getTitleDesc());
return listItemView;
}
}
Here is my NewFolder code. Which sets contentview to a different XML. it's pretty empty since I'm lost on what to do
public class NewFolder extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.new_folder_view);
Button add = (Button) findViewById(R.id.add);
//If the user clicks the add button - it will save the contents to the Word Class
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//make TextView variables and cast the contents to a string and save it to a String variable
TextView name = (TextView) findViewById(R.id.new_folder);
String title = (String) name.getText();
TextView descText = (TextView) findViewById(R.id.desc);
String desc = (String) descText.getText();
//Save it to the Word class
ArrayList<WordFolder> word = new ArrayList<>();
word.add(new WordFolder(title, desc));
//goes back to the MainActivity
Intent intent = new Intent(NewFolder.this, MainActivity.class);
startActivity(intent);
}
});
}
In my WordFolder class I made some TextView variables and save the strings to my ArrayList<> object but so far it's been useless since it doesn't interact with the previous ArrayList<> in ActivityMain which makes sense because its an entirely new object. I thought about making the ArrayList a global variable which atm it doesn't make sense to me and I'm currently lost.
Sample code would be appreciative but looking for a sense of direction on what to do next. I can provide other code if necessary. Thank you
To pass data between Activities to need to do a few things:
First, when the user presses your "Add" button, you want to start the second activity in a way that allows it to return a result. this means, that instead of using startActivity you need to use startActivityForResult.
This method takes an intent and an int.
Use the same intent you used in startActivity.
The int should be a code that helps you identify where a result came from, when a result comes. For this, define some constant in your ActivityMain class:
private static final int ADD_RESULT_CODE = 123;
Now, your button's click listener should looks something like this:
addButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent=new Intent(MainActivity.this, NewFolder.class);
startActivityForResult(intent, ADD_RESULT_CODE);
}
});
Now for returning the result.
First, you shouldn't go back to your main activity by starting another intent.
Instead, you should use finish() (which is a method defined in AppCompatActivity, you can use to finish your activity), this will return the user to the last place he was before this activity - ActivityMain.
And to return some data, too, you can use this code:
Intent intent=new Intent();
intent.putExtra("title",title);
intent.putExtra("desc",desc);
setResult(Activity.RESULT_OK, intent);
where title and desc are the variables you want to pass.
in your case it should look something like this:
public class NewFolder extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.new_folder_view);
Button add = (Button) findViewById(R.id.add);
//If the user clicks the add button - it will save the contents to the Word Class
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//make TextView variables and cast the contents to a string and save it to a String variable
TextView name = (TextView) findViewById(R.id.new_folder);
String title = (String) name.getText();
TextView descText = (TextView) findViewById(R.id.desc);
String desc = (String) descText.getText();
//Save it to the Word class
ArrayList<WordFolder> word = new ArrayList<>();
word.add(new WordFolder(title, desc));
Intent intent=new Intent();
intent.putExtra("title",title);
intent.putExtra("desc",desc);
setResult(Activity.RESULT_OK, intent);
//goes back to the MainActivity
finish();
}
});
}
You should probably also take care of the case where the user changed his mind and wants to cancel adding an item. in this case you should:
setResult(Activity.RESULT_CANCELLED);
finish();
In your ActivityMain you will have the result code, and if its Activity.RESULT_OK you'll know you should add a new item, but if its Activity.RESULT_CANCELLED you'll know that the user changed their mind
Now all that's left is receiving the data in ActivityMain, and doing whatever you want to do with it (like adding it to the grid view).
To do this you need to override a method called onActivityResult inside ActivityMain:
// Call Back method to get the Message form other Activity
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
// check the result code to know where the result came from
//and check that the result code is OK
if(resultCode == Activity.RESULT_OK && requestCode == ADD_RESULT_CODE )
{
String title = data.getStringExtra("title");
String desc = data.getStringExtra("desc");
//... now, do whatever you want with these variables in ActivityMain.
}
}
this is my first post here so be gentle :p
Here is the thing, I'm facing a really though issue and after several research i did not manage to figure out a clean solution. Let me explain:
I'm actually developing an android app for restaurant management.
In activity A, i'm able to create some articles with different parameters (picture, name, price ..).
I can also create a menu in which i indicate which articles are included. To do so i run Activity B that contains a dynamic list of the available articles (the ones i created) to be chosen. After picking up some of them the customised chosen objects are sent to Activity A through Parcel. And the chosen article list is updated in the menu.
But here is the thing, as far as i know, using Parcels create another instance of the object. As a result, if i modify or delete an article, the article list included in the menu does not change, and obviously i would like the list in the menu to be automatically updated.
Is there a way to simply pass customised objects through activities by reference?
What could be a clean solution to make the article list in the menu dynamic?
Here is some code:
In Activity A, in the menu interface i click + button to add an article, which run Activity B (the extras is the list of articles already included in the menu before, so in the beginning it's empty).
//Add article
FloatingActionButton addArticleButton = (FloatingActionButton)parentActivity.findViewById(R.id.addArticleButton);
addArticleButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showMenuDetails(menuListView,menuAdapter,currentMenu);
parentActivity.startActivityForResult(new Intent(parentActivity.getApplicationContext(),ChooseArticleActivity.class).putParcelableArrayListExtra("menuArticleList",currentMenu.getArticles()),PICK_ARTICLES);
}
});
In activity B: I select Articles in a list of available Articles (the ones i created). After picking up i press OK button to put the list of chosen articles in result Intent as Parcelable Extras
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.choose_article_layout);
initializeLists();
this.resultIntent = new Intent();
}
private void initializeLists(){
final ListView articleToChoose = (ListView)findViewById(R.id.articleToChoose);
final ListView articleChosen = (ListView)findViewById(R.id.articleChosen);
final ArrayList<Article> articleToChooseList = (ArrayList<Article>)MainActivity.model.getArticleList().getArticleList().clone();
final ArrayList<Parcelable> articleChosenListParcelable = (ArrayList<Parcelable>)this.getIntent().getParcelableArrayListExtra("menuArticleList");
final ArticleAdapter articleToChooseAdapter = new ArticleAdapter(getApplicationContext(), articleToChooseList);
articleToChoose.setAdapter(articleToChooseAdapter);
ArrayList<Article> articleChosenListTemp = new ArrayList<>();
ArrayList<Article> articleToRemove = new ArrayList<>();
for(Parcelable a:articleChosenListParcelable){
articleChosenListTemp.add((Article)a);
for(Article article:articleToChooseList){
if(article.getName().equals(((Article) a).getName())){
articleToRemove.add(article);
}
}
}
articleToChooseList.removeAll(articleToRemove);
articleToChooseAdapter.notifyDataSetChanged();
final ArrayList<Article> articleChosenList = articleChosenListTemp;
final ArticleAdapter articleChosenAdapter = new ArticleAdapter(getApplicationContext(),articleChosenList);
articleChosen.setAdapter(articleChosenAdapter);
articleChosen.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Article articleClicked = articleChosenAdapter.getItem(position);
articleChosenList.remove(articleClicked);
articleToChooseList.add(articleClicked);
articleChosenAdapter.notifyDataSetChanged();
articleToChooseAdapter.notifyDataSetChanged();
}
});
articleToChoose.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Article articleClicked = articleToChooseAdapter.getItem(position);
if(!articleChosenList.contains(articleClicked)){
articleChosenList.add(articleClicked);
articleToChooseList.remove(articleClicked);
articleToChooseAdapter.notifyDataSetChanged();
articleChosenAdapter.notifyDataSetChanged();
}
}
});
Button okButton = (Button)findViewById(R.id.okButton);
okButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
chosenArticleListAttr = articleChosenList;
resultIntent.putParcelableArrayListExtra("articleList",chosenArticleListAttr);
setResult(RESULT_OK,resultIntent);
finish();
}
});
Button cancelButton = (Button)findViewById(R.id.cancelButton);
cancelButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
}
In activity A, in onActivityResult i catch the result and update the list, but the added Articles here are not the same instance as the article list in the model
if(requestCode==PICK_ARTICLES && resultCode==RESULT_OK){
ArticleAdapter articleAdapter = (ArticleAdapter) gestionMenusLayout.getMenuArticleListView().getAdapter();
ArrayList<Parcelable> chosenArticleList = (ArrayList<Parcelable>)data.getParcelableArrayListExtra("articleList");
gestionMenusLayout.getCurrentMenu().getArticles().clear();
for(Parcelable a:chosenArticleList){
gestionMenusLayout.getCurrentMenu().addArticle((Article)a);
}
articleAdapter.notifyDataSetChanged();
}
For debugging purpose only, I suggest that you use a public static List<Article> articleList and call it directly from whether activity A or B
A better but take-alittle-more-effort solution is that you store the list in a database, and every updates, queries, ... come through it.You can use the server's database (where people usually get articles from), or a offline database like Realm here
I figured it out with a quite easy and simple solution finally.
I keep passing my Article objects through intents by parcels.
But as it creates a new instance, instead of adding this instance i add the original one (the one from the model) after an equality key check (the name of the article). By doing so i keep the reference on my Article.
Thank you for helping!
Edit:
Here is the code:
if(requestCode==PICK_ARTICLES && resultCode==RESULT_OK){
ArticleAdapter articleAdapter = (ArticleAdapter) gestionMenusLayout.getMenuArticleListView().getAdapter();
ArrayList<Parcelable> chosenArticleList = (ArrayList<Parcelable>)data.getParcelableArrayListExtra("articleList");
gestionMenusLayout.getCurrentMenu().getArticles().clear();
ArrayList<Article> modelArticles = MainActivity.model.getArticleList().getArticleList();
for(Parcelable a:chosenArticleList){
for(Article modelArticle:modelArticles){
if(((Article)a).getName().equals(modelArticle.getName())){
gestionMenusLayout.getCurrentMenu().addArticle(modelArticle);
}
}
}
articleAdapter.notifyDataSetChanged();
}
I am creating an android dictionary app with sounds... I have listview, when an item is selected, a new activity open, inside the new activity contains 4 textviews and an image button, the textviews function perfectly but the image button was not. The audio files are placed in raw folder. How can I put the specific sounds of an item that was clicked?
Here's the code:
MainActivityJava
public class MainActivity extends AppCompatActivity {
ListView lv;
SearchView sv;
String[] tagalog= new String[] {"alaala (png.)","araw (png.)","baliw (png.)","basura (png.)",
"kaibigan (png.)","kakatuwa (pu.)", "kasunduan (png.)","dambuhala (png.)",
"dulo (png.)","gawin (pd.)","guni-guni (png.)","hagdan (png.)","hintay (pd.)",
"idlip (png.)","maganda (pu.)","masarap (pu.)", "matalino (pu.)"};
int[] sounds= new int[]{R.raw.alaala,
R.raw.araw,
R.raw.baliw,
R.raw.basura,
R.raw.kaibigan,
R.raw.kakatuwa,
R.raw.kasunduan,
};
ArrayAdapter<String> adapter;
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv = (ListView) findViewById(R.id.listView1);
sv = (SearchView) findViewById(R.id.searchView1);
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,tagalog);
lv.setAdapter(adapter);
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String tagword =tagalog[position];
String[] definition = getResources().getStringArray(R.array.definition);
final String definitionlabel = definition[position];
String[] cuyuno = getResources().getStringArray(R.array.cuyuno);
final String cuyunodefinition = cuyuno[position];
String[] english = getResources().getStringArray(R.array.english);
final String englishdefinition = english[position];
Intent intent = new Intent(getApplicationContext(), DefinitionActivity.class);
intent.putExtra("tagword", tagword);
intent.putExtra("definitionlabel", definitionlabel);
intent.putExtra("cuyunodefinition",cuyunodefinition);
intent.putExtra("englishdefinition", englishdefinition);
startActivity(intent);
}
});
sv.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String text) {
return false;
}
#Override
public boolean onQueryTextChange(String text) {
adapter.getFilter().filter(text);
return false;
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
return super.onCreateOptionsMenu(menu);
}
}
DefinitionActivity.java
public class DefinitionActivity extends AppCompatActivity {
MediaPlayer mp;
String tagalogword;
String worddefinition;
String cuyunoword;
String englishword;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_definition);
TextView wordtv = (TextView) findViewById(R.id.wordtv);
TextView definitiontv = (TextView) findViewById(R.id.definitiontv);
TextView cuyunotv = (TextView) findViewById(R.id.cuyunotv);
TextView englishtv = (TextView) findViewById(R.id.englishtv);
ImageButton playbtn = (ImageButton) findViewById(R.id.playbtn);
final Bundle extras = getIntent().getExtras();
if (extras != null) {
tagalogword = extras.getString("tagword");
wordtv.setText(tagalogword);
worddefinition = extras.getString("definitionlabel");
definitiontv.setText(worddefinition);
cuyunoword = extras.getString("cuyunodefinition");
cuyunotv.setText(cuyunoword);
englishword = extras.getString("englishdefinition");
englishtv.setText(englishword);
}
playbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
you can pass the raw id in the intent extra and play it on meadiaPlayer
What you want to accomplish is pretty simple.
you can ofcourse pass the id.
But I created this method for your case you can paste it in your activity or class and make a call to it. In my case, I put this method in a class that holds all the common functions, methods, strings, etc. The choice is yours :
public static void playDisSound(Context c, int soundID){
//Play short tune
MediaPlayer mediaPlayer = MediaPlayer.create(c, soundID);
mediaPlayer.setOnCompletionListener( new OnCompletionListener(){
#Override
public void onCompletion( MediaPlayer mp){
mp.release();
}
});
mediaPlayer.start();
}
And this is how to use it in your case :
Example I want to play an audio track from :
int[] sounds= new int[]{R.raw.alaala,
R.raw.araw,
R.raw.baliw,
R.raw.basura,
R.raw.kaibigan,
R.raw.kakatuwa,
R.raw.kasunduan,
};
So I just do :
//TODO ~ pls. remember to define context inside "onCreate" as
//call this before "onCreate"
Context context;
//And do this inside "onCreate" :
context = getApplicationContext();
OR
context = MainActivity.this;
//Then here comes the solution, just make a call to the playDisSound method with the id , in this case the "sounds[postion_referencer_i]"
playDisSound(context, sounds[postion_referencer_i]);
//And now on the question of what your "position_referencer_i" would be .... it also depends on how you intend to pass the id.
Are your going to make a match between the position picked and the position of the sound. It depends on you. But I would have created a set of integers to signify which try I want to play and do a matching simple calculation between the position picked for the item clicked to arrive at the position_referencer_id.
//But simply : note that in your array if I want to play for example "R.raw.baliw" I would just call :
playDisSound(context, R.raw.baliw);
I hope this works perfectly for you. So if I elaborated too much. Do let me know if you may need to stream the sound so I would just paste/send you a very cool method I have been using here in an app am working.
//FINALLY PLS. Remember this : this method would play the sound alright but it wont hesitate to play the sound all over again if you repeat the process. So do remember to check if the sound did play and finished before allowing the user to repeat, if not it could lead to repeated or kind of two speakers playing from the same song but at different time. (And the user may start to think that there is problem with the app. Pls. be very logical and sensitive in using this method)
In solving that, you can disable the button or the UI element that initiates the sound playing until the sound has finished playing, by way of monitoring duration of the track (which I am sure you should know and inculcate into your logic or by simply listening if sound is already playing)
All the best. Era. :)