How to add EditText's value to the listview items? - java

I want to add the content from an EditText to a ListView here is my code that dosen't work:
mass = userInput.getText().toString();
//fruits is a String[]
final List<String> fruits_list = new ArrayList<String(Arrays.asList(fruits));
final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(context.getApplicationContext(), android.R.layout.simple_list_item_1, fruits_list);
fruits_list.add(mass);
lv.setAdapter(arrayAdapter);
The code adds the item to the listview but when the process is repeated it replaces the previously added string from the EditText.

Your code appears to create a new fruits_list array every time you read the user's entry from the EditText. This will result in only the latest entry being added to your list, replacing any previously added entries.
You need to create the array once (probably as a class member) and then update it each time you read the user input, e.g. something like:
private ArrayList<String> fruits_list;
private ArrayAdapter<String> arrayAdapter;
...
public void initialise(Context context) {
fruits_list = new ArrayList<>(Arrays.asList(fruits));
arrayAdapter = new ArrayAdapter<>(context, android.R.layout.simple_list_item_1, fruits_list);
lv.setAdapter(arrayAdapter);
}
....
public void getInput(
mass = userInput.getText().toString();
fruits_list.add(mass);
arrayAdapter.notifyDataSetChanged();
}
Note the use of arrayAdapter.notifyDataSetChanged() to signal that new data has been added to the underlying data set.
As #Aaron says, you should also look at RecyclerView as a possible replacement, although that's a little bit more complicated to set up.

Related

ArrayAdapter crashes when adding new items to adapter

I am facing a problem that when I try to dynamically add items to my spinner the app crashes. So first I add an array from Strings.xml my R.array.restrictions contains 16 items therefore I am inserting each key into 16 and then adding it onto the next position. and after that I load each item from firebase and add it to the adapter, then I set the adapter, so in my mind it should work. Any ideas why it causes a crash? Says:
UnsupportedOperationException at
java.util.AbstractList.add(AbstractList.java:148)
Thanks.
public void startSpinner(){
//built in Profiles
spinner = (Spinner) findViewById(R.id.spinnerProfiles);
adapter = ArrayAdapter.createFromResource(this, R.array.restrictions, android.R.layout.simple_spinner_item);
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// This method is called once with the initial value and again
// whenever data at this location is updated.
map = (Map<String, Object>) dataSnapshot.child("users").child(userID).getValue();
ArrayList<String> array = new ArrayList<>();
int x = 16;
for (Map.Entry<String,Object> entry : map.entrySet()) {
// key contains Profile Name
String key = entry.getKey();
adapter.insert(key, x);
x++;
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
//Auto Generated Method
}
});
adapter.setDropDownViewResource(android.R.layout.simple_list_item_1);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(this);
}
Perhaps the problem is that you are changing an array that is coming from resources. This can happen as the list you are using is not created by you.
You can try the following:
ArrayList<CharSequence> array = new ArrayList<CharSequence>(Arrays.asList(context.getResources().getTextArray(R.array.restrictions)));
adapter = new ArrayAdapter<>(context, android.R.layout.simple_spinner_item, array);

why spinner view appears shrunk when called asynchronously in Android

