Why is my ArrayAdapter null? It enter on exception and when I look the message, it gave me null. I can't initialize this array. I test my string[] and it's not null. I see all the file names from my mImageFilenames.
private void PopulateListView() {
mPrivateRootDir = new File(Environment.getExternalStorageDirectory()
+ "");
Toast.makeText(this, mPrivateRootDir + " <--mPrivateRootDir||",
Toast.LENGTH_LONG).show();
// Get the files/images subdirectory;
mImagesDir = new File(mPrivateRootDir, "MyPdf");
Toast.makeText(this, mImagesDir + "<--mImagesDir", Toast.LENGTH_LONG)
.show();
// Get the files in the images subdirectory
mImageFiles = mImagesDir.listFiles();
Toast.makeText(this, mImageFiles[0] + "<--mImageFiles||",
Toast.LENGTH_LONG).show();
// Set up ListView
listViewSelectFile = (ListView) findViewById(R.id.listviewSelectFiles);
// listViewSelectStudent = (ListView)
// findViewById(R.id.listviewSelectStudent);
/*
* Display the file names in the ListView mFileListView. Back the
* ListView with the array mImageFilenames, which you can create by
* iterating through mImageFiles and calling File.getAbsolutePath() for
* each File
*/
mImageFilenames = new String[mImageFiles.length];
for (int i = 0; i < mImageFilenames.length; ++i) {
mImageFilenames[i] = mImageFiles[i].getName();
Toast.makeText(this,
mImageFilenames[i] + "<-- mImageFilenames[i]" + " FOR",
Toast.LENGTH_LONG).show();
}
try {
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
R.layout.list_view_rows, R.id.listview, mImageFilenames);
listViewSelectFile.setAdapter(adapter);
// listViewSelectStudent.setAdapter(adapter);
} catch (Exception e) {
Toast.makeText(this, "ArrayAdapter Error :" + e.getMessage(),
Toast.LENGTH_LONG).show();
}
EDIT
screen3 xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:baselineAligned="false" >
<ListView
android:id="#+id/listviewSelectFiles"
android:layout_width="0dp"
android:layout_height="fill_parent"
android:layout_weight=".50" >
</ListView>
</LinearLayout>
list_view_rows xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/listviewSendFile"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/Send_Files"
android:textAppearance="?android:attr/textAppearanceMedium" />
</LinearLayout>
Ok I got the problem
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
R.layout.list_view_rows, R.id.listview, mImageFilenames);
You need to pass the id of a TextView in the parameters not a listview. Change it to
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
R.layout.list_view_rows, R.id.someTextView, mImageFilenames);
The TextView should be present in list_view_rows.xml
EDIT
Since you want a simple ListView, you need to initialize it and the ArrayAdapter in the onCreate() of the activity. Just return the list's value from the populate method.
This is how you would set an adapter for a ListView
onCreate()
{
...
values = populateListView(); //just make the method return an array or ArrayList
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, android.R.id.text1, values);
..
}
Try this:
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,R.layout.list_view_rows, mImageFilenames);
ArrayAdapter adapter_name = new ArrayAdapter(this,android.R.layout.simple_list_item,ArrayList_name);
//the format of array adapter should look like this
ArrayAdapter adapter_name = ArrayAdapter (Context context, int resource,int textViewResourceId, T[] objects);
//simple_list_item is list view xml file
//ArrayList_name is list that is to be processed in list view
Related
i have a problem here in using spinner, i want to add value to each array item in my string.xml
this is my code:
<string-array name="hubungan">
<item>Choice</item>
<item>CHILD</item>
<item>PARENT</item>
<item>HUSBAND</item>
<item>WIFE</item>
</string-array>
I mean is:
<string-array name="hubungan">
<item>Choice value="1"</item>
<item>CHILD value="2"</item>
<item>PARENT value="3"</item>
<item>HUSBAND value="4"</item>
<item>WIFE value="5"</item>
</string-array>
try this
<Spinner
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/spinner"
android:entries="#array/hubungan"
/>
Well if you insist doing in this way try this example. The example will be as minimal as possible since you don't provide enough code.
Your string array values as you defined but I modified the way of storing by convenince.
<string-array name="hubungan">
<item>Choice,1</item>
<item>CHILD,2</item>
<item>PARENT,3</item>
<item>HUSBAND,4</item>
<item>WIFE,5</item>
</string-array>
I will assume that you have a spinner and a textview in your activity / fragment. You can set this data and process it as needed like following:
Spinner definition in xml
<Spinner
android:id="#+id/spinner"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
This code must be located in your onCreate method if you use an activity, or onViewCreated method if you use a fragment.
// I assume that you've already instantiated the spinner and textview
// Setup for spinner
String[] hubungans = getResources().getStringArray(R.array.hubungan);
if(hubungans != null && hubungans.length > 0) {
String[] names = new String[hubungans.length];
String[] values = new String[hubungans.length];
// Now we will parse the records and split them into name and value
for(int i = 0; i < hubungans.length; i++) {
String hubungan = hubungans[i];
if(hubungan == null || hubungan.isEmpty()) {
Log.d(TAG, "onViewCreated: couldn't get record for index "+i);
continue;
}
// Split the record by "," seperator for example for choice "Choice,1"
String[] nameValue = hubungan.split(",");
if(nameValue.length < 2) {
Log.d(TAG, "onViewCreated: couldn't get split record for index "+i);
continue;
}
names[i] = nameValue[0]; // first index will have the names
values[i] = nameValue[1]; // second will have its value
}
Log.d(TAG, "onViewCreated: names and values: "+ Arrays.toString(names)+" - "+Arrays.toString(values));
ArrayAdapter<CharSequence> adapter = new ArrayAdapter<>(requireContext(), android.R.layout.simple_spinner_item, names);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
int val = 0;
try {
val = Integer.parseInt(values[position]); // Here you have value as numeric type
} catch (NumberFormatException nfe) {
nfe.printStackTrace();
}
textView.setText(String.format("Value for %s is %d", names[position], val));
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
} else {
Log.d(TAG, "onViewCreated: Hubungans cannot be read!");
}
There you go! Hope this helps you with your unique problem.
So I'm trying to populate a ListView with Checkboxes. While my code does populate the ListView with the correct number of Checkboxes, the text for each textbox is incorrect (it appears to be the raw code for the Checkbox). What am I doing wrong?
Result:
Code for populating a checkbox: (SUBJECTS is an array of strings)
lv = (ListView) findViewById(R.id.myListView);
ArrayList<CheckBox> your_array_list = new ArrayList<CheckBox>();
int i = 0;
for (i = 0; i < 3; ++i) {
CheckBox cb = new CheckBox(getApplicationContext());
cb.setText(SUBJECTS[i]);
your_array_list.add(cb);
}
ArrayAdapter<CheckBox> arrayAdapter = new ArrayAdapter<CheckBox (this, R.layout.cbview, your_array_list );
lv.setAdapter(arrayAdapter);
XML code for cbview:
<?xml version="1.0" encoding="utf-8"?>
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/checkBox"
xmlns:android="http://schemas.android.com/apk/res/android" />
your_array_list.add(cb);
that line is adding the CheckBox object that you create which is why you get the output you do.
Change that to
your_array_list.add(cb.getText().toString());
this will get the String text that you have added to it with cb.setText()
I'm trying to decrease the font size of the spinner, and I created an XML file called spinner_item.
spinner_item.xml:
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#android:id/text1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="12sp"
android:textColor="#800080" />
method to load the spinner:
private void loadCustomServiceSpinner(String workRequestType) {
CustomServiceDBQueries csQueries = new CustomServiceDBQueries();
customServices = csQueries.selectCustomService(workRequestType);
String[] strCustomService = new String[customServices.size() + 1];
strCustomService[0] = "";
int i = 1;
for (CustomService cs : customServices) {
strCustomService[i] = cs.getCustomServiceName();
i++;
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
R.layout.spinner_item, strCustomService);
adapter.setDropDownViewResource(R.layout.spinner_drop_default);
Spinner SpnCustomService = (Spinner) findViewById(R.id.SpnCustomService);
SpnCustomService.setAdapter(adapter);
}
I do not see any changes, the source may be 20 or 50 SP SP that does not change anything. Can someone help me?
I have an app that take strings from database and put it in ListView.
this is the code for getting my String from database:
public void setLogView(String date){
ArrayAdapter<TextView> adapter = new ArrayAdapter<TextView>(this, android.R.layout.simple_list_item_1);
listView.setAdapter(adapter);
DataBaseMain dataBase = new DataBaseMain(this);
dataBase.open();
String[][] all = dataBase.dayLog(date);
dataBase.close();
if(all == null)
return;
String temporay = "";
for(int j = 0; j < all[0].length; j++){
temporay = "";
for (int i = 0; i < all.length; i++){
TextView text = new TextView(this);
temporay = temporay + " " + all[i][j];
text.setText(temporay);
adapter.add((TextView)text);
}
}
}
Its seems that i get new TextView in my ListView but the text is messed up.
I checked my temporay string and is fine.
Is somewhere in putting him in the ListView.
No error in logcat or exceptions.
here is what i got in my app ListView insted of my wanted text.(i wanted to put picutrue but i dont have enough repetion:
There, it becomes clear from the image you provided
Try, this..
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1);
listView.setAdapter(adapter);
Your adapter to appending textView object instead of String you are providing.
then add temporay instead of textView inside you loop..like
adapter.add(temporay);
This, will certainly solve your issue.
Change your adapter to ArrayAdapter<String>, and add temporay instead of the whole listview.
Or else, you can extend the ArrayAdapter in and override the getView()
Assuming that, you are trying to display the text in custom listview using separate layout.xml which contains only textview in it.
Check my example given below, this is how i did to achieve this:
First of all fetch the data you are want to display and store it in an ArrayList. Here, al_rec_id, al_rec_name are arraylists of the type Integer and String, respectively.
cursor = database.query("records_data", new String[]{"rec_id", "rec_name"}, "cat_id=?", new String[]{cat_id+""}, null, null, null);
if(cursor.getCount() == 0)
Toast.makeText(getBaseContext(), "No records found.", Toast.LENGTH_SHORT).show();
else
{
while(cursor.moveToNext())
{
al_rec_id.add(cursor.getInt(0));
al_rec_name.add(cursor.getString(1));
}
cursor.close();
}
After that, bind this arraylist with ArrayAdapter and then set this adapter to listview as below. Here, array_adapter_all_records is an ArrayAdapter of the type String
array_adapter_all_records = new ArrayAdapter<String>(this, R.layout.single_row_home, R.id.textViewSingleRowHome, al_rec_name);
listview_all_records.setAdapter(array_adapter_all_records);
This is my single_row_home.xml code:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="15dp"
android:background="#ffffff" >
<TextView
android:id="#+id/textViewSingleRowHome"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
style="#style/listview_only_textview"
android:text="TextView" />
</RelativeLayout>
Thats it. And you're done...!!!
Create a class custom adapter which will extend your ArrayList Adapter in that You can either inflate a different xml which contains your textview or you can create a dynamic textview as you are doing it now in your getView method in custom Adapter. If You need an example let me know.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Adapter for a custom layout of listview
ArrayAdapter<String> adapter = null;
JSONArray productsList = null;
try {
productsList = obj5.getJSONArray("Content");
} catch (JSONException e2) {
e2.printStackTrace();
}
if(productsList != null){
ListView lv = (ListView) findViewById(android.R.id.list);
for (int i=0; i<productsList.length(); i++) {
final String[] items = new String[productsList.length()];
String product = null;
try {
product = productsList.getJSONObject(i).getString("Quantity")+" X "+
productsList.getJSONObject(i).getString("Name") +" "+
Currency.britishPound+productsList.getJSONObject(i).getString("MinCost");
} catch (JSONException e) {
e.printStackTrace();
}
if(product!=null){
items[i]=product;
}
adapter = new ArrayAdapter<String>(APIQuickCheckout.this, R.layout.product_item, R.id.label, items);
lv.setAdapter(adapter);
}
Here is my list view:
<ListView
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_margin="5dip"
android:layout_weight="30">
</ListView>
And here is how I pass each product seperately.
<?xml version="1.0" encoding="utf-8"?>
<!-- Single List Item Design -->
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/label"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="10dip"
android:textSize="16sp"
android:textStyle="bold" >
</TextView>
Now and according to the the aforementioned code I'm passing to each line just a simple string. However, I was wondering how could I pass three different Strings. The reason that I want to pass three different Strings is that I want them to be in the following format:
Quantity X
Number Price(this should be at the end of the line)
You have to derive from adapter, and provide properly filled views. Like here:
https://github.com/ko5tik/camerawatch/blob/master/src/de/pribluda/android/camerawatch/CameraAdapter.java
For better performance consider:
reusing views supplied to getView() method#
utilise viewHolder patern to save getViewById() resolution