listview move up item position - java

I'm trying to move the item's position on ListView by pressing a button which will move up one row of the list.I tried looking for other answers on SO but their ListView was populated from an ArrayList whilst mine from fileList()
Do I need to somehow sort the files in fileList()? or is using ArrayList enough for me to change their positions?
I used ArrayList to get the item's position
How I populate my ListView
String[] SavedFiles;
String dataDr;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_address);
dataDr = getApplicationInfo().dataDir;
showDirFile(dataDr);
}
void showDirFile(String dirpth)
{
String path = dirpth+"/files";
Log.d("Files", "Path: " + path);
File f = new File(path);
File file[] = f.listFiles();
Log.d("Files", "Size: "+ file.length);
SavedFiles = new String[file.length];
for (int i=0; i < file.length; i++)
{
Log.d("Files", "FileName:" + file[i].getName());
SavedFiles[i] = file[i].getName();
}
ArrayAdapter<String> adapter
= new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1,
SavedFiles);
listView.setAdapter(adapter);
}
How I get the item's position
OnItemClickListener getFileEditContent = new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// Get item's file name according to position
String clickedFile = (String)parent.getItemAtPosition(position);
stringArrayList.add(clickedFile)
// Get item position
intArrayList.add(position);
}
};

you have used String[] SavedFiles; for showing list using adapter.
On click of an Item you want to move it up for that write logic for swapping array items and notify adapter.
Your logic will make the top item to current one and current one to top one.
Hope this will help you.

I managed to solve it myself by using the Collections.swap method
Example
Collections collections;
void positionChange(){
//to store arrays into ArrayList
List<String> newList = new ArrayList<String>(Arrays.asList(myDataFiles));
//to get the item's position # get the first item in array if multiple arrays exist
String currentPos = String.valueOf(intArrayList.get(0));
int oldPos = Integer.valueOf(currentPos);
int newPos = oldPos-1;
//Swap position # move up list
collections.swap(newList, oldPos, newPos);
//store ArrayList data into arrays
myDataFiles = newList.toArray(myDataFiles);
intArrayList.clear();
adapter.notifyDataSetChanged();
}
This will make our selected item move up, but it won't save the state. Meaning the item's position displayed on ListView will go back to the way it was upon closing the app

Related

the app keep crashing whenever the While loop starts

