Displaying values in an ArrayList using ArrayAdapter - java

I am attempting to create a ListView to display values entered via an EditText. I am using an ArrayList and ArrayAdapter but I am afraid I don't fully understand how they work.
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, android.R.id.listView1, num1);
I am unsure why I am unable to use android.R.id.listView1 where listView1 is the id of my list view in the activity. Is this not the resourceid that the adapter needs to list off my ArrayList?
Below is my full method and delcarations. Sorry if I am being vague in my questions, I don't fully know which terminology to use for what and I don't intend to cause confusion.
public ArrayAdapter<String> adapter;
ArrayList<String> allScores = new ArrayList<>();
ListView listScores = (ListView)findViewById(R.id.listView1);
public void onButtonClick(View V){
EditText input1 = (EditText) findViewById(R.id.scorePrompt);
TextView output1 = (TextView) findViewById(R.id.textTotal);
String blankCheck = input1.getText().toString(); //CHANGE INPUT IN scorePrompt TO STRING
TextView output2 = (TextView) findViewById(R.id.custName); //TEST FOR ARRAY LIST DISPLAY
if (blankCheck.equals("")) {
Toast blankError = Toast.makeText(getApplicationContext(), "YOU CANT SKIP HOLES JERK", Toast.LENGTH_LONG);
blankError.show();
} else {
//savedScores.add(input1.getText().toString());//Save input into array list
int num1 = Integer.parseInt(input1.getText().toString()); //Get input from text box
int sum = num1 + score2;
score2 = sum;
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, android.R.id.listView1, num1);
output1.setText("Your score is : " + Integer.toString(sum));
input1.setText(""); //Clear input text box
}
};
For some background information on my intentions, I want the user to enter integers in an EditText, save these values in an ArrayList, and then populate a ListView line-by-line with the values the user entered. Thank you for the help.

Try This way.
ArrayAdapter<String> itemsAdapter =
new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, items);
ListView listView = (ListView) findViewById(R.id.listView1);
listView.setAdapter(itemsAdapter);

here you have to use setadapter of listview not put in the adapter
try this
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,allscores);
listscores.setAdapter(adapter)
if you want to add input things than make an Arraylist and simply pass it in adapter's third parameter

Related

ListView does not display the first row value

UPDATE: PROBLEM FIXED -
The ActionBar was covering the first item on the list.
SOLUTION: Android AppBarLayout overlaps listview
In my program, I am retrieving data from the database and displaying it using List View.
However, the first row elements are always skipped in the process and the display begins from the second row.
public void displaydata(){
Cursor res = myDb.getAllData();
lv = (ListView) findViewById(R.id.idListView);
if(res.getCount() == 0){
//show message
return;
}
ArrayList<String> buffer = new ArrayList<>();
while(res.moveToNext()){
buffer.add(res.getString(1));
};
ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1,buffer);
lv.setAdapter(adapter);
}
How do I make it display from the first row?
Any help is appreciated, thanks.
EDIT: I have tried all suggested answers of using a 'do-while' and a 'for loop', all of which give the same result.
Try changing
while(res.moveToNext()){
buffer.add(res.getString(1));
};
to
Edit: change the while so it increments after:
do {
buffer.add(res.getString(1));
} while (cursor.moveToNext());
Personally, I would recommend a CursorAdapter when using a database.
lv = (ListView) findViewById(R.id.idListView);
String from = { COLUMN_NAME };
int[] to = { android.R.id.text1 };
SimpleCursorAdapter adapter =
new SimpleCursorAdapter(this, android.R.layout.simple_list_item_1,
myDb.getAllData(),
from, to);
lv.setAdapter(adapter);
Try out this this code may be useful for fetching data from db using cursor.
public ArrayList<BasicInfo> getFetchBasicInfo() {
ArrayList<BasicInfo> data = new ArrayList<BasicInfo>();
String sql = "select * from basic_info;
Cursor c = fetchData(sql);
if (c != null) {
while (c.moveToNext()) {
String FirstName = c.getString(c.getColumnIndex("first_name"));
String LastName = c.getString(c.getColumnIndex("last_name"));
String Sabcription = c.getString(c
.getColumnIndex("salutation_id"));
data.add(new BasicInfo(FirstName, LastName));
}
c.close();
}
return data;
}

Subitems for items in array and get their data to a variable and change item in array

