How to generate random list and insert into listview - java

I am trying to put random items from an array and insert them into a listview, at the moment the listview is just coming up blank. Ideally I would like to be able to retrieve what position from the array the list item is if it is clicked on too
String[] levelOneListList = new String[] {
"Daisy", "Rock", "Tree", "Dandelion", "Grass"
};
Random r=new Random();
int randomNumber=r.nextInt(levelOneListList.length);
ArrayAdapter arrayAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_checked, randomNumber);
The listview is now empty on the emulator

Try to take a look at this page. It's a good Tutorial on how to use Listviews with ArrayAdapter.
https://guides.codepath.com/android/Using-an-ArrayAdapter-with-ListView

Related

Searching the First Character of a String to Pull Up Items From An Array

I have an app I'm working on in Android Studio. I have an array with a list of the 50 states.
The user is able to input one letter of text and then must press "search."
Once they press search, it should display all states beginning with the letter. For instance, if they search "k," they should see Kansas and Kentucky.
These results should be presented in a spinner.
I know I need to use
string_name.charAt(0);
somewhere in my code, but I'm not exactly sure where or what else needs to go with it.
Currently, when I run my app, no matter what letter I search for, the app displays "Alabama" in the spinner and then when you click the drop down for the spinner, it just shows all of the states.
Any help would be appreciated as I am fairly new to Java as well as StackOverflow, so I hope that I presented my question clearly and appropriately. Thank you to anyone who can help.
Here is part of my Java code.
public void buttonOnClick(View v) {
Button button = (Button) v;
Spinner spinner = (Spinner) findViewById(R.id.spinner);
ArrayList states = new ArrayList();
states.add("Alabama");
states.add("Alaska");
states.add("Arizona");
states.add("Arkansas");
states.add("California");
states.add("Colorado");
states.add("Connecticut");
states.add("Delaware");
states.add("Florida");
states.add("Georgia");
states.add("Hawaii");
states.add("Idaho");
states.add("Illinois");
states.add("India");
states.add("Iowa");
states.add("Kansas");
states.add("Kentucky");
states.add("Louisiana");
states.add("Maine");
states.add("Maryland");
states.add("Massachusetts");
states.add("Michigan");
states.add("Minnesota");
states.add("Mississippi");
states.add("Missouri");
states.add("Montana");
states.add("Nebraska");
states.add("Nevada");
states.add("New Hampshire");
states.add("New Jersey");
states.add("New Mexico");
states.add("New York");
states.add("North Carolina");
states.add("North Dakota");
states.add("Ohio");
states.add("Oklahoma");
states.add("Oregon");
states.add("Pennsylvania");
states.add("Rhode Island");
states.add("South Carolina");
states.add("South Dakota");
states.add("Tennessee");
states.add("Texas");
states.add("Utah");
states.add("Vermont");
states.add("Virginia");
states.add("Washington");
states.add("West Virginia");
states.add("Wisconsin");
states.add("Wyoming");
final
ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_spinner_item, states);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(this);
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
}
When the button is clicked, at least you need to get the value in the input box, then choose what to add to that arrayList according to the first letter.
I didn't see your code getting the input text.
well you can also make a substring of the state string in a for loop and test with the input.The substring works with a start and end variable like
Result=states.substring(0,1), as this it will keep only the first letter

listview move up item position

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

How to put arrays into listview

Ok so i sucsessfully gotten my names from my database, and now i've stored them in the array result[], and at the end of the code i've written return result; now my question, how do i get the names from my result[] to appear in a listview? note: i do not want to have the connecting to mysql database on the same class as my listview one.
How would i go about doing this?
I also wish to know how i would go about making a custom listview with the names and a picture on the side. Also if you could tell me how i would go about adding pictures to listviews aswell, that'd be great :) i'm going to be using bmp, retriving them from database as byte[] and then convert them to bmp.
note: fairly new to java and android development
You can find a lot of examples on internet.
A simple example would be:
ListView listView = (ListView) findViewById(R.id.listOne);
String[] name={"HELLO","THIS","IS","NABIN"};
String[] phone={"12","24","36","48"};
ArrayList<HashMap<String,String>> obj= new ArrayList<HashMap<String,String>>();
for(int i=0;i<name.length;i++){
HashMap<String,String> toFill = new HashMap<String,String>();
toFill.put("name", name[i]);
toFill.put("phone", phone[i]);
obj.add(toFill);
}
//to define adapter
ListAdapter adapter = new SimpleAdapter(MainActivity.this, obj, R.layout.contact, new String[] {"name", "phone"},new int[] {R.id.etName,R.id.etPhone});
listView.setAdapter(adapter);
Edited:
For images to display:(Considering your images are in drawable folder)
You have to make a custom adapter
And for imageView of custom adapter do the following:
String imageName = ......// get text from your array which would be the name of image.
int resID = getResources().getIdentifier(imageName , "drawable", getPackageName());
ImageView imageView = (ImageView) findViewById(R.id.image);
imageView.setImageResource(resId);

How to display ArrayList data in tabular format in android

I have a problem in display data in to respective fields.
I have like this data from database in arraylist.
ArrayList<String> ar= new ArrayList<String>;
ar data is:-> [2, India#1, USA#3, Australia#1, Germany#2];
How to get above data like this arraylist:
Country ArrayList: India,USA,Australai, Gernamy
valucheck arraylist: 1,3,1,2
Here first element is id and others ara values. Like India- EditText field and integer(1,2,3) is radiobutton.
India 1(checked first radio button)
India 3(checked third radio button)
Australia 1(Checked first radio button)
Germany 2(Checked second radio button)
I have been trying lots of time, but could get proper solution, so please update some tricks for display those data
I want to display like this data in to tabular form
What i did,
List<EditText> listET = new ArrayList<EditText>();
ArrayList<String> first= new ArrayList<String>();
if(edittextfield){
first.add("India");first.add("USA");first.add("Australia");first.add("Germany");
EditText et_text_input = new EditText(getContext());
for(int p=0;p<listET.size()+1;p++){
et_text_input.setText(first.get(p));
listET.add(et_text_input);
ll.addView(et_text_input);
}
}else if(radiobuttonfield){
what to do in radiobutton.
}
Here If i put data in list of first in static, then works fine, but how to put about ar list data into first list ..
Take a look at the ListView-class.
Look into ArrayAdapter (http://developer.android.com/reference/android/widget/ArrayAdapter.html) which allows you to display the data in a ListView.
Assuming you mean output to console, you could step through the list and display it's items with tab separation
//As an example of usage, not a solution using your structures
for (MyObject o : ar)
{
System.out.println(o.getCountry() + "\t" + o.getValue())
}

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.

Categories

Resources