Populating Custom List with Intent Extras - Android - android

I am an application, which is basically an empty activity (empty list-view) where in the toolbar there is an Add button, clicking the button takes you to another activity with two edit text fields and a button (to submit the activity, in other words send the intent extras to the first activity). I want to take those input (both are strings) from that activity and display them in the list-view in the first activity.
I have made the toolbar and the button, and placed the custom list-view with its adapter in the first activity, and in the second activity I created the necessary views and along with the intent (for passing the two strings).
The problem is, that in the second activity, when I pass the intent extras to the first activity, a new list-view gets created every time instead of appending the list-view.
Can someone help me append the intent extras rather than creating a new list every time the user adds the two inputs?
This is the onCreate method in the first activity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_countries);
ActionBar actionBar = getActionBar();
if(actionBar != null)
actionBar.setDisplayHomeAsUpEnabled(true);
listView = (ListView) findViewById(R.id.listView);
populateList();
}
This is the populateList();
public void populateList(){
Bundle countryData = getIntent().getExtras();
if (countryData == null){
return;
}
String country = countryData.getString("country");
String year = countryData.getString("year");
ArrayAdapter<Country> adapter = new CustomAdapter();
listView.setAdapter(adapter);
countryList.add(new Country(country, year));
}
This is the adapter:
private class CustomAdapter extends ArrayAdapter<Country>{
public CustomAdapter() {
super(MyCountries.this, R.layout.list_item, countryList);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if (convertView == null){
view =getLayoutInflater().inflate(R.layout.list_item, parent, false);
}
Country currentCountry = countryList.get(position);
TextView countryText = (TextView) view.findViewById(R.id.countryName);
countryText.setText(currentCountry.getCountryName());
TextView yearText = (TextView) view.findViewById(R.id.yearOfVisit);
yearText.setText(currentCountry.getYear());
notifyDataSetChanged();
return view;
}
}
And this is the onClick() for submitting the input:
public void onClick(View v) {
String country = addCountry.getText().toString();
String year = addYear.getText().toString();
Intent result = new Intent(this, MyCountries.class);
result.putExtra("country", country);
result.putExtra("year", year);
startActivity(result);
}
Thank you very much.
Any help, or guidance will be greatly appreciated.

Related

ListView replaces first object instead of adding a new one

