ArrayAdapter Causes ClassCastException - android

I have an AutoCompleteTextView inside a RelativeLayout inside a FrameLayout. I want to populate the completion list using a class declared as follows:
public class AutoCompleteAdapter extends ArrayAdapter<String> implements Filterable {
...
public AutoCompleteAdapter(Context context, int textViewResourceId) {
super(context, textViewResourceId);
data = new ArrayList<String>();
}
...
}
I attached the adapter as follows:
AutoCompleteTextView tv = (AutoCompleteTextView) v.findViewById(R.id.editTextClient);
AutoCompleteAdapter adapter = new AutoCompleteAdapter(getActivity(), R.layout.fragment_main_right);
tv.setAdapter(adapter);
where R.layout.fragment_main_right is the enclosing FrameLayout mentioned above. When I start to input text, I get a ClassCastException with the following message: "android.widget.FrameLayout cannot be cast to android.widget.TextView". I understand this to mean that the second parameter in the ArrayAdapter constructor should be the id of something derived from a TextView. All the examples show this parameter as being the enclosing layout. Can someone clear up my confusion?

For the second parameter in your adapter constructor, pass in android.R.layout.simple_dropdown_item_1line or android.R.layout.simple_list_item_1 instead.
The hint is given away that it expects a textview by the name of the parameter: textViewResoureceId.

Related

Why do we need to pass a resource layout to a custom adapter in constructor?

I am curious to know this as I am not able to find it in internet.
I am creating a custom list adapter. In this adapter there is a getView method which I am overriding. In this method I inflate the row layout which I pick from layout folder.
In this case I should not need to pass the same row layout as a constructor to the adapter, which is not allowed.
Please answer.
Regards
Utsav.
you can safely ignore it by overriding the constructor, like this:
public class MyAdapter extends ArrayAdapter {
public MyAdapter(Context context){
super(context, 0);
}
}
edit:
That exists for cases that you're not creating a custom adapter, e.g. new ArrayAdapter(context, R.layout.item);
This adapter would write the value of to string() of its data items to TextView with ID android.R.id.text1 inside that layout.

Cant set list to custom adapter in fragment

I'm trying to create listview with custom adapter, everything fine in activity class.
but fragment extended class i can not set list in my custom adapter.
you should pass a Context object as first argument of your CustomListAdaptor's constructor but you are passing a Fragment objecy instead.
try this :
CustomListAdaptor customListAdaptor = new CustomListAdaptor(getActivity(), list);
Your problem is in this line
CustomListAdapter customAdapter = new CustomListAdapter(this, list);
More specifically the keyword this is your problem. You are trying to pass this as Context, which works in an Activity, because Activities have Context. However, Fragments do not.
So you must call the parent Activity's Context like so:
CustomListAdapter customAdapter = new CustomListAdapter(getActivity(), list);

"ArrayAdapter requires the resource ID to be a TextView"

I basically know where this exception comes from and what causes it. It's because my textview is wrapped in an RelativeLayout.
But can you tell me why this works
playerAdapter = new PlayerAdapter(this,R.layout.item_lv_player,playerList);
lvPlayer.setAdapter(playerAdapter);
While this doesn't
PlayerAdapter playerAdapter1 = new PlayerAdapter(this,R.layout.item_lv_player,playerAdapterSource[0]);
spinnerPlayer1.setAdapter(playerAdapter1);
Shouldn't both of this throw an exception?
PlayerAdapater is a class that extends ArrayAdapter.
Is it because in the first example I'm using a ListView, and in the second one it's a Spinner? That wouldn't sound logical to me at all since the problem is the creation of the Adapter.
exception is not depends upon your adapter,its depends upon widgets.Every widgets has some properties,based on that only it will raise a exception,
Listview always depends upon Textview for all positions,but spinner not depending on that.If you run ListView without R.id.TextView it raise a nullpointer exception because of you have not initialized the textview in the adapter.But spinner doesnot because it not depending on the textview.
You have ArrayAdapter with 3 parameters passed to it.
The 3 parameter ArrayAdapter constructor can take any of the following parameters -
1) ArrayAdapter(Context context, int resource, int textViewResourceId)
2) ArrayAdapter(Context context, int resource, T[] objects)
The first one Explanation -
public ArrayAdapter (Context context, int resource, int
textViewResourceId)
Added in API level 1 Constructor
Parameters
context The current context.
resource The resource ID for a layout file containing a layout to
use when instantiating views.
textViewResourceId The id of the TextView within the layout
resource to be populated
The second one Explanation -
public ArrayAdapter (Context context, int resource, T[] objects)
Added in API level 1 Constructor
Parameters
context The current context.
resource The resource ID for a layout file containing a TextView to use when instantiating views.
objects The objects to represent in the ListView.
Having explained that for -
PlayerAdapter playerAdapter1 = new PlayerAdapter(this,
R.layout.item_lv_player,playerAdapterSource[0]);
spinnerPlayer1.setAdapter(playerAdapter1);
Is the last parameter a textViewResourceId ? > NO
Is the last parameter a ListView ? > NO
From developer docs android ArrayAdapter.

Android: display BroadcastReceiver in ListView