Background
When I fill a spinner using a resource array, things work just fine:
Spinner countryCodeSpinner = (Spinner) findViewById(R.id.country_code_spinner);
countryCodeSpinner.setOnItemSelectedListener(this);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
R.array.country_codes_array, android.R.layout.simple_spinner_item);
where country codes are read from a resource:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string-array
name="country_codes_array">
<item>971</item>
<item>961</item>
<item>628</item>
<item>193</item>
<item>477</item>
</string-array>
</resources>
output:
Question
but when I fill up the spinner contents from an api call like so:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
..
Spinner currencySpinner = (Spinner) findViewById(R.id.currency_spinner);
populateCurrency(currencySpinner);
private void populateCurrency(final Spinner spinner) {
_currencies = new HashMap<String, String>();
final Context context = this;
// getting the contents of spinner from api call
new SyncHelper().get(CreateOrderActivity.this,
Connections.CURRENCIES(CreateOrderActivity.this),
null, null, new SyncListener() {
#Override
public void onSuccess(String data, int requestCode) {
try {
JSONObject object = new JSONObject(data);
if (object.getString("errors") == "false") {
JSONArray currenciesArray = object.getJSONObject("data")
.getJSONArray("currencies");
for (int i=0; i< currenciesArray.length(); i++) {
String currencyRef = currenciesArray.getJSONObject(i).getString("ref");
String currencyId = currenciesArray.getJSONObject(i).getString("id");
_currencies.put(currencyRef, currencyId);
}
String[] currencyrefs = Arrays.copyOf(_currencies.keySet().toArray(),
_currencies.keySet().toArray().length, String[].class);
ArrayAdapter<String> adapter =
new ArrayAdapter<String>(context, android.R.layout.simple_spinner_item,currencyrefs);
spinner.setAdapter(adapter);
then the spinner rendered view is all shrunk like so:
even though in both cases, we're using android.R.layout.simple_spinner_item.. any idea how to fix this?
I wasn't able to reproduce the issue, for me the first example gives an output similar to the second example and second example gives the same output (No margins, height is set to wrap_content, also for the second example, I only used the same adapter constructor to simulate). The difference in behavior might be because of the different APIs (I used an emulator with API 26).
However, to me your first and desired output looks like simple_spinner_dropdown_item instead of simple_spinner_item and I was able to produce a similar spinner with simple_spinner_dropdown_item, so you might want to check it out.

Adding items to an array list by clicking on an item from an arraylist in another activity

I know I am Probably making a bigger deal out of this but here is my problem:
I basically want to be able to make a playlist from a list of songs. As each song/item is clicked it adds it to another arraylist in another activity.
Please help it so frustrating:
here is my code..
public class SDLTlist extends ListActivity {
// Songs list
public ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.ltsdlist);
ArrayList<HashMap<String, String>> songsListData = new ArrayList<HashMap<String, String>>();
ImportSD plm = new ImportSD();
// get all songs from sdcard
this.songsList = plm.getPlayList();
// looping through playlist
for (int i = 0; i < songsList.size(); i++) {
// creating new HashMap
HashMap<String, String> song = songsList.get(i);
// adding HashList to ArrayList
songsListData.add(song);
}
// Adding menuItems to ListView
ListAdapter adapter = new SimpleAdapter(this, songsListData,
R.layout.playlist_item, new String[] { "songTitle" }, new int[] {
R.id.songTitle });
setListAdapter(adapter);
};
});
}
}
The above class imports songs using MEDIA_PATH with file extensions .MP3 (which is called in another class called importSD) and lists them in an array, as I select an item from that list I want it to be added to another list in a different activity. Should I use the onItemClickListners function? If so how would I do it?
You can either:
A. Keep the ArrayList you want to add to outside the Activities (ie. In a class that overrides Application) and then add it while still in the second Activity.
or
B. Pass the selected Array of data back to the Activity and handle it in OnActivityResult by pulling out the list you passed back.
IE. If you have a String[], you could pull that out of the passed-back Intent with:
data.getStringArrayExtra("my_string_array_name")
You can always create a global application class that can be shared across all your activities:
package com.example.app;
import android.app.Application;
import java.util.ArrayList;
public class GlobalVars extends Application {
public ArrayList<String> aList;
public GlobalVars() {
aList = new ArrayList<String>();
}
}
Then in each Activity you can get the global class like this:
gVars = (GlobalVars) getApplication();
gVars.aList.add("Adding a String");
Make sure to add this Application class correctly to your AndroidManifest.xml.

How to Fill a Spinner with Database Info

I have a spinner that I need to fill with information from a database, but the examples that i found don't work.
Here is my code:
public void consulta() {
AdminSQLiteOpenHelper admin =
new AdminSQLiteOpenHelper(this, "administracion", null, 1);
SQLiteDatabase bd=admin.getWritableDatabase();
Cursor c = bd.rawQuery("select name from category",null);
startManagingCursor(c);
// create an array to specify which fields we want to display
String[] from = new String[]{"name"};
// create an array of the display item we want to bind our data to
int[] to = new int[]{android.R.id.text1};
// create simple cursor adapter
SimpleCursorAdapter adapter =
new SimpleCursorAdapter(this, android.R.layout.simple_spinner_item, c, from, to );
adapter.setDropDownViewResource( android.R.layout.simple_spinner_dropdown_item );
// get reference to our spinner
spinner1.setAdapter(adapter);
bd.close();
}
This is how I do it:
db = SQLiteDatabase.openDatabase("/data/data/packagename/databases/mydata.db", null, SQLiteDatabase.OPEN_READONLY);
Cursor c_cat = db.rawQuery("select _id, column_desc from your_table", null);
startManagingCursor(c_cat);
spinner = (Spinner) findViewById(R.id.spinnername);
String[] from = new String[]{"column_desc"};
int[] to = new int[]{android.R.id.text1};
SimpleCursorAdapter mAdapter = new SimpleCursorAdapter(this, android.R.layout.simple_spinner_item, c_cat, from, to);
mAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(mAdapter);
db.close();
I did all that in my onCreate. I declared all my variables outside the method so that they are public to the whole class. One thing I made a mistake of in the past was closing the cursor after filling the spinner. The cursor must remain open if you want to see data in the spinner.
I hope this solves it for you.
EDIT: I noticed you are not querying for _id in your rawQuery. You must include that if you wish to populate the spinner. Analyze the code I provided.
Assuming you didn't leave any code out, you need to find/define spinner1, so that the framework knows where to put your info from the adapter.
private Spinner spinner1;
spinner1 = (Spinner) view.findViewById(R.id.yourspinnerid);
// rest of your code

Show two columns from SQLite as same string in a listview in android

Hi I am developing an android in which I am loading data from database and showing it in a List View.
My code is as follows
public class rel extends ListActivity {
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.refill);
//Creating an object called mydbhelper
Dbms mydbhelper = new Dbms(this);
//Loading the database in writable format
SQLiteDatabase db=mydbhelper.getWritableDatabase();
String[] id= new String[]{"_id","medicine","hs"};
//Cursor
Cursor c = db.query("medicines",id,null,null,null, null,null);
startManagingCursor(c);
String[] from = new String[]{"medicine"};
int[] to = new int[] { R.id.textlist1};
// Now creating an array adapter and set it to display using my row
SimpleCursorAdapter notes =new SimpleCursorAdapter(this, R.layout.notes_row, c, from, to);
setListAdapter(notes);
}
What i want to achieve is show a list view as "Medicine-hs" in which medicine is from one column and hs is from an another column of database. For example as
XYZ-HS1
ABC-HS2
as the listview contents
How to achieve this?
Right now I am able to get only Medicine
Please give your kind suggestions
}
I want to say replace this:
String[] from = new String[]{"medicine"};
int[] to = new int[] { R.id.textlist1};
with this:
String[] from = new String[]{"medicine", "medicine-hs"};
int[] to = new int[] { R.id.textlist1, R.id.textlist2};
You will of course need to have a R.id.textlist2 available to use in your layout.
EDIT: Reverted back to the previous revision, which solved the problem.
What you could do is execute the rawQuery() method off the DBHelper class with SQL that combines the fields like so:
SELECT medicine + "-" + hs AS medicineHs FROM medicines ...
so the string array would be
String[] from = new String[]{"medicineHs"};

Categories