I created a test project, and in that project I am trying to create a listview that the user can add to when they click a button. The button opens an new activity with an editText and another button to go back to the listview activity and an item should have been added. It works the first time, but when I add another Item it replaces the old one. I have search for a while now, and all the other answer don't seem to help me. Thanks in advance.
public class MainActivity extends Activity {
ListView simpleList;
String input;
ArrayList<Item> listItems =new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
simpleList = (ListView) findViewById(R.id.listView);
addData();
MyAdapter myAdapter=new MyAdapter(this,R.layout.row, listItems);
simpleList.setAdapter(myAdapter);
}
public void addData(){
Bundle extras = getIntent().getExtras();
if (extras != null) {
input = extras.getString("Homework");
listItems.add(new Item(input, input, input));
}
}
public void toInput(View view){
Intent intent = new Intent(this, inputScreen.class);
startActivity(intent);
}}
This is my main activity, the adapter is a custom adapter that is made in this class.
public class MyAdapter extends ArrayAdapter<Item> {
ArrayList<Item> listItems = new ArrayList<>();
public MyAdapter(Context context, int textViewResourceId, ArrayList<Item> objects){
super(context, textViewResourceId, objects);
listItems = objects;
}
public int getCount(){
return super.getCount();
}
public View getView(int position, View convertView, ViewGroup parent){
View v = convertView;
LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = inflater.inflate(R.layout.row, null);
TextView textView = (TextView) v.findViewById(R.id.homeworkDisplay);
TextView textView2 = (TextView) v.findViewById(R.id.dueDisplay);
TextView textView3 = (TextView) v.findViewById(R.id.classDisplay);
textView.setText(listItems.get(position).getHomework());
textView2.setText(listItems.get(position).getDate());
textView3.setText(listItems.get(position).getClasses());
return v;
}}
The string that is added to the listview is sent from the another activity that gets it from an editText, here is it's class
public class inputScreen extends Activity{
EditText userInput;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.input_screen);
userInput = (EditText) findViewById(R.id.editText);
}
public void sendInfo(View view){
Intent goingBack = new Intent(this,MainActivity.class);
goingBack.putExtra("Homework", userInput.getText().toString());
startActivity(goingBack);
}}
I know there is alot of code there, you don't need to go through it all as I am sure the problem is in MainActivity. I have another class called items that returns homework. Thank you!
Used startActivity() is not correct.
your activity stack is like this :
the start
~~~~~~~~~~~~
MainActivity
~~~~~~~~~~~~
after you call toInput in MainActivity()
~~~~~~~~~~~~
InputScreen(activity)
MainActivity
~~~~~~~~~~~~
then when you call send() in InputScreen
~~~~~~~~~~~~
MainActivity
InputScreen
MainActivity
~~~~~~~~~~~~
see what's happening?
the first time in InputScreen you called send() start MainActivity with extras
then you started a new MainActivity ,then went the addData() ,you got data, and changed listView.
but when you do it again , you always start new Activities ,so only the first one was gonna change
always repeat the first step always start a new activity
you should call startActivityForResult() in MainActivity to start inputScreen and override the onActivityResult method in MainActivity
just google startActivity and startActivityForResult you will work this out .
and anther key word you should google is ,listView --> data source
sorry,I am not a native English speaker, if I did something wrong ,please forgive me ~~~~
Written by: https://stackoverflow.com/users/2936153/rohit5k2
Source: Listview replaces first item instead of creating new items
Every time you call changeText() your adapter is reset so only one
item will be displayed
Change your fragment like this
public class ListViewFragment1 extends Fragment {
protected ArrayAdapter<String> adapter1;
ListView list1;
#Override
public View onCreateView(LayoutInflater inflater,
#Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.list_view_fragment1, container, false);
adapter1 = new ArrayAdapter<String>(getActivity(), R.layout.items);
list1 = (ListView) view.findViewById(R.id.listview1);
list1.setAdapter(adapter1);
return view;
}
public void changeText(String data){
adapter1.add(data);
adapter1.notifyDataSetChanged();
}
}

ListView creates one more item than needed

I have a ListView which is populated in my MainActivity, but when i want to find the selected item, all of the items appear to have the same position.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_select_teams);
ListView mainListView;
// Find the ListView in the UI.
mainListView = (ListView) findViewById( R.id.listView );
String values = "Team A vs Team B=Team C vs Team D";
//Matches are send in one long string, and are separated by the = sign.
//This splits the string up and puts it into an array.
String[] array = values.split("=", -1);
ArrayList<String> arraylist = new ArrayList<String>();
arraylist.addAll( Arrays.asList(array) );
ArrayAdapter listAdapter;
// Create ArrayAdapter using the planet list.
listAdapter = new ArrayAdapter<String>(this, R.layout.list_view_style, arraylist);
// Set the ArrayAdapter as the ListView's adapter.
mainListView.setAdapter(listAdapter);
}
This makes a list like this:
Team A vs Team B [checkbox]
Team C vs Team D [checkbox]
I have a button and when it is clicked it runs this method:
public void matchStart(View view){
String selectedMatch = String.valueOf(((ListView) findViewById( R.id.listView )).getSelectedItemPosition());
Toast.makeText(SelectTeams.this, selectedMatch, Toast.LENGTH_SHORT).show();
}
However whenever i click the button, the toast displays the same value no matter which item in the listview is selected. Why is this?
You should use the adapters getView method, something like this:
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = inflater.inflate(R.layout.some_layout, parent,
false);
convertView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//here get what you need by the position
}
});
}
}

ListView not being changed

