I am using data store in Assets folder like "reader.txt" this data get in using "InputStream" geting string value like this set to String value in textview. My question is how to store String in listview?
Here is my code:
try {
InputStream is = getAssets().open("reader.txt");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
// Convert the buffer into a string.
String text = new String(buffer);
TextView tv = (TextView) findViewById(R.id.list);
tv.setText(text);
} catch (IOException e) {
// Should never happen!
throw new RuntimeException(e);
}
There are two ways by which you can store strings in listView. Either you can use android:entries which takes an array or object resource as an input, or u can use ArrayAdapter to set entries in listView.I will show you an example.
String[] values={""}//whatever values you have shown in the TextView
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, android.R.id.text1, values);
// Assign adapter to ListView
listView.setAdapter(adapter);
You can read text from file, then store it into String[] and then use ListAdapter for example ArrayAdapter<String> with ListView.
ListView list = (ListView) findViewById(R.id.someId);
your work with file ...
list.setAdapter(new ArrayAdapter<String>(Context, Layout, data));
// data is String[]
Here is similar example:
ArrayAdapter sample program in
Android
Difference with yours is that your String[] will be dynamically generated from file. So at first you will prepare data from file, store them into String[] and set them into Adapter.
Related
I'm using string array which I'm passing to ArrayAdapter for spinner item.
my array size(usually less than 10) and values are variable (I'm taking it from asset file)
if I'm using this :
String[] arr = new String[10];
protected void onCreate(Bundle savedInstanceState) {
breader = new BufferedReader(new InputStreamReader(getAssets().open(path)));
int length = Integer.parseInt(breader.readLine());
for(int i=0; i<length; i++){
arr[i]=breader.readLine();
initialize();
....
}
initialize(){
spinner1 = (Spinner) findViewById(R.id.spinner1);
ArrayAdapter<String> array = new ArrayAdapter<String>(Activity.this, android.R.layout.simple_spinner_item, arr);
spinner1.setAdapter(array);
}
it shows NullPointerException at spinner1.setAdapter(array); line.
can I reassign array length. I think its not possible.
because of you add null when no data in last portion of array.
I mean there are 7 data in assest file and you move for loop 10 times so after 7 data Add there are null represent. so breader.readLine(); read null and add it to your string array and when you parse StringArray to Array Adapter there are null get on 8th position of array and nullpointer Exception fire.
So just check breader.readLine() != Null then add it to String of Array otherwise add some Temp text.
Or
You Also Use ArrayList instead of String[] Array.
ArrayList is dynamically Arraylist you can add data to list useing array.add(yourdata).
Thats it...
I have a ListView with some items, but after I update a Database I'd like to "refresh" the ListView. Anyone can help me?
EDIT: populateListView add items to ListView
public void populateListView()
{
String URL = config.getUrl_For_Query() + ",&nameq=Select&tipo=select"; // my URL
String jsonString = reading.execute_query(URL); // jsonString is formatted well
try
{
JSONObject jsonResponse = new JSONObject(jsonString);
JSONArray array = jsonResponse.getJSONArray("elenco");
for (int i=0; i<array.length(); i++) // I scan all array
{
JSONObject nameObj = (JSONObject)array.get(i);
// I retrieve all information
allNames.add(nameObj.getString("name")); // Name
allLng.add(nameObj.getString("lng")); // Another information
}
}
catch (Exception e)
{ e.printStackTrace(); }
List<String> Array = new ArrayList<String>();
for(int i=0;i<allNames.size();i++) // I add all values
{
String value = allNames.get(i).toString() + ", \n\t" + allLng.get(i).toString();
Array.add(value); // here I populate my Array
}
final ListView listView = (ListView) getActivity().findViewById(R.id.List);
listView.setAdapter(new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, Array));
//
// Click
//
}
saveChanges
public void saveChanges()
{
// I update a Database
// And then I'd like to refresh ListView's items
populateListView(); // Update ListView
}
Use a Comparator. There you define what to compare and how, in the compare() method you define what should be returned from two of your instances. Here's an example for a String Comparator.
Comparator myComparator = new Comparator<String>() {
public int compare(final String user1, final String user2) {
// This would return the ASCII representation of the first character of each string
return (int) user2.charAt(0) - (int) user1.charAt(0);
};
};
adapter.sort(myComparator);
This way, when you add an item, you don't have to recreate the whole Adapter but it will be sorted instead. But don't forget to call .notifyDataSetChanged() on your adapter, this will make (amongs other things) to refresh your layout.
Try using ArrayAdapter.insert method to insert objects in specific index.
At first take a look at this tutorial about SQlite database in Android.
So, your problem is that new items are added at the end of the list. Huh? This is because you have not notified Adapter from the changes of the Array.
ArrayAdapter<String> Adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, Array);
Your first solution is to clear Adapter before updating Database. Sth like:
Adapter.clear(); can do that. This way your Adapter is empty before updating database and new items are inserted. You can use Adapter.notifyDataSetChanched(); for awaring Adapter about the changes.
In above tutorial there is a custom Adapter. It uses this code:
List<String> Array = new ArrayList<String>();
Array = (ArrayList<String>) db.getAllContacts();
Adapter = new MyCustomAdapter(getActivity() [in fragment case or getApplicationContext() in Activity case], R.layout.simple_list_item_1, Array);
This way there is no need for clearing Adapter because it automatically does that. Wherever you use this method, updated adapter is used for showing the list.
As I am new to android development i struck up with a problem where i am unable to set data to spinner adapter..
Here i am getting data from database is like
String times = [09:30,10:30,12:15,04:45,10:50]
I am getting array in this pattern. When i am trying to set this array to spinner adapter it's getting error...
dateadp=new ArrayAdapter<CharSequence>(this, android.R.layout.simple_spinner_dropdown_item,times);
datespn.setAdapter(dateadp);
so how to convert the following array to string array and how i can append that data to spinner. Can anyone help me with this....
If
["09:30","10:30","12:15","04:45","10:50"] represents String abc.
Then you can take following approach.
String processingString = abc.substring(abc.indexOf("[") + 1,
abc.indexOf("]"));
String[] arr = processingString.split(",");
ArrayAdapter < String > adapter = new ArrayAdapter < String > (this,
android.R.layout.simple_list_item_1, arr);
I think you struck with converting arraylist to String array. if you are getting data into the arraylist then the code is here.
ArrayAdapter<String> dateadp;
timesArray= times.toArray(new String[times.size()]);
dateadp=new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item,timesarray);
datespn.setAdapter(dateadp);
I am currently using a simpleCursorAdaptor and a cursor to load a spinner with data, however I would prefer to convert the cursor to a simple array and use this instead (as the list is short and static).
What's the simplest way of doing this?
My code currently is:
private void loadEmployeeList(){
LoginDataHandler dataHandler = new LoginDataHandler(getContentResolver());
Cursor data = dataHandler.activeEmployeeList();
if (null!=data){
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
android.R.layout.simple_spinner_item,
data,
new String[]{MyobiliseData.Columns_employees.NAME},
new int[] { android.R.id.text1 }
);
// Attach the data to the spinner using an adaptor
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
}
}
ArrayList<String> mArrayList = new ArrayList<String>();
for(data.moveToFirst(); !data.isAfterLast(); data.moveToNext()) {
mArrayList.add(data.getString(data.getColumnIndex(MyobiliseData.Columns_employees.NAME)));
}
now you can proceed as you have an array mArrayList of cursor's data,
If it is short and static, you might consider putting it in your strings.xml as an array and accessing it that way rather than incurring somewhat greater overhead of reading from a DB and translating to an array.
data.xml
<resources>
<string-array name="States">
<item>AL</item>
<item>AK</item>
<item>AR</item>
</string-array>
</resources>
Then to use it for your spinner:
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
getActivity(), R.array.States, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(R.layout.listlayout_black);
final Spinner states = (Spinner) v.findViewById(R.id.mbr_state_spinner);
states.setAdapter(adapter);
Then you have to write a logic for iterating over cursor and fetch data. Create array with these data you got from cursor.
Here you go
ArrayList<String> list = new ArrayList<String>();
Cursor data = dataHandler.activeEmployeeList();
if (data.moveToFirst())
{
do {
list.add(data.getString(data.getColumnIndex(MyobiliseData.Columns_employees.NAME)));
} while (data.moveToNext());
}
I have the code as below
String[] myList = new String[] {"Hello","World","Foo","Bar"};
ListView lv = new ListView(this);
myList[4] = "hi";
lv.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,myList));
setContentView(lv);
The app is force closing,in logs im getting "java.lang.UnsupportedOperationException" if i remove myList[4] = "hi"; code I'm getting the listview as in myList array. But my problem is i have to add string dynamically to this array and have to display.
Don't use array. Array has fixed length and you cannot add new items to it. Use list instead:
List<String> myList = new ArrayList<String>();
myList.add("Hello");
myList.add("World");
myList.add("Foor");
myList.add("Bar");
ListView lv = new ListView(this);
myList.add("hi");
You cannot simply add another element to the array. When you declare your array as
String[] myList = new String[] {"Hello","World","Foo","Bar"};
Your array is created with four elements in it. When you are trying to set myList[4], you're essentially trying to set a fifth element - and are obviously getting ArrayIndexOutOfBoundsException.
If you need to dynamically add elements, you are better off using ArrayList instead of an array.
Since your array contains 4 items, myList[4] is actually out of bounds. The maximum element index will be myList[3]. Sure this is the issue.
you are trying to add element at 5th position. Arrays don't grow dynamically. why dont' you try like this,
String[] myList = new String[] {"Hello","World","Foo","Bar"};
ArrayList<String> mList=new ArrayList<String>();
Collections.addAll(mList,myList);
ListView lv = new ListView(this);
mList.add("Hi");
lv.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,mList));
setContentView(lv);