Android ListView only shows one item at a time - java

My program is that when a user enteres some information and clicks the "Submit" button, this data will be stored in a separate activity's list View.I have a Shared Preferences incorporated so that the data will be stored. The problem is that only one piece of information gets stored at a time. If I enter a new piece of data, the previous one is overwritten.
public class PreviousPractices extends Activity {
int minutes,hours;
String description;
String date;
ListView practiceList;
ArrayAdapter<String> adapter;
ArrayList<String> listItems = new ArrayList<String>();
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.previous_practices_layout);
practiceList=(ListView)findViewById(R.id.practiceList);
adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1,listItems);
practiceList.setAdapter(adapter);
getIntents();
LoadPreferences();
}
public void getIntents(){
if (getIntent().getExtras() == null) {
}
else {
Bundle extras = getIntent().getExtras();
hours = extras.getInt("Hours");
minutes = extras.getInt("Minutes");
description = extras.getString("Description");
date = extras.getString("dateOfPractice");
adapter.notifyDataSetChanged();
SavePreferences("LISTS", date);
}
}
Right now I'm only working with the date to simplify things. I'm not sure what the issue is, and I'd appreciate some help.

Related

Passing Data from multiple activities to one activity

I have created three different activities with three different ListViews similar to this and created another activity with a Button.
The purpose is to select any item from any ListView and it will change the Button text to the selected item I choose.
Here is the code I use to create the ListViews:
public class C_Camera extends AppCompatActivity {
ListView listView_C_Camera;
String[] listview_c_camera = new String[]{
"a" , "b", "c", "d" , "e" , "f","g", "h","i","j"
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_c__camera);
listView_C_Camera = findViewById(R.id.listview_c_camera);
ArrayAdapter<String> CanonCamera = new ArrayAdapter<>(this , R.layout.listview_row,listview_c_camera);
listView_C_Camera.setAdapter(CanonCamera);
listView_C_Camera.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String C_Camera_Temp = listview_c_camera[position];
Intent intent = new Intent(C_Camera.this, BuildCamera.class);
intent.putExtra("C_Camera",C_Camera_Temp);
startActivity(intent);
}
});
}
}
I have another activity with a Button that will get the values of the three different ListViews.
public class BuildCamera extends AppCompatActivity {
Button camerabuild;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_build_camera);
camerabuild = findViewById(R.id.camerabuild);
String C_Camera_Holder = getIntent().getStringExtra("C_Camera");
String N_Camera_Holder = getIntent().getStringExtra("N_Camera");
String S_Camera_Holder = getIntent().getStringExtra("S_Camera");
camerabuild.setText(C_Camera_Holder);
camerabuild.setText(N_Camera_Holder);
camerabuild.setText(S_Camera_Holder);
...
Here I'm facing a problem.
If I use String C_Camera_Holder = getIntent().getStringExtra("C_Camera") and comment the others it will work and change the text,
String C_Camera_Holder = getIntent().getStringExtra("C_Camera");
// String N_Camera_Holder = getIntent().getStringExtra("N_Camera");
// String S_Camera_Holder = getIntent().getStringExtra("S_Camera");
camerabuild.setText(C_Camera_Holder);
// camerabuild.setText(N_Camera_Holder);
// camerabuild.setText(S_Camera_Holder);
but if I uncomment the second one (String N_Camera_Holder = getIntent().getStringExtra("N_Camera")) the first one will stop changing the text and the second will do and so on.
String C_Camera_Holder = getIntent().getStringExtra("C_Camera");
String N_Camera_Holder = getIntent().getStringExtra("N_Camera");
// String S_Camera_Holder = getIntent().getStringExtra("S_Camera");
camerabuild.setText(C_Camera_Holder);
camerabuild.setText(N_Camera_Holder);
// camerabuild.setText(S_Camera_Holder);
the button will always carry the last setText() function that you call.
camerabuild.setText(C_Camera_Holder);
camerabuild.setText(N_Camera_Holder);
camerabuild.setText(S_Camera_Holder); <<----------which is, this one.
to make it dynamic on your activity intents you can use if statement.
like this
if(C_Camera_Holder != null){
camerabuild.setText(C_Camera_Holder);
}else if(N_Camera_Holder != null){
camerabuild.setText(N_Camera_Holder);
}else if(S_Camera_Holder != null){
camerabuild.setText(S_Camera_Holder);
}

activity only loads data for first ever pressed index after reloading app

I have created Activity with a listView which uses setOnItemClickListener to determine which index has been pressed. Then it should pass the data into the next activity based on the selected index.
Passing of the values works, but it only works for the first listView index pressed after the app is reloaded.
To make it more clear. When the app is loaded I can press on any index of the ListView which will pass the data to the next Activity and display it correctly, but then when I go back to the ListView and select different index it still displays the same data from the previous index without updating it. Therefore, I have to reload the app to get new index results displayed.
Here is my ViewListActivity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_artist);
artistList = (ListView) findViewById(R.id.artistList);
databasehandler = new SqliteHandler(ViewArtistActivity.this);
allArtists = databasehandler.getAllArtists();
artistName = new ArrayList<>();
singleArtistDetails = new ArrayList<>();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
if (allArtists.size() > 0) {
for (int i=0; i < allArtists.size(); i++) {
ArtistModel artistModel = allArtists.get(i);
artistName.add(artistModel.getArtistName());
}
}
adapter = new ArrayAdapter(ViewArtistActivity.this, android.R.layout.simple_list_item_1, artistName);
artistList.setAdapter(adapter);
artistList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
ArtistModel artistModel = allArtists.get(position);
singleArtistDetails.add(artistModel.getArtistName());
singleArtistDetails.add(artistModel.getArtistDOB());
singleArtistDetails.add(artistModel.getArtistBiography());
Intent intent = new Intent(ViewArtistActivity.this, SavedArtistDetailsActivity.class);
intent.putExtra("NAME", singleArtistDetails.get(0));
intent.putExtra("DOB", singleArtistDetails.get(1));
intent.putExtra("BIOGRAPHY", singleArtistDetails.get(2));
startActivity(intent);
}
});
}
Here is my code for displaying selected index results Activity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_saved_artist_details);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
artistSavedNameLbl2 = (TextView) findViewById(R.id.artistSavedNameLbl2);
artistSavedDOBLbl2 = (TextView) findViewById(R.id.artistSavedDOBLbl2);
artistSavedBiographyLbl2 = (TextView) findViewById(R.id.artistSavedBiographyLbl2);
btnDeleteDetails = (Button) findViewById(R.id.btnDeleteDetails);
updateUI();
}
private void updateUI() {
artistSavedNameLbl2.setText(getIntent().getStringExtra("NAME"));
artistSavedDOBLbl2.setText(getIntent().getStringExtra("DOB"));
artistSavedBiographyLbl2.setText(getIntent().getStringExtra("BIOGRAPHY"));
}
Do one thing , initialize [not saying declare] your array list singleArtistDetails inside the onClick method, before adding any values to it.
like
singleArtistDetails = new ArrayList();
Hope this will help.