I created a broadcast receiver to follow my Wi-Fi, I'm getting normaly information in LogCat, but I couldn't put the data in a ListView, like I wan't.
I put a ListView example to test it in the onReceive method but I didn't work, and I'm having this error:
The constructor ArrayAdapter(Wifi.Receiver, int, int,
String[]) is undefined
This is my code:
public class Wifi extends Activity implements OnClickListener{
/** Called when the activity is first created. */
WifiManager wifi;
Button enab;
String resultsString ;
String[] myStringArray;
public class Receiver extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent intent) {
}
ListView listView ;
// Get ListView object from xml
listView = (ListView) findViewById(R.id.listView1);
// Defined Array values to show in ListView
String[] values = new String[] { "Android List View",
"Adapter implementation",
"Simple List View In Android",
"Create List View Android",
"Android Example",
"List View Source Code",
"List View Array Adapter",
};
//getting this error : The constructor ArrayAdapter<String>(Wifi.Receiver, int, int, //String[]) is undefined
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, android.R.id.text1, values);
listView.setAdapter(adapter);
}
}
PS: when I put the code of the ListView in the onCreate method it worked normaly, but I want it in the onReceive method.
In your case this does not refer to Activity Context.
Use
ArrayAdapter<String> adapter = new ArrayAdapter<String>(Wifi.this,android.R.layout.simple_list_item_1, android.R.id.text1, values);
Look at the constructor
public ArrayAdapter (Context context, int resource, int textViewResourceId, T[] objects)
Added in API level 1 Constructor
Parameters
context The current context.
resourc The resource ID for a layout file containing a layout to use when instantiating views.
textViewResourceId The id of the TextView within the layout resource to be populated
objects The objects to represent in the ListView.
So the first param is a valid context
java.lang.Object
↳ android.content.Context // see context
↳ android.content.ContextWrapper
↳ android.view.ContextThemeWrapper
↳ android.app.Activity // see activity
And your class extends Activity
public class Wifi extends Activity
Hence use Wifi.this as a valid context.

Android Custom Spinner - What is the useable result?

I have a custom spinner (customized for formatting). It works fine and shows the result of the selected array item. The string array with my data is called mydata[].
I want to do something with that result - I've tried hours of changes but, it seems I don't know what the container is for the selected result - it just displays automatically. The mNumber refers to a case select in a class (it's result is based on what's passed into-it).
My question(s) - refer to the * WHAT DO I USE HERE * shown in the code's last line:
1. What is the container for the result?
2. How to access and syntax it?
Here's the code:
Thank you!
**[declared in onCreate]**
Spinner spinner = (Spinner) findViewById(R.id.Spinner01);
MySpinnerAdapter adapter = new MySpinnerAdapter(this, R.layout.mspinner, R.id.text,mydata);
spinner.setAdapter(adapter);
**[declared outside of onCreate]**
#SuppressWarnings("unchecked")
private class MySpinnerAdapter extends ArrayAdapter{
public MySpinnerAdapter(Context context, int resource, int textViewResourceId, String[] objects) {
super(context, resource, textViewResourceId, objects);
final TextView woof =(TextView)findViewById(R.id.TextView07);
woof.setText(String.valueOf(dogday.mNumber(*** WHAT DO I USE HERE ? ***)));
}
}
EDITED - FOR MY RESPONSE TO COMMONSWARE (too many characters for a comment box).
Thanks. You know the result that gets displayed in a spinner (by default) when something's selected - that's the piece of data I need. I want to use it as an argument for a call.
The user selects something in the spinner - The selected item will be used to make some choices in the class method (dogDay), which takes a data argument for mNumber(data) and returns a result (just like a function).
I want to do some math calcs with the result. First, I want to display what's coming back (for now) so, I'm using the dogDay.mNumber(data) as an argument for woof.text.
My question is this, How to get the piece of data (the thing the user selected in the Spinner)? How did the spinner know what to display for my selection - that's what I want? I tried using something like getSelectedItem (or whatever the it was - I can't remember just now) but, it crashes.
Is their an easier way to custom format a spinner? (and get the data) I searched hi and low for info and found only one applicable to android 1.5/later (I want a spinner with all black background and red text - I can do it via the way shown in my code using a the custom layout).
Thanks - I got a bit long winded!
EDITED - with full code
Here's a full code with the custom spinner and the call you suggested. As I mentioned, I already tried it - it only shows the first item in the list - never the selected one. I use the result of getSelectedItem as an argument for the string... I tried it from both within and outside the adapter...
package com.bt.junk;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;
public class MyMaincode extends Activity {
private static String mydata[] = {"one", "two", "three"};
int poop;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// DECLARATIONS ------------------------------------------------
Spinner spinner = (Spinner) findViewById(R.id.Spinner01);
MySpinnerAdapter adapter = new MySpinnerAdapter(
this,R.layout.custom_spinner_row,R.id.text, mydata );
spinner.setAdapter( adapter );
poop = spinner.getSelectedItemPosition();
}//end onCreate ********************************************
// METHODS, CLASSES, etc ---------------------------------------
#SuppressWarnings("unchecked") //<-- I added that
private class MySpinnerAdapter extends ArrayAdapter{
public MySpinnerAdapter(Context context, int resource,
int textViewResourceId, String[] objects) {
super(context, resource, textViewResourceId, objects);
final TextView sayWhat = (TextView) findViewById(
R.id.TextView01);
sayWhat.setText(String.valueOf(mydata[poop]));
}//end MySpinnerAdapter
}//end class MySpinnerAdapter
}//end activity
Your question makes little sense to me. I am assuming that "I want to do something with that result" means "I want to find out the selected item's position in the array". If that assumption is correct, you can get the selected position for a Spinner by calling getSelectedItemPosition(). This will be 0 when the Spinner first appears, unless you change the position yourself.
Your code is also very strange, IMHO. The constructor of an ArrayAdapter should not be attempting to manipulate a widget.

Categories

Resources