To start off I'm a beginner with this android programming.
My app has 2 activites defined in TabHost, hence Tab 1 and Tab 2.
In Tab 1 I receive an EditText input that I would like to show in tab 2 (activity 2) in a ListView.
For this I created a Custom ListView with this tutorial: http://www.ezzylearning.com/tutorial/customizing-android-listview-items-with-custom-arrayadapter
Now:
I pass the EditText value as a String with the help of an intent in tab 1, to tab 2.
//Intent to tab 2
Intent intent = new Intent(getBaseContext(), Tab2Activity.class);
intent.putExtra("values", streetName);
startActivity(intent);
In my Tab 2 (Tab2Activity) I receive this intent like this:
public void onResume (){
super.onResume();
Intent intent = getIntent();
Bundle bundle = intent.getExtras();
if (bundle != null) {
updateData(bundle);
}
}
public void updateData (Bundle bundle) {
String data = bundle.getString("values");
Toast.makeText(this, data, Toast.LENGTH_LONG).show();
Bostad bostad_data[] = new Bostad[]{new Bostad (streetName, money)};
adapter = new BostadAdapter(this, R.layout.listview_item_row, bostad_data);
listView.setAdapter(adapter);
adapter.notifyDataSetChanged();
...
}
I have two question (two problems).
1) I know that since I call "startActivity(intent) in Tab1 this will open up the activity and not in the tab. Is it possible to just switch tab and update the listView? (This isn't necessary. Only if it's an easy solution)
2) I get the activity with the right info up on my screen, but the listView in Tab2 isn't updated with this information. How can I fix this?
What I mean is, a row doesn't get added to the listview. What am I doing wrong?
Thanks for any help!
EDIT: Adding the onCreate in Activity2 as well.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tab2);
//Create listView and connect to the .xml (activity_tab2)
listView = (ListView) findViewById(R.id.listView1);
//Arrayen which the list will receive values from
Bostad bostad_data[] = new Bostad[]{
new Bostad("", "")
};
adapter = new BostadAdapter(this, R.layout.listview_item_row, bostad_data);
View header = getLayoutInflater().inflate(R.layout.listview_header_row, null);
listView.addHeaderView(header);
listView.setAdapter(adapter);
...
}
Edit 2: Adding BostadAdapter.java
public class BostadAdapter extends ArrayAdapter<Bostad> {
Context context;
int layoutResourceId;
Bostad data[] = null;
public BostadAdapter(Context context, int layoutResourceId, Bostad[] data) {
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
BostadHolder holder = null;
if(row == null) {
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new BostadHolder();
holder.gatunamn = (TextView)row.findViewById(R.id.gatunamn);
holder.totalkostnad = (TextView)row.findViewById(R.id.totalkostnad);
row.setTag(holder);
}
else {
holder = (BostadHolder)row.getTag();
}
Bostad bostad = data[position];
holder.gatunamn.setText(bostad.gatunamn);
holder.totalkostnad.setText(bostad.totalkostnad+" SEK per månad");
return row;
}
static class BostadHolder
{
TextView gatunamn, totalkostnad;
}
}
Edit 3: Adding Bostad.java
public class Bostad {
String gatunamn, totalkostnad;
public Bostad (){
super();
}
public Bostad (String gatunamn, String totalkostnad) {
super();
this.gatunamn = gatunamn;
this.totalkostnad = totalkostnad;
}
}
If I understand properly, I think what you are doing is creating a new activity that looks identical to tab 2 but isn't the same object. So that activity you start in startActivity() is the only one that gets the data. What I would suggest is using a ViewPager with fragments and interfaces to pass/update data from the parent activity. That may be a bit too advanced yet and it's not something you can easily write out as an answer, however there are a lot of tutorials on the process. As you're just starting out you may want to explore faster options but it is what I'd do.
A quick fix might be to access the tab host and replace the existing tab 2 activity with the activity you just made that has the data.

ListView displays item after 2nd item has been created

