Android- Adding item to ListView from another activity onButtonClick - java

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.

Related

When I intent the arrayList's data, and how can I get those data in the second activity and setText and Image?

I have made a Song List using ArrayList, and I got all the information and it can be passed to the second activity and open it on a new page.
What I want to have is when I click the song list, then it opens in a new page, and the new page shows the details and the image of the song.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView_Main=findViewById(R.id.listView_Main);
final Song song1 = new Song("Love Story","Taylor Swift","September 12,2008", "$1.29");
Song song2 = new Song("Lover","Taylor Swift","August 23,2019", "$1.29" );
Song song3 = new Song("I Forgot That You Existed", "Taylor Swift", "August 23,2019", "$1.29");
Song song4 = new Song("The Archer", "Taylor Swift", "August 23,2019", "$1.29");
Song song5 = new Song("I Think He Knows","Taylor Swift", "August 23,2019", "$1.29");
final List<Song> songs = new ArrayList<>();
songs.add(song1);
songs.add(song2);
songs.add(song3);
songs.add(song4);
songs.add(song5);
MainAdapter adapter = new MainAdapter(this, songs);
listView_Main.setAdapter(adapter);
listView_Main.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Intent intent=new Intent(view.getContext(),SongDetailActivity.class);
intent.putExtra("currentSong",(Serializable) songs.get(i));
startActivity(intent);
}
});
}
But my problem is in the second activity, I don't know how to get the detail of the song, and the images by using the setText.
So, I have made the song details in the String.xml file.
How can I get those details and the image in the second activity?
Also, I don't know how to get the position of the song list in the second activity, I mean the position of which song that I click, and It show the detail of that song I had clicked.
//Here is the second activity of the Song Details.//////
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_song_detail);
textViewSongDetail=findViewById(R.id.textView_SongDetail);
imageViewSongDetail=findViewById(R.id.image_SongDetail);
Song currentSong=(Song)getIntent().getSerializableExtra("currentSong");
}
First of all make sure you've implemented Serializable in your model class Song. Than your code will work fine.
And to receive the position you can send -
intent.putExtra("position", i); // to send
getIntent().getIntExtra("position", -1); //to receive (-1 is default value)

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.

Android ListView only shows one item at a time

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.

send arraylist from one to another activity into listview android [duplicate]

This question already has an answer here:
Passing arraylist in intent from one activity to another
(1 answer)
Closed 7 years ago.
I am making an android app. It is simple and based on quotes. I have a database of around 300 quotes divided in 5 categories (movies, books, etc.) and I show them at random when a user clicks on a category, in a TextView. Now I want the users to have an option to save their favorite quotes, so I have another activity called Favorites where I want the favorites to show in a ListView.
For this I think that the best way is to have all the favorites the user will put in a String ArrayList, and then send the whole ArrayList to the Favorites activity where it will put the strings from the ArrayList in the ListView. But, every time I try to send an ArrayList to the other activity, my app crashes.
I only managed to send the current string that is shown on screen like this
text.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
intent.putExtra("key", text.getText());
Context context = getApplicationContext();
CharSequence text = "Added to favorites";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
And then I take it and put it in the other activity
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_favorites);
final ListView lista = (ListView) findViewById(R.id.listView);
Intent intent = getIntent();
tekst = intent.getStringExtra("key");
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, listItems);
lista.setAdapter(adapter);
listItems.add(tekst);
adapter.notifyDataSetChanged();
}
But then if I try to add another favorite, it just overwrites the previous one. So how should I deal with this? How to send all the favorites that the user wants to put? Is ArrayList the best option or is there another way?
Activity A :
ArrayList<String> list = new ArrayList<String>();
intent.putExtra("yourlist", list);
startActivity(intent);
Activity B:
ArrayList<String> list = getIntent().getSerializableExtra("yourlist");
I hope its help you..!
Your previous ArrayList is overwritten because every time you navigate to the Favorites activity, it gets recreated and so does the ArrayList. The data is not persisted. The best option would be to use a database and save the item to the database from one activity. Then the favorite items can be retrieved from the database inside the Favorites activity.

Convert string array to int array android

I'm trying to convert an string array (listview_array) to int array, and then compare numbers. Unfortunately, the app is crashing everytime I execute it.
Here is the code:
public class FindStop3 extends Activity implements OnItemClickListener{
private String stop,line,listview_array[],buschain,dayweek,weekly;
private int selected,day;
private TextView tvLine,tvToday,tvNext;
private ListView lv;
String currentdate = java.text.DateFormat.getDateInstance().format(Calendar.getInstance().getTime());//Get current time
String currenttime = java.text.DateFormat.getTimeInstance().format(Calendar.getInstance().getTime());//Get current time
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_find_stop3);
FindStop3.this.overridePendingTransition(android.R.anim.slide_in_left, android.R.anim.slide_out_right);//Lateral transition
Intent intent = getIntent();//Take data from last activity
Bundle bundle = intent.getExtras();
line=bundle.getString("Line");//Takes the previous selected line from the last activity
stop=bundle.getString("Stop");//Takes the previous selected stop from the last activity
setTitle("Selected stop: "+stop);//Modifies title
getDayOfWeek();//Gets day of week
getBusChain(line,stop,weekly);//Calls method to get the xml chain name
tvLine = (TextView) findViewById(R.id.tvLine);
tvLine.setText("Line from "+line);
tvNext = (TextView) findViewById(R.id.tvNext);
tvNext.setText("Next bus arrives at "+currenttime);
tvToday = (TextView) findViewById(R.id.tvToday);
tvToday.setText(dayweek+","+currentdate+" schedule:");
selected= getResources().getIdentifier(buschain, "array",
this.getPackageName());//Lets me use a variable as stringArray
listview_array = getResources().getStringArray(selected);
lv = (ListView) findViewById(R.id.lvSchedule);
lv.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, listview_array));
getNextBus();
}
And here is the method to convert it:
public void getNextBus () {
//Converts listview_array into an integer array
int myar[]=new int[listview_array.length];
for(int i=0;i<listview_array.length;i++){
myar[i]=Integer.parseInt(listview_array[i]);
}
If the method is not executed, the application works perfectly. The values are taken from an xml file as follows:
<string-array name="Schedule">
<item>05:40</item>
<item>06:00</item>
<item>06:16</item>
<item>06:28</item>
<item>06:40</item>
<item>07:16</item>
<item>07:29</item>
<item>07:43</item>
<item>07:55</item>
<item>08:07</item>
<item>08:22</item>
</string-array>
Could anyone gives an idea about what can be the problem?
Thanks.
I think that your problem is when you try to convert the values, because a value like this "05:40" cannot be converted into a int.
Problably, you're getting a NumberFormatException.
If you want a better answer please send the log of your app.

Categories

Resources