I have created this in an activity:
protected void onClickSunSea(View v) {
persons = (EditText) findViewById(R.id.txtPerson);
days = (EditText) findViewById(R.id.txtDays);
String p = persons.getText().toString();
String d = days.getText().toString();
String [] array = getResources().getStringArray(R.array.sunsea);
Intent myintent = new Intent(MainActivity.this, MainActivity.class);
myintent.putExtra("PERSONS", p);
myintent.putExtra("DAYS", d);
myintent.putExtra("PLACES",array);
startActivity(myintent);
}
To send to this activity:
String person = getIntent().getStringExtra("PERSONS");
String day = getIntent().getStringExtra("DAYS");
TextView txtPerson = (TextView) findViewById(R.id.txtViewPersons);
txtPerson.setText("Persons travelling: " + person);
TextView txtDay = (TextView) findViewById(R.id.txtViewDays);
txtDay.setText("Days of traveling: " + day);
String[] arrayCityBreak = getIntent().getStringArrayExtra("PLACES");
ArrayAdapter<String> adapterCityBreak = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, arrayCityBreak);
ListView myview = (ListView) findViewById(R.id.lstView);
myview.setAdapter(adapterCityBreak);
I have made these arrays in strings.xml:
<resources>
<string name="app_name">Assignment</string>
<array name="citybreak">
<item>Barcelona, Spain</item>
<item>Berlin, Germany</item>
<item>Copenhagen, Denmark</item>
<item>Gothenburg, Sweden</item>
<item>Milan, Italy</item>
</array>
<array name="sunsea">
<item>Alicante, Spain</item>
<item>Antalya, Turkey</item>
<item>Athens, Greece</item>
<item>Florida, USA</item>
<item>Gran Canaria, Spain</item>
</array>
<array name="skisnow">
<item>Kiruna, Sweden</item>
<item>Trondheim, Norway</item>
<item>Salzburg, Austria</item>
<item>Kittila, Finland</item>
<item>Ivalo, Finland</item>
</array>
I want to insert a subitem with a price inside it, for example:
Barcelona, Spain
200
And then get that "200" value in a variable and change it, and then put it back in the array to write it out with the new value + some text before it. Like this:
Barcelona, Spain
the cost for 2 persons is 400
Can anyone help me with that?
Hope you understand my question.
First of all you should use some kind of Map for this data, so you'll be able to have a pair where city name will be a key and the price will be a value. The bad news is that you can't save Map in the resources. But you can "emulate" it, for example use "|" as a separator:
<array name="citybreak">
<item>Barcelona, Spain|200</item>
<item>Berlin, Germany|300</item>
<item>Copenhagen, Denmark|250</item>
<item>Gothenburg, Sweden|500</item>
<item>Milan, Italy|700</item>
</array>
Then you can parse these strings and create a Map from it. Check this answer as an example. When you'll have a Map, you can pass it to your second activity, modify prices there and then send it back with new prices.

Combine String Array and Iterator and sort

I have 2 sets of values in my app - 1 from resources file and 1 from sharedpreferences. Is there an easy way to combine these both and create a Sorted List for the adapter? Here is my code:
Spinner copyFromCity = (Spinner) findViewById(R.id.spinner);
Resources res = getResources();
String [] predefinedCities = res.getStringArray(R.array.predefined_cities);
// Necessary to add Iterator String to an adapter
ArrayList<String> sortedPredefinedCities = new ArrayList<String>();
ArrayAdapter<CharSequence> adapter = new ArrayAdapter(
this,
android.R.layout.simple_spinner_item,
new ArrayList(Arrays.asList(predefinedCities)));
// Add values from our custom cities onto the Adapter via SharedPreferences
prefs = getSharedPreferences(MY_PREFS_NAME, Context.MODE_PRIVATE);
Iterator<String> userCities = readCitiesFromPref(); // unsorted values
while(userCities.hasNext()){
adapter.add(userCities.next());
}
/* TODO Way to sort both these values into alphabetical order */
// Specify the layout to use when the list of choices appears
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
copyFromCity.setAdapter(adapter);
Adding readCitiesFromPref() method for clarifying why Iterator is being returned
protected Iterator<String> readCitiesFromPref() {
// See if preferences store this
JSONObject citiesList = null;
Iterator<String> userCities = null;
try {
// Yes, so get the values out
citiesList = new JSONObject(prefs.getAll());
userCities = citiesList.keys();
} catch (NullPointerException e1) {
//TODO
}
return userCities;
}
What I think is add those arrays/list to a List, sort and set it to adapter
String [] predefinedCities = res.getStringArray(R.array.predefined_cities);
prefs = getSharedPreferences(MY_PREFS_NAME, Context.MODE_PRIVATE);
Iterator<String> userCities = readCitiesFromPref(); // unsorted values
List<String> copyOfCities = new ArrayList<String>();
while (userCities.hasNext()){
copyOfCities.add(userCities.next());
}
ArrayList<String> sortedCities = new ArrayList<String>();
sortedCities.addAll(copyOfCities);
sortedCities.addAll(Arrays.asList(predefinedCities));
Collections.sort(sortedCities);
ArrayAdapter<CharSequence> adapter = new ArrayAdapter(
this,
android.R.layout.simple_spinner_item,
sortedCities);
You can do like this:
Convert the string array to a List
convert the Iterator to List
Combine them
Sortthem like Collections.sort(yourCombinedList);
feed them to the adapter