So I'm having a weird order of events in my code. It'll probably be something minor that I haven't seen yet. A have ListView that and is pulling the string from an EditText after button click.
The EditText lives in a dialog that's being pulled back to the main Activity by an interface
What happens now, is when I type something in the EditText field say "a", nothing shows up. But when I go to add another, "b", "a" shows up. and so forth. So one has to be created in order for the previous to show up.
Here's my what I have.
public class NewActivity extends FragmentActivity implements AddSiteDialog.AddSiteDialogListener {
ListView mSiteListView;
ArrayList<String> siteList = new ArrayList<String>();
CustomAdapter arrayAdapter = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_site);
mSiteListView = (ListView) findViewById(R.id.siteAddList);
arrayAdapter = new CustomAdapter();
mSiteListView.setAdapter(arrayAdapter);
Button b = (Button) findViewById(R.id.addSiteButton);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showDialog();
}
});
}
public void showDialog() {
FragmentManager fm = getSupportFragmentManager();
AddSiteDialog addSiteDialog = new AddSiteDialog();
addSiteDialog.show(fm, "main");
}
public void onSignIn(String inputText) {
siteList.add(inputText);
}
class CustomAdapter extends ArrayAdapter<String> {
CustomAdapter() {
super(NewActivity.this, R.layout.add_site, siteList);
}
public View getView(int position, View convertView, ViewGroup parent){
View row = convertView;
if (row == null){
LayoutInflater inflater = getLayoutInflater();
row = inflater.inflate(R.layout.list_row, parent, false);
}
((TextView) row.findViewById(R.id.textViewId)).setText(siteList.get(position));
return (row);
}
}
}
Can anyone spot where this is happening?
Simple.
call arrayAdapter.notifyDataSetChanged() in
public void onSignIn(String inputText) {
siteList.add(inputText);
//add that here
}
If the data which is backed by your adapter changes, you need to call notifyDataSetChanged() on your adapter to instruct the ListView to update itself.
I don't see anything like that in your code.
Just to add:
Your adapter implementation is sub-optimal - although in this case it doesn't really matter.
You should create a ViewHolder and store it as your View's tag, so that you can retrieve it if convertView is given. The ViewHolder should keep references to all sub-views of your view (TextView, ImageView, whatever you need to update). This would avoid the repeated call to findViewById() - which is slow.

How to set view or Activity for dealing with previous listactivity? for example "see full detail page"

This is my ListActivity after clicking on the list it will start a new activity which shows Full detail of each attraction place. I have no idea how to implement Full detail page. Can you guys show me some code of full detail activity which retrieve data from the previous list?
public class AttractionsListActivity extends ListActivity {
private static MyDB mDbHelper;
String[] from = new String[] { Constants.TITLE_NAME , Constants.ADDRESS_NAME };
int[] to = new int[] {R.id.place_title, R.id.place_address};
private Cursor c;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mDbHelper = new MyDB(this);
mDbHelper.open();
c = mDbHelper.getplaces();
setListAdapter(new SimpleCursorAdapter(this,
R.layout.list_place, c,
from, to));
final ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView parent, View view,int position, long id) {
Intent newActivity = new Intent(view.getContext(), Place.class);
startActivity(newActivity);
}
});
}
}
I have no idea how to implement this activity to deal with the action from AttractionslistActivity.Class
public class Place extends Activity {
private static final String CLASSTAG = Place.class.getSimpleName();
private TextView title;
private TextView detail;
private TextView location;
private TextView phone;
private ImageView placeImage;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.v(Constants.TAG, " " + Place.CLASSTAG + " onCreate");
this.setContentView(R.layout.detail_place);
this.title = (TextView) findViewById(R.id.name_detail);
//title.setText(cursor.getString(Constants.TITLE_NAME));
this.detail = (TextView) findViewById(R.id.place_detail);
this.location = (TextView) findViewById(R.id.location_detail);
this.phone = (TextView) findViewById(R.id.phone_detail);
this.placeImage = (ImageView) findViewById(R.id.place_image);
}
}
Override onListItemClick(...) in your List Activity, using the Cursor get the id of the selected item
Start your Detail Activity passing the id through the intent extras
In your Detail Activity, recover the id and open a cursor to get your data back from the DB.
Fill your view with the data
The Android Notepad Tutorial includes an example of exactly this, if I understand the question correctly.
First of all sorry for the late answer,
in your adapter class you can use item click listener achieve this easily, please do the following steps for achieving this.
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(
AdapterView parent, View view,int position, long id) {
Intent newActivity = new Intent(
view.getContext(), Place.class);
startActivity(newActivity);
}
});
for passing list item details into next screen you can use intent extras.before calling start activity u need pass the extras like below.
newActivity.putExtra("name", c.place);
newActivity.putExtra("description", c.placeDscription);
newActivity.putExtra("distance", c.distance);
after u need to call ---> startActivity(newActivity);
if you want pass string, Integer, float, boolean etc...types of data you can like above code.

Categories

Resources