I have made an ArrayList store the numbers from 1 to 10 in Strings, then I wanted to make the numbers in the ArrayList displayed in the screen using While loop. But the app keeps crashing when the loop starts.`
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_number);
}
ArrayList<String> words = new ArrayList<>();
{
// Create an ArrayList of words
words.add("One");
words.add("Two");
words.add("Three");
words.add("Four");
words.add("Five");
words.add("Six");
words.add("Seven");
words.add("Eight");
words.add("Nine");
words.add("Ten");
LinearLayout rootView = findViewById(R.id.rootView);
// Create a variable to keep track of the current index position
int index = 0;
// Keep looping until we've reached the end of the list (which means keep looping
// as long as the current index position is less than the length of the list)
while (index < words.size()) {
// Create a new TextView
TextView wordView = new TextView(this);
// Set the text to be word at the current index
wordView.setText(words.get(index));
// Add this TextView as another child to the root view of this layout
rootView.addView(wordView);
// Increment the index variable by 1
index++;
}
}
The initialisation is called before the onCreate method. so the views are not created yet.
ArrayList<String> words = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_number);
// Create an ArrayList of words
words.add("One");
words.add("Two");
words.add("Three");
words.add("Four");
words.add("Five");
words.add("Six");
words.add("Seven");
words.add("Eight");
words.add("Nine");
words.add("Ten");
LinearLayout rootView = findViewById(R.id.rootView);
// Create a variable to keep track of the current index position
int index = 0;
// Keep looping until we've reached the end of the list (which means keep looping
// as long as the current index position is less than the length of the list)
while (index < words.size()) {
// Create a new TextView
TextView wordView = new TextView(this);
// Set the text to be word at the current index
wordView.setText(words.get(index));
// Add this TextView as another child to the root view of this layout
rootView.addView(wordView);
// Increment the index variable by 1
index++;
}
}
You are writing this code outside your onCreate function. Put all the code from Array List to index++ inside onCreate function, so when activity is created, it is inside the content.

Android grid view on click listener get selected item

I am trying to get the selected item from grid view in Android development. Here is the list of drawable I used to populate the grid view:
private static Integer[] iconlist = {
R.drawable.food_icon, R.drawable.transport_icon, R.drawable.entertainment_icon,
R.drawable.bill_icon, R.drawable.others_icon, R.drawable.salary_icon,
R.drawable.investment_icon, R.drawable.bonus_icon, R.drawable.medication_icon,
R.drawable.drinks_icon, R.drawable.car_icon, R.drawable.mask_icon,
R.drawable.shopping_icon, R.drawable.lottery_icon, R.drawable.pet_icon,
R.drawable.movie_icon, R.drawable.plant_icon, R.drawable.paint_icon,
};
And gridview on click listener:
grid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent,
View v, int position, long id) {
Toast.makeText(getActivity(), "Grid Item " + (position + 1) + " Selected", Toast.LENGTH_LONG).show();
int selected = position + 1;
for(int i = 0; i < iconlist.length; i++){
if(iconlist[i] == selected){
}
}
}
});
I managed to get the correct integer position based on the clicks. What I am trying to do is based on the selected drawable, I am trying to extract out the string.
For example, when transport icon is clicked, I am trying to get the "transport_icon" string from "R.drawable.transport_icon" and store it as string. However, I not sure how to do it.
Any ideas?
first define a drawable from integer array (the ids)
Drawable drawable = context.getResources().getDrawable(iconlist[n]);
and you can get name of resources like this
String name = context.getResources().getResourceEntryName(ID);
this method should return what you need.
You can try in below way:
Context.getResources().getResourceEntryName(R.drawable.transport_icon)
or
Context.getResources().getResourceName(R.drawable.transport_icon)
Reference: https://developer.android.com/reference/android/content/res/Resources.html#getResourceEntryName(int)

ListView items aren't updating with notifyDataSetChanged()

Apparently the notifyDataSetChanged() only updates the visible items in the listview, I have a system that changes the background color of an item when its clicked (to dkgray), and I set everything else to transparent(the default), however other items that aren't visible remain selected(dkgray) (I only want the currently selected item to be dkgray). Is there a way to force notifyDataSetChanged() to update all items.
Here's example:
//makes all item backgrounds transparent
public void resetListViewBackground(){
for (int i = 0; i < listView.getChildCount(); i++){ //parent.getChildCount()
listView.getChildAt(i).setBackgroundColor(Color.TRANSPARENT);
}
}
//reloads the listview
private void reloadListView() {
listItems.clear();
adapter.notifyDataSetChanged();
listView.invalidateViews();
ArrayList<HashMap<String, String>> notesArrayList = dbTools.getAllNotes();
for (int i = 0; i < notesArrayList.size(); i++){
String temp = "";
if (notesArrayList.get(i).get("note").length() > 51){
temp = notesArrayList.get(i).get("note").substring(0,50).toString() + "...";
} else {
temp = notesArrayList.get(i).get("note").toString();
}
listItems.add(temp);
adapter.notifyDataSetChanged();
}
}
Everywhere I call resetListViewBackground(), I call reloadListView() after.
And this is what I use to highlight the selected item.
view.setBackgroundColor(Color.DKGRAY);
Also, the most common occurrence of this problem is that every 6th item is highlighted. The listview only shows about 4 items at a time.
The getChildCount() method won't work for all list items as view recycling is done.
Astral is right as he writes in the comments.
1) Create a custom adapter.(See http://windrealm.org/tutorials/android/listview-with-checkboxes-without-listactivity.php)
2)Inside the onListItemClick listener's onItemClick() method, call your adapter's notifyDataSetChanged() method(whenever the user clicks a list item).
I modified the project that I mentioned and posted it on my Dropbox.(Just import it in Eclipse and run).
Check it out at https://www.dropbox.com/s/gchccjzpkxk8n2z/Planets_modified.zip

Android ListAdapter start # top

Currently the list when populated is starting with the view # the bottom of the list. Is there a way using listAdapters to force it to the top of the list?
Currently the orientation scrolls to the bottom on create. Is there a way to pin the screen to the top when it creates? http://imgur.com/wGTEy in this example you see that entry 1 on create is shoved upwards to make room for six... Instead I want it to populate like this. http://imgur.com/6Lg6e... entry 1 is the top of the list and 6 is pushed off to the bottom for the scroll.
If you look at the picture above you will notice it starts at the bottom of the list instead of at the top. Any Ideas?
mAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, mStrings);
setListAdapter(mAdapter);
registerForContextMenu(getListView());
populateFields();
private void populateFields() {
if (mRowId != null) {
Cursor note = mDbHelper.fetchDaily(mRowId);
startManagingCursor(note);
String body = note.getString(note.getColumnIndexOrThrow(NotesDbAdapter.KEY_DBODY));
mAdapter.clear();
if (!(body.trim().equals(""))){
String bodysplit[] = body.split(",");
for (int i = 0; i < bodysplit.length; i++) {
mAdapter.add(bodysplit[i].trim());
}
}
}
}
**edited to fix != string error.
You want the items later in the list to be at the top of the ListView? If so, check out this questions: Is it possible to make a ListView populate from the bottom?
You are completely changing the adapter, so the scroll position is lost in the process... You can use:
ListView listView = getListView();
int position = listView.getFirstVisiblePosition();
if (!(body.trim().equals(""))){
String bodysplit[] = body.split(",");
for (int i = 0; i < bodysplit.length; i++) {
mAdapter.add(bodysplit[i].trim());
}
}
listView.setSelection(position);
But this is not perfect as it is, if a row is added before position the index will be off. If your list contains unique values you can use ArrayAdapter#getPosition(), to find the new index.
While I still recommend using a CursorAdapter, because it handles large table data better, I want to address a point on efficiency with your ArrayAdapter code.
By using adapter.clear() and adapter.add() you are asking the ListView to redraw itself on every step... potentially dozens or hundreds of times. Instead you should work with the ArrayList directly and then ask the ListView to redraw once itself with ArrayAdapter#notifyDataSetChanged() after the loop completes.

Android ListView center selection

I have a ListView that shows the closest word matches to a search.
For example if I search "hi" I get the following results in the ListView
...
hi
hi five
hi-five
high
highlight
....
I am using
ListView.setSelection(wordList.indexOf(searchWord));
ListView.setSelected(true);
The above code puts the selected word "hi" at the top and doesnt highlight the selection.
I want the "hi" to be centrally positioned , selected and highlighted automatically.
See below
...
hello
hello there
hi
hi-five
hi five
...
What code can I use to achieve the above?
Many thanks.
ListView view = (ListView)findViewById(R.id.YourListView);
int height = view.getHeight();
int itemHeight = view.getChildAt(0).getHeight();
view.setSelectionFromTop(position, height/2 - itemHeight/2);
The position (int) is the listitem you want to center in the listview!!
try setSelectionFromTop() you'll have to do the math yourself. setSelection() bring the selected item to the top of the view, which is what you are seeing.
try this.
first, get visible item count of listview
int count=0;
for (int i = 0; i <= listview.getLastVisiblePosition(); i++)
{
if (listview.getChildAt(i)!= null)
{
count++;
}
}
second, scroll the item to the center of listview.
int target = position-count/2;
if (target<0) target = 0;
listview.setSelection(target);
Try this:
ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// When clicked, show a toast with the TextView text
Toast.makeText(getApplicationContext(), ((TextView) view).getText(),
Toast.LENGTH_SHORT).show();
}
});
for more information :
http://developer.android.com/resources/tutorials/views/hello-listview.html

Categories

Resources