Refresh the current item of a Spinner

Consider the following combo list
comboList = new Spinner(this);
list_arr = new ArrayList<String>();
The ArrayList is filled with Strings from SharedPreferences and the Spinner is populated in this way
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, list_arr);
comboList.setAdapter(dataAdapter);
Then it gets updated in case of an event OnClickListener()
list_arr.clear();
ArrayList<String> res = getMyLists();
for (int i = 0; i < res.size(); i++) {
list_arr.add(res.get(i));
}
How can I refresh also the already selected item programmatically?
From the GUI, I have to manually select another value from the list and then change it back.
This could be a duplicate of this other question but it is very old and unanswered.
You may have to call dataAdapter.notifyDataSetChanged();
In this case, you'll need to re-create the spinner's adapter:
list_arr.clear();
ArrayList<String> res = getMyLists();
for (int i = 0; i < res.size(); i++) {
list_arr.add(res.get(i));
}
dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, list_arr);
comboList.setAdapter(dataAdapter);

how to get values from dynamically created edittexts

I have created a tablelayout with dynamically created rows with 3 edittexts on every row. Say there are 5 rows with 3 edittexts on each, how can i get the the entered values from every first edittext from each row into an arraylits and calculating them.
Here is my code so far:
Public void addRow (View v) {
TableRow row = new TableRow(this);
EditText et1 = new EditText(this);
EditText et2 = new EditText(this);
EditText et3 = new EditText(this);
idCount++;
mRowCount++;
et1.setTag(a + idCount);
et1.setText(a + idCount);
et2.setTag(b + idCount);
et2.setText(b + idCount);
et3.setTag(c + idCount);
et3.setText(c + idCount);
mLayout.addView(row);
row.setId(mRowCount);
row.addView(et1);
row.addView(et2);
row.addView(et3);
Thanx in advance
ArrayList<String> stringList = new ArrayList<String>(); //Generic ArrayList to Store your Strings
stringList.add(et1.getText()) ;//do this for your 3 textviews
stringList.add(et2.getText()) ;
stringList.add(et3.getText()) ;
int count=0;
Iterator<String> iterator = stringList.iterator();
while (iterator.hasNext()) {
count=count+Integer.parseInt(iterator.next());
}
1) If you have the reference, you can access it with getText().
2) If you haven't the reference, you have to set an ID to every EditText and the you could reach them with findViewById()
by the getText() method
edt1.gettext();
If you are entering string data then use toString() method as
String res=edt1.getText().toString();
Depending how many rows you are likely to end up creating I would store a reference to the EditText objects when you create them. This may mean defining a row object for holding the three EditText objects, but just as east to create a Map:
Map<String, List<EditText>> mRows = new HashMap<String, List<<EditText>>();
When creating the new row you can modify your code so as to store the references:
Public void addRow (View v) {
TableRow row = new TableRow(this);
EditText et1 = new EditText(this);
EditText et2 = new EditText(this);
EditText et3 = new EditText(this);
List<EditText> row = new ArrayList<EditText>();
row.add(et1);
row.add(et2);
row.add(et3);
mRows.add("" + idCount, row);
I would also move that code into a separate function.
On submission you can now iterate over the map and pull the first entry out from each entry.
First of all you have to take EditText(View) from your table layout and
TableRow tr = (TableRow) v.getParent();
// Index of column of table layout it should be an Integer value.
EditText et = (EditText) tr.getChildAt(Your_Index);
EditText et1 = (EditText) tr.getChildAt(Your_Index);
EditText et2 = (EditText) tr.getChildAt(Your_Index);
Then you will get value of that edittext with following code
String a = et.getText().toString();
String b = et1.getText().toString();
String c = et2.getText().toString();
Hope it will help you.

Categories