What I'm trying to is making a list which contains series of numbers like [1,2,3,4,5,6...100].
In Java, it is simple using 'range' so I tried to find similar class in android.
Therefore, I found that some classes like Range and Intstream, but I don't know how to use them.
I'll be appreciated if you teach me how can I get my purpose, thanks.
You could write a simple function which would look like this:
public List<Integer> buildList(int maximum) {
List<Integer> list = new ArrayList();
for (int i = 1; i <= maximum; i++) {
list.add(i);
}
return list;
}
And a call which produces your desired result would look like this:
List<Integer> list = buildList(100);
If you want an array instead of a list, do this:
int[] array = list.toArray(new int[list.size()]);
int size = 100;
ArrayList<Integer> list = new ArrayList<>(size);
for (int i = 1; i <= size; i++) {
list.add(i);
Log.i("Value is = ", i+"");
}
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(1);
list.add(2);
list.add(3);
.....
You don't need to define the size because ArrayList is dynamically
while in some other language we use list[index] to get the value.
But here we use list.get(index) to do that.
I am trying to create a layout, that shows current 3 hour lessons along with the time and date with room number.
possible screens:
The room and time/date is always static at the top and the rest would be dynamic from calls in SQL from JSON.
data = idleResponse.getJSONArray("lecture");
ArrayList<String> lects = new ArrayList<String>();
for (int i = 0; i < data.length(); i++) {
JSONObject jObj = data.getJSONObject(i);
String time = jObj.getString("startTime"); // to do.substring(0, 4);
String moduleName = jObj.getString("moduleName");
lects.add(time + " " + moduleName);
}
String[] lectureList = new String[lects.size()];
for (int i = 0; i<lects.size();i++){
// fill with data
lectureList[i] = lects.get(i);
}
lecture.setText("Upcomming Lectures:");
//set to list view
ListView listitems=(ListView)findViewById(R.id.listView1);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,lectureList);
listitems.setAdapter(adapter);
I tried to implement this with a list view, however it just shrinks down to a small section of the screen based on number of elements.
as you can see it just shrinks down.
I was wondering what would be the best type of layout to use for this type of problem, all of my layouts are pretty basic and something like this seems quite a challenge for me thanks.
You would have to write your own Adapter for listview and use weight property for layout of each row
I have two lists of Default and Chrome browsers history.
I want to merge these two lists into one list.
I need to update item if I find it duplicate (is common between two lists).
So, my "BrowserRecord" class is like this:
public class BrowserRecord {
private long id;
private int bookmark;
private long created;
private long date;
private String title;
private String url;
private long visits;
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
BrowserRecord record = (BrowserRecord) o;
return url.equals(record.url);
}
#Override
public int hashCode() {
return url.hashCode();
}
// other getter setter methods
...
}
and finally, I have a method that gets browsers histories and does merging:
public List<BrowserRecord> getHistory() {
List<BrowserRecord> browserList = new ArrayList<BrowserRecord>();
// get history of default and chrome browsers
List<BrowserRecord> defaultList = getDefaultBrowserHistory();
List<BrowserRecord> chromeList = getChromeBrowserHistory();
Log.e(TAG, "=> size of Default browser:" + defaultList.size());
Log.e(TAG, "=> size of Chrome browser:" + chromeList.size());
// compare list A with B, update A item if equal item found in B and push it to tempList
for(int i=0; i<chromeList.size(); i++) {
BrowserRecord chromeBrowser = chromeList.get(i);
for(int j=0; j<defaultList.size(); j++) {
BrowserRecord defaultBrowser = defaultList.get(j);
if(chromeBrowser.equals(defaultBrowser)) {
if(chromeBrowser.getBookmark() != defaultBrowser.getBookmark())
chromeBrowser.setBookmark(1);
chromeBrowser.setVisits(chromeBrowser.getVisits() + defaultBrowser.getVisits());
}
}
browserList.add(chromeBrowser);
}
// compare list B with A, jump if equal item found in A, push to tempList if item not found
for(int i=0; i<defaultList.size(); i++) {
BrowserRecord defaultBrowser = defaultList.get(i);
boolean found = false;
for(int j=0; j<chromeList.size(); j++) {
BrowserRecord chromeBrowser = chromeList.get(j);
if(defaultBrowser.equals(chromeBrowser)) {
found = true;
break;
}
}
if(!found)
browserList.add(defaultBrowser);
}
Log.e(TAG, "=> size of final browser:" + browserList.size());
return browserList;
}
I have tested this method and is working fine. Since my history records on mobile device after 3 years didn't exceed more than 200 records on one list and 150 for others, I assume something similar is happening for other users. But I'm sure is not optimum way.
What do you recommend?
any suggestion would be appreciated. Thanks.
Not sure I understand correctly, but it seems like what you're trying to do is, given both lists, create a final list which will contain all of the elements from both lists, removing any duplicates.
If this is the case, then take a look at Java's TreeSet class. If you iterate over all of the elements from both your lists and insert them into a TreeSet, you will basically get the result you're looking for. You can then use an Iterator to create an ArrayList containing all of the non-duplicate items from both your lists. As a side-effect of using a TreeSet, they will ordered (you can also use either a HashSet if you don't care about the order or a LinkedHashSet if you want to preserve the order of insertion).
I am stuck with an issue in my project.The need is to show all data fetched from server using webservices.I successfully get data from server using json.but i want to show data on screen in tabular format 50 records at a time.Please suggest me how to do this or if you can guide me through a better way to implement paging in android.
The code of paging is here :
Implement Pagination on tab layout
and the function i use to append rows dynamically to tablelayout is :
private void appendRows(TableLayout table, String[] data) {
int rowSize = data.length;
int colSize = (data.length > 0) ? 1 : 0;
for (int i = 0; i < rowSize; i++) {
TableRow row = new TableRow(this);
for (int j = 0; j < colSize; j++) {
String[] rowVal = null;
rowVal = data[i].split(",");
for (int k = 0; k <= rowVal.length - 1; k++) {
TextView c = new TextView(this);
c.setText(rowVal[k]);
c.setTextColor(getResources().getColor(R.color.white));
c.setPadding(3, 3, 3, 3);
row.addView(c);
}
}
table.addView(row, new TableLayout.LayoutParams());
}
}
Please guide me I need to show hyperlink page numbers at the bottom of my window as shown in google
This might be of some help. Its a tutorial for pagination. Here is the source code.
I have had similar requirement like yours and I normally use the listview for it. Due to the recycling of views it is a lot more efficient than using a table layout.
You can create a custom adapter where you always return the size as 50+1, 100+1. So in your onItemClickListener you can check if the row position is more than the items, if so, then you add the next 50 items to the adapter. This is a basic idea of how to do it.
I am using an array adapter and to this am adding an array list of string s , the list is multi select , How can i get the values of list items clicked ?
my_contacts_list.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
ArrayAdapter<String> adapter=new ArrayAdapter<String>(this, android.R.layout.simple_list_item_multiple_choice,conts_list);
my_contacts_list.setAdapter(adapter);
I was trying to do this ,
SparseBooleanArray positions = my_contacts_list.getCheckedItemPositions();
int size=positions.size();
int i=0;
while(i <= size){
conts_list.get(positions.get(i));
i++;
}
But position.get(i) is an array list , how to retrieve the selected items then ?
SparseBooleanArray.get returns a boolean, but I believe you need to check it for each position in your list, e.g.
int len = listView.getCount();
SparseBooleanArray checked = listView.getCheckedItemPositions();
for (int i = 0; i < len; i++)
if (checked.get(i)) {
String item = cont_list.get(i);
/* do whatever you want with the checked item */
}
This API is a mess. Here is what works for me.
SparseBooleanArray checked = tags.getCheckedItemPositions();
for (int i = 0; i < checked.size(); i++) {
if(checked.valueAt(i)) {
Tag tag = (Tag) tags.getItemAtPosition(checked.keyAt(i));
Log.i("xxxx", i + " " + tag);
}
}
I believe the fastest way to get the info out of this SparseArray is to iterate over the keys (actually I'm fairly sure that the solutions above won't work in all cases). The ListView will enter a pair (index, true) into the SparseBooleanArray for every selected index.
So the code might look like this:
SparseBooleanArray checked = lv.getCheckedItemPositions();
int size = checked.size(); // number of name-value pairs in the array
for (int i = 0; i < size; i++) {
int key = checked.keyAt(i);
boolean value = checked.get(key);
if (value)
doSomethingWithSelectedIndex(key);
}
I think the Answer from Daren Robbins is Wrong, here is my answer:
ArrayList<String> ids = extras.getStringArrayList("commonids");
SparseBooleanArray checked = lv.getCheckedItemPositions();
for (int i = 0; i < checked.size(); i++) {
if(checked.get(i))
Log.i("CheckedItem", ids.get(checked.indexOfKey(i)));
}
Assume ids is an arraylist with the same size of the listview containing the ids of the items in the list view
The thing is you must iterate all the list view items but not checkedPositions.
Define the variables:
listView (The instance of you ListView)
names (the ArrayList you are )
saveCheckedName (save all checked name to this Arraylist)
SparseBooleanArray checkedPositions = listView.getCheckedItemPositions();
for (int i = 0; i < subjectListView.getCount(); i++) {
if (checkedPositions.get(i) == true) {
saveCheckedName.add(names.get(i));
}
}
Like so many other things, multi-select ListViews are a real problem in Android.
Instead of simply requesting the selected items as a List of Objects (dear Google, this is what we expect):
List selected_items = my_list_view.getSelectedItems();
we are forced to use this stupendously ridiculous API:
SparseBooleanArray checked = my_list_view.getCheckedItemPositions();
int num_selected = 0;
for(int i = 0; i < checked.size(); i++) {
if(checked.valueAt(i)) {
num_selected++;
int key = checked.keyAt(i);
boolean value = checked.get(key);
if (value) {
//
}
}
}
The horribly named SparseBooleanArray is populated by calling the even more horribly named getCheckedItemPositions() on the ListView. But instead of returning the positions of each selected/checked item in the list, it returns the position of every item in the list that WAS EVER touched, whether it is currently actually selected or not! Unbelievable, but true.
To calculate whether the item is ACTUALLY CURRENTLY checked, we are forced to test valueAt(i) for truthiness while looping through the 'was ever touched' array of items.
In addition to this madness, if we want to calculate the number of selected items, we appear to be forced to increment our own counter (e.g. num_selected).
With APIs like this one, it's little wonder developers are an angry lot!
I think another option is to just keep track of all of this yourself.
list.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> listView, View selectedItem,
int position, long itemId) {
//Keep a reference here, and toggle a global variable.
HOW I SOLVED THE ISSUE with a second ArrayList :
Created a second ArrayList instance
Updated that ArrayList instance with the UNCHECKED items
added it to the my listadapter
public void removeSelectedItems(){
updatedList = new ArrayList<String>(); //initialize the second ArrayList
int count = lv.getCount(); //number of my ListView items
SparseBooleanArray checkedItemPositions = getListView().getCheckedItemPositions();
for (int i=0;i < count;i++){
if(!checkedItemPositions.get(i))
updatedList.add(liveNames.get(i)); //liveNames is the current ArrayList
Log.e("TEST", liveNames.get(i));
}
adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_multiple_choice, updatedList);
setListAdapter(adapter);}
Hope it will be helpfull :)
Foo objectAtCheckedRow = null;
for (int i = 0; i < positions.size(); i++) { //positions.size() == 2
objectAtCheckedRow = adapter.getItem(positions.keyAt(i));
//Do something significant with object here
}
A couple things to understand
It's a key-value pair list.
The key is the index of a row, get it with positions.keyAt(i)
The value is whether the row at that index is checked or not(true or false), get it with positions.valueAt(i)
positions.get(i) returns the same boolean as .valueAt(i)
Careful not to get indexes mixed up. You do not need to(and should not) iterate over your whole list. Use int i to iterate over positions, but don't use i to get objects from your list
But in this specific case(listView.getCheckedPositions()) it only fills in true(checked rows), so you don't actually need to verify using .get(i) nor .valueAt(i)
Example:
Let's say you've checked the 5th and 8th items in the list(index 4 and 7), then positions.size() == 2 and i will be 0 and then 1
So when:
i == 0 then keyAt(i) == 4
i == 1 then keyAt(i) == 7
i == 0 OR i == 1 then valueAt(i) == true AND get(i) == true
FYI, Here is how Google did it:
Excerpted from http://mytracks.googlecode.com/hg/MyTracks/src/com/google/android/apps/mytracks/util/Api11Adapter.java
/**
* Gets the checked positions in a list view.
*
* #param list the list view
*/
private int[] getCheckedPositions(ListView list) {
SparseBooleanArray positions = list.getCheckedItemPositions();
ArrayList<Integer> arrayList = new ArrayList<Integer>();
for (int i = 0; i < positions.size(); i++) {
int key = positions.keyAt(i);
if (positions.valueAt(i)) {
arrayList.add(key);
}
}
int[] result = new int[arrayList.size()];
for (int i = 0; i < arrayList.size(); i++) {
result[i] = arrayList.get(i);
}
return result;
}
and here is my adapted version:
public static List<Integer> getAbsListViewCheckedItemPositions(AbsListView absListView) {
SparseBooleanArray checked = absListView.getCheckedItemPositions();
List<Integer> positions = new ArrayList<>();
int checkedSize = checked.size();
for (int i = 0; i < checkedSize; i++) {
if (checked.valueAt(i)) {
positions.add(checked.keyAt(i));
}
}
return positions;
}
We use this in our Android utility class. The generics help prevent compiler warnings, but you can remove them if your adapter returns multiple types.
public static <T> Collection<T> getCheckedItems(ListView listView) {
Collection<T> ret = new ArrayList();
SparseBooleanArray checkedItemPositions = listView.getCheckedItemPositions();
for (int i = 0; i < checkedItemPositions.size(); i++) {
if (checkedItemPositions.valueAt(i)) {
T item = (T) listView.getAdapter().getItem(checkedItemPositions.keyAt(i));
ret.add(item);
}
}
return ret;
}
Very simple, use below code
listViewRequests.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
AppCompatCheckedTextView checkBox = (AppCompatCheckedTextView) view;
if (checkBox.isChecked() == true){
Log.i("CHECK",checkBox.isChecked()+""+checkBox.getText().toString());
}
}
});
for(int i =0; i< listView.getAdapter().getCount(); i++){
if(listView.isItemChecked(i)){
listView.getAdapter().getItem(i); // item
}
}
should be used after setAdapter() method