How to play a specific sound for a Listview item when it is clicked

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. :)

Android- Adding item to ListView from another activity onButtonClick

I'm not sure why my code isn't working, I've looked at the rest of the threads on this site and followed the directions but there still seems to be some error.
In my app, there is a page for a user to enter some data, including dates, descriptions, hours, and minutes of duration. The description/date are Strings and hours and minutes are ints. I've focused on only the String date for now to simplify things.
After the user enters this data in the activity, they will click the "Submit" button. When they click this submit button, I want the user to be taken to another page where they will be able to see a history of their submitions in a ListView.
In the first Activity, when the "Submit" button is clicked, this method will be called:
public void newEntrySubmit(View v)
{
hours = npHours.getValue();
minutes = npMinutes.getValue();
description=String.valueOf(etDescription.getText().toString());
dateOfPractice=String.valueOf(etDate.getText().toString());
Intent i = new Intent(this, PreviousPractices.class);
i.putExtra("Hours", hours);
i.putExtra("Minutes", minutes);
i.putExtra("Description", description);
i.putExtra("dateOfPractice", dateOfPractice);
startActivity(i);
}
After this, the PreviousPractices class should open. The onCreate method for this class is shown:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.previous_practices_layout);
Bundle extras = getIntent().getExtras();
hours = extras.getInt("Hours");
minutes = extras.getInt("Minutes");
description=extras.getString("Description");
date = extras.getString("Date");
practiceList=(ListView)findViewById(R.id.practiceList);
ArrayList<String> listItems = new ArrayList<String>();
adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1,listItems);
practiceList.setAdapter(adapter);
listItems.add(date);
adapter.notifyDataSetChanged();
}
The problem is that when I click the "Submit" button, the app crashes. When I remove the
practiceList.setAdapter(adapter);
line, it successfully goes to the correct ListView page, however there is nothing shown(since no adapter is set).
Try this:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.previous_practices_layout);
Bundle extras = getIntent().getExtras();
hours = extras.getInt("Hours");
minutes = extras.getInt("Minutes");
description=extras.getString("Description");
// date = extras.getString("Date");
practiceList=(ListView)findViewById(R.id.practiceList);
ArrayList<String> listItems = new ArrayList<String>();
listItems.add(description);
adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1,listItems);
practiceList.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
I changed your test string to description, since date is not getting set (no extra for "Date" in previous activity). Also, I moved your ArrayList.add() to before your ListView.setAdapter(). Try this and see if it works.

Keeping list entries when I move activity

I have a ListView.
I populate this list from 2 editTexts
When I move activity and go back to it the entries are gone again.
I kind of understand why this is but dont know how to correct it.
ListView lv2 = (ListView) findViewById(R.id.listView2);
final SimpleAdapter simpleAdpt = new SimpleAdapter(this, planetsList, android.R.layout.simple_list_item_1, new String[]{"planet"}, new int[]{android.R.id.text1});
planetsList.add(createPlanet("planet", "testme"));
lv2.setAdapter(simpleAdpt);
button21.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
iinitList();
simpleAdpt.notifyDataSetChanged();
editText5.setText("");
editText6.setText("");
}
});
}
private void iinitList() {
String st,str;
Double db;
if (editText5.getText().toString()!= "" && editText6.getText().toString()!="") {
st = editText5.getText().toString();
str = editText6.getText().toString();
db = Double.parseDouble(str);
planetsList.add(createPlanet("planet", ""+st+
": \n" +db+""));
}
}
HashMap<String, String> createPlanet(String key, String name) {
HashMap<String, String> planet = new HashMap<String, String>();
planet.put(key, name);
return planet;
}
As you can see I have added a value to the list manually called test also, when I move activity this stays in the list, I would love if the editText entries were to stay in there also when I move activities.
Activities can be destroyed when you navigate to a new one or rotate. This will clear anything that is only referenced by the activity, like your EditTexts. However, Android provides a nice utility for saving things you want to remain in a method called, which you can override in your activity:
#Override
protected void onSaveInstanceState(Bundle state) {
// Put your values in the state bundle here
}
#Override
protected void onCreate(Bundle savedState) {
// Load your UI elements as usual
if (savedState != null) {
// Load your state from the bundle
}
}
That same bundle will be given back to you in onCreate, where you create your UI to begin with so you can reload the state from it.
This is a really good description of how activities work:
http://developer.android.com/reference/android/app/Activity.html

Categories

Resources