I am trying to create a dynamic List View using BaseAdapter class.
Below is the code that I am using here.
Code for Main Activity:
public class DisplayFlightsActivity extends AppCompatActivity {
String str_jsonresponse,fare,carrier,number,arrivaltime,departuretime,origin,destination;
ArrayList<String> listitem = new ArrayList<String>();
ListView listView;
//MyBaseAdapter baseAdapter;
Context context = DisplayFlightsActivity.this;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
Bundle extras = intent.getExtras();
str_jsonresponse = extras.getString(DisplaySummaryActivity.STR_JSONRESPONSE);
try{
JSONObject root_jsonresponse = new JSONObject(str_jsonresponse);
JSONObject l1_jsonobject = root_jsonresponse.optJSONObject("trips");
JSONArray l2_jsonarray = l1_jsonobject.optJSONArray("tripOption");
for (int i=0;i < l2_jsonarray.length();i++)
{
JSONObject l21_jsonobject = l2_jsonarray.getJSONObject(i);
fare = l21_jsonobject.getString("saleTotal");
JSONArray l3_jsonarray = l21_jsonobject.optJSONArray("slice");
for (int j=0;j < l3_jsonarray.length();j++)
{
JSONObject l4_jsonobject = l3_jsonarray.getJSONObject(j);
JSONArray l5_jsonarray = l4_jsonobject.optJSONArray("segment");
for(int k=0;k < l5_jsonarray.length();k++)
{
JSONObject l6_jsonobject = l5_jsonarray.getJSONObject(k);
JSONObject l7_jsonobject = l6_jsonobject.optJSONObject("flight");
carrier = l7_jsonobject.getString("carrier");
number = l7_jsonobject.getString("number");
JSONArray l8_jsonarray = l6_jsonobject.optJSONArray("leg");
for(int m=0;m < l8_jsonarray.length(); m++)
{
JSONObject l9_jsonobject = l8_jsonarray.getJSONObject(m);
arrivaltime = l9_jsonobject.getString("arrivalTime");
departuretime = l9_jsonobject.getString("departureTime");
origin = l9_jsonobject.getString("origin");
destination = l9_jsonobject.getString("destination");
}
}
}
listitem.add(fare);
listitem.add(carrier);
listitem.add(number);
listitem.add(arrivaltime);
listitem.add(departuretime);
listitem.add(origin);
listitem.add(destination);
}
}
catch(JSONException JE){
JE.printStackTrace();
}
catch (Exception err){
err.printStackTrace();
}
MyBaseAdapter baseAdapter = new MyBaseAdapter(context,listitem);
listView = (ListView) findViewById(R.id.list_view);
listView.setAdapter(baseAdapter);
setTitle("Results Page");
//setContentView(R.layout.activity_display_flights);
}
}
Code for Base Adapter class:
class MyBaseAdapter extends BaseAdapter {
Context context;
ArrayList<String> listitem = new ArrayList<>();
LayoutInflater inflater = null;
public MyBaseAdapter(Context context, ArrayList<String> listitem) {
this.context = context;
this.listitem = listitem;
inflater = LayoutInflater.from(this.context);
}
public int getCount() {
return listitem.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
if (convertView == null)
vi = inflater.inflate(R.layout.listview_item_layout, null);
TextView carrier = (TextView) vi.findViewById(R.id.layout_textview1);
TextView number = (TextView) vi.findViewById(R.id.layout_textview2);
TextView arrivaltime = (TextView) vi.findViewById(R.id.layout_textview6);
TextView departuretime = (TextView) vi.findViewById(R.id.layout_textview7);
TextView saletotal = (TextView) vi.findViewById(R.id.layout_textview8);
String str_carrier = listitem.get(position).toString();
String str_number = listitem.get(position).toString();
String str_arrivaltime = listitem.get(position).toString();
String str_departuretime = listitem.get(position).toString();
String str_saletotal = listitem.get(position).toString();
carrier.setText(str_carrier);
number.setText(str_number);
arrivaltime.setText(str_arrivaltime);
departuretime.setText(str_departuretime);
saletotal.setText(str_saletotal);
return vi;
}
}
My Problem is: The Base Adapter class is never getting invoked for me. I was trying to debug, but the control never goes inside of BaseAdapter class. I am able to parse the JSON Data and put it in ListItem but I am not able to access Base Adapter class.
Is there anything I am doing wrong? Can anybody please review the code and let me know why it is not working.
Thanks in advance!
I was able to solve the problem by adding the line setContentView(R.layout.activity_display_flights); above, like this --
baseAdapter = new MyBaseAdapter(context,listitem);
setTitle("Results Page");
setContentView(R.layout.activity_display_flights);
listView = (ListView) findViewById(R.id.list_view);
listView.setBackgroundResource(R.drawable.androidbckgrnd1);
listView.setAdapter(baseAdapter);
Earlier the ListView instance was coming as null. Now that issue has been resolved.
Related
I have
public class MainActivity extends FragmentActivity
I wrote Loader class which implements AsyncResponse:
public class Loader implements AsyncResponse {
public Activity contextActivity;
Loader(Activity context) {
this.contextActivity = context;
}
Class "Loader" has method "DrawTabInfo" which calling from AsyncResponse callback.
public void drawTabInfo(String jsonBlob, int tabId)
{
JSONObject dataJsonObj;
PullToRefreshListView list = null;
try {
dataJsonObj = new JSONObject(jsonBlob);
JSONArray jsonData = dataJsonObj.getJSONArray("steals");
ArrayList<JSONObject> data = new ArrayList<JSONObject>();
for (int i=0;i<jsonData.length();i++){
data.add(jsonData.getJSONObject(i));
}
Adapter adapter = new Adapter(contextActivity, data);
LayoutInflater inflater = LayoutInflater.from(contextActivity);
if (tabId == 0) {
View view = inflater.inflate(R.layout.listviewlayout, null, false);
list = (PullToRefreshListView) view.findViewById(R.id.listView);
}
if (tabId == 1) {
View view = inflater.inflate(R.layout.listviewlayout2, null, false);
list = (PullToRefreshListView) view.findViewById(R.id.listView2);
}
list.setAdapter(adapter);
adapter.setNotifyOnChange(true);
Log.d("COUNT") shows - "4", what means array is built fine.
public class Adapter extends ArrayAdapter<JSONObject> {
private final Activity context;
private final ArrayList<JSONObject> profiles;
public String header;
public String preText;
public String imageURL;
static class ViewHolder {
public TextView header;
public ImageView image;
public TextView preText;
public LinearLayout linearItemLayout;
}
public Adapter(Activity context, ArrayList<JSONObject> array) {
super(context, R.layout.tab1_list_layout, array);
Log.d("ADAPTER", "SETTING ADAPTER");
this.context = context;
this.profiles = array;
Log.d("COUNT", "" + profiles.size());
}
#Override
public int getCount()
{
return profiles.size();
}
My getView method:
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View rowView = convertView;
Log.i("GetView Log", "Adapters GetView hasbeen called");// thats never calling
if (rowView == null) {
LayoutInflater inflater = context.getLayoutInflater();
rowView = inflater.inflate(R.layout.tab1_list_layout, null);
ViewHolder viewHolder = new ViewHolder();
viewHolder.linearItemLayout = (LinearLayout) rowView.findViewById(R.id.linearItemLayout);
viewHolder.header = (TextView) rowView.findViewById(R.id.itemHeader);
viewHolder.image = (ImageView) rowView.findViewById(R.id.itemPreImage);
viewHolder.preText = (TextView) rowView.findViewById(R.id.itemPreText);
rowView.setTag(viewHolder);
}
ViewHolder holder = (ViewHolder) rowView.getTag();
JSONObject item = null;
try {
item = profiles.get(position);
header = item.getString("header");
preText = item.getString("previewText");
imageURL = item.getString("previewImageUrl");
} catch (JSONException e) {
e.printStackTrace();
}
Log.d("ADAPTER LOG", header);
holder.header.setText(header);
holder.preText.setText(preText);
int headerHeight = (int) Math.round(header.length() * 1.5);
holder.linearItemLayout.setMinimumHeight(40 + headerHeight + preText.length());
Picasso.with(context).setIndicatorsEnabled(true);
Picasso.with(context).load(imageURL).resize(140,100).into(holder.image);
return rowView;
}
In MainActivity i calling, where "this" = MainActivity;
Loader loader = new Loader(this);
loader.loadTabInfo(0);
Method getView never calling. What I'am doing wrong?
UPD:
Solved:
public void drawTabInfo(String jsonBlob, int tabId)
{
JSONObject dataJsonObj;
PullToRefreshListView list = null;
try {
dataJsonObj = new JSONObject(jsonBlob);
JSONArray jsonData = dataJsonObj.getJSONArray("steals");
ArrayList<JSONObject> data = new ArrayList<JSONObject>();
for (int i=0;i<jsonData.length();i++){
data.add(jsonData.getJSONObject(i));
}
Adapter adapter = new Adapter(contextActivity, data);
//LayoutInflater inflater = LayoutInflater.from(contextActivity);
if (tabId == 0) {
//View view = inflater.inflate(R.layout.listviewlayout, null, false);
list = (PullToRefreshListView) contextActivity.findViewById(R.id.listView);
Your code is fine .. just you need a little bit change in get view method
add a return statement.. like return rowView;
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View rowView = convertView;
Log.d("GETVIEaW", "GETVIEW");
if (rowView == null) {
LayoutInflater inflater = context.getLayoutInflater();
rowView = inflater.inflate(R.layout.tab1_list_layout, null);
ViewHolder viewHolder = new ViewHolder();
viewHolder.linearItemLayout = (LinearLayout) rowView.findViewById(R.id.linearItemLayout);
viewHolder.header = (TextView) rowView.findViewById(R.id.itemHeader);
viewHolder.image = (ImageView) rowView.findViewById(R.id.itemPreImage);
viewHolder.preText = (TextView) rowView.findViewById(R.id.itemPreText);
rowView.setTag(viewHolder);
}
else{
viewHolder = (ViewHolder) rowView.getTag();
}
viewHolder.preText.setText("Type your name");
return rowView;
}
Are you sure that Log.d() is not called? You may want to change logging scope, usually default scope is info and it doesn't show debug messages. You can try to use Log.i() or change scope.
Try posting your adapter.setNotifyOnChange(true); to handler. Follow this link
I am writing food ordering program, and in CartActivity i have to show Grand Total of all items available in Cart.
Here is How my CartActivity looks right now :
As you can see i am using a TextView above ListView, which has 0.00 as default value, here i want to show Total of all list items....
Can someone help me ? because i believe many of you already experienced this
CartActivity.java:-
public class CartActivity extends Activity{
ListView listView;
CartAdapter cartAdapter;
TextView textGrandTotal;
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cart);
listView = (ListView) findViewById(R.id.listViewCart);
textGrandTotal = (TextView) findViewById(R.id.textGrandTotal);
cartAdapter = new CartAdapter(CartActivity.this);
listView.setAdapter(cartAdapter);
if(Handler.itemsHandler.size()>0)
{
for (int i = 0; i < Handler.itemsHandler.size(); i++) {
}
}
}
}
CartAdapter.java:-
public class CartAdapter extends BaseAdapter {
// Declare Variables
Context context;
LayoutInflater inflater;
HashMap<String, String> resultp = new HashMap<String, String>();
public CartAdapter(Context context) {
this.context = context;
}
#Override
public int getCount() {
return Handler.itemsHandler.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
public View getView(final int position, View convertView, ViewGroup parent) {
// Declare Variables
public View getView(final int position, View convertView, ViewGroup parent) {
// Declare Variables
final ViewHolder holder;
if(convertView==null)
{
holder = new ViewHolder();
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.adapter_cart, null);
// Locate the TextViews in listview_item.xml
holder.title = (TextView) convertView.findViewById(R.id.textTitle);
holder.cost = (TextView) convertView.findViewById(R.id.textCost);
holder.total = (TextView) convertView.findViewById(R.id.textTotal);
holder.quantity = (TextView) convertView.findViewById(R.id.editQuantity);
holder.add = (ImageButton) convertView.findViewById(R.id.btnAdd);
holder.less = (ImageButton) convertView.findViewById(R.id.btnLess);
holder.quantity.setText("1");
holder.quantity.setEnabled(false);
HashMap<String, String> item = new HashMap<String, String>();
item = Handler.itemsHandler.get(position);
// Capture position and set results to the TextViews
holder.title.setText(item.get(ItemActivity.OBJECT_TITLE));
holder.cost.setText(item.get(ItemActivity.OBJECT_COST));
Log.d("Getting Handler", "Item [getting]:: " + item);
String strValue = holder.quantity.getText().toString();
Log.d("quantity::", strValue);
int newValue = Integer.parseInt(strValue);
Log.d("newValue", String.valueOf(newValue));
String strCost = holder.cost.getText().toString();
Log.d("cost::", strCost);
double costValue = Double.parseDouble(strCost);
Log.d("double::cost:-", String.valueOf(costValue));
holder.total.setText(new DecimalFormat("##.#").format(costValue*newValue));
String total = holder.total.getText().toString();
Log.d("total::", total);
..........
return convertView;
}
}
Handler.java:-
public class Handler {
public static ArrayList<HashMap<String, String>> itemsHandler = new ArrayList<HashMap<String, String>>();
}
public class CartActivity extends Activity{
ListView listView;
CartAdapter cartAdapter;
TextView textGrandTotal;
double sum=0;
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cart);
listView = (ListView) findViewById(R.id.listViewCart);
textGrandTotal = (TextView) findViewById(R.id.textGrandTotal);
cartAdapter = new CartAdapter(CartActivity.this);
listView.setAdapter(cartAdapter);
if(Handler.itemsHandler.size()>0)
{
for (int i = 0; i < Handler.itemsHandler.size(); i++) {
HashMap<String, String> item = new HashMap<String, String>();
item = Handler.itemsHandler.get(position);
String strCost= item.get(ItemActivity.OBJECT_COST);
//add this line of code
String quantity= item.get(ItemActivity.OBJECT_QUANTITY);
double costValue = Double.parseDouble(strCost*quantity);
sum=sum+costValue;
}
}
}
}
you just have to multiply (cost of each item*number of items) like above i did.
My situation is like this:
My main activity has 3 fragments. The first fragment requests data from the server and tries to render it. I use an AsyncTask inner class to get the data and render in onPostExecute. I render using a SimpleCursorAdapter with a ListView. Rendering works fine. After this is done, I try to manipulate the UI (set value of a TextView) but it is not working. getViewById does not return null or any errors but I still cannot change the value for some reason. Any suggestions are highly appreciated. Here is the Fragment Class that I use:
public class FeedFragment extends Fragment {
#Override
public View onCreateView(final LayoutInflater inflater, final ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_feed, container, false);
Activity activity = getActivity();
try {
new getFeedData(activity,rootView).execute();
}
finally{
return rootView;
}
}
private class getFeedData extends AsyncTask<Void, Void, String> {
private Context activity;
private View rootView;
public getFeedData(Context context, View main){
this.activity=context;
this.rootView=main;
}
#Override
protected String doInBackground(Void... params) {
try {
HttpRequest request = HttpRequest.get("http://upinion.us/test/feed_sample/");
String response = "";
if (request.ok()) {
response = request.body();
}
return response;
} catch (HttpRequestException exception) {
return null;
}
}
#Override
protected void onPostExecute(String response) {
String[] columns = new String[] {"_id","title","description"};
int[] viewIds = new int[] {R.id.postId,R.id.title,R.id.description};
JSONArray finalResponse;
try {
finalResponse = new JSONArray(response);
} catch (JSONException e) {
e.printStackTrace();
finalResponse = null;
}
MatrixCursor mc = new MatrixCursor(new String[] {"_id","title","description"}); // properties from the JSONObjects
for (int i = 0; i < finalResponse.length(); i++) {
JSONObject jsonObject;
try {
jsonObject = finalResponse.getJSONObject(i);
mc.addRow(new Object[] {jsonObject.get("_id"),jsonObject.get("title"),jsonObject.get("description")});
} catch (JSONException e) {
jsonObject=null;
}
}
SimpleCursorAdapter mAdapter = new SimpleCursorAdapter(getActivity(), R.layout.post, mc, columns, viewIds,0);
ListView list = (ListView) this.rootView.findViewById(R.id.feed_feed);
list.setAdapter(mAdapter);
View v;
for (int i = 0; i < list.getCount(); i++) {
v = list.getAdapter().getView(i, null, null);
TextView text = (TextView) v.findViewById(R.id.title);
text.setText("HELLO MOTO");
}
list.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// selected item
Integer convId = parent.getId();
}
});
}
}
}
As you can see, I pass the activity and the inflated root view to the asynctask, but still no luck. I have spent nearly two days trying to find a solution with no success.
for (int i = 0; i < list.getCount(); i++) {
v = list.getAdapter().getView(i, null, null);
TextView text = (TextView) v.findViewById(R.id.title);
text.setText("HELLO MOTO");
}
this is your problem:
you are NOT supposed to call getView yourself
to update your listview, you need to call adapter.notifyDataSetChanged
and the system will call the updates for you
so remove this piece of code entirely and just replace it with adapter.notifyDataSetChanged
I know this question has been asked thousands of times but I couldn't find an answer for my case for some reason.
What I have is a thread that fetches data from a web services and populates a list with the info. Then I want to press a button and call the same thread to fetch some more data and add it to the list.
But when I call notifyDataSetChanged(), the list for some reason doesn't refresh. The data is in the adapter though...
Here's the code:
#Override
protected void onPostExecute(PropertyNotesParser result) {
this.progressDialog.dismiss();
ArrayList<PropertyNoteHistory> propertyNoteList = result.getAllTheNotes();
addNoteListItems(propertyNoteList);
Collections.sort(getNoteList());
ArrayList<String> titles = new ArrayList<String>();
ArrayList<String> subtitles = new ArrayList<String>();
DateHandler handleDate = new DateHandler();
DataResolve convert = new DataResolve();
for(Iterator<PropertyNoteHistory> i = getNoteList().iterator(); i.hasNext(); ) {
PropertyNoteHistory item = i.next();
PropertyNoteHistory.Note note = item.getNotes();
PropertyNoteHistory.Jobs jobs = item.getJobs();
// Default value is office in case the xml does not have the tag "job" associated with "note".
String service = "Office";
if(jobs != null){
service = convert.getServiceName(jobs.getServiceID());
}
titles.add(note.getTitle() + " (" + service + ")");
subtitles.add(handleDate.formatDate(note.getDate(), "dd MMM yyyy") + " Ref: " + note.getJobID());
}
if(getConnectionCount() == 0){
adapter = new SimpleListAdapter(getActivity(), titles, subtitles);
lv.setAdapter(adapter);
}
else {
adapter.addItem(titles, subtitles);
}
and my adapter:
public class SimpleListAdapter extends BaseAdapter {
private int count = 0;
private static LayoutInflater inflater = null;
private ArrayList<String> titles = new ArrayList<String>();
private ArrayList<String> subtitles = new ArrayList<String>();
private ArrayList<Integer> imageResource = new ArrayList<Integer>();
private boolean hasImage = false;
public SimpleListAdapter(Activity activity, ArrayList<String> titles,
ArrayList<String> subtitles, ArrayList<Integer> imageResource) {
count = titles.size();
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.titles = titles;
this.subtitles = subtitles;
this.imageResource = imageResource;
this.hasImage = true;
}
/**Constructor that creates an adapter with only a title and subtitle.
* #param activity The context.
* #param titles ArrayList with the titles of each list option.
* #param subtitles ArrayList with the subtitles of each list option. */
public SimpleListAdapter(Activity activity, ArrayList<String> titles,
ArrayList<String> subtitles) {
count = titles.size();
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.titles = titles;
this.subtitles = subtitles;
this.hasImage = false;
}
public void addItem(ArrayList<String> title, ArrayList<String> subtitle){
this.titles.addAll(title);
this.subtitles.addAll(subtitle);
notifyDataSetChanged();
}
#Override
public int getCount() {
return count;
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if(v == null)
v = inflater.inflate(R.layout.layout_simple_list, null);
final ImageView icon = (ImageView) v.findViewById(R.id.icon);
final TextView title = (TextView) v.findViewById(R.id.title);
final TextView subtitle = (TextView) v.findViewById(R.id.subtitle);
title.setText(titles.get(position));
subtitle.setText(subtitles.get(position));
if (hasImage) {
icon.setImageResource(imageResource.get(position));
}
else {
icon.setVisibility(ImageView.GONE);
}
return v;
}
}
You will need to update your count variable too in addItem so that the all the rows are created when notifyDataSetChanged is called
I got the following Fragment
public static class DummySectionFragment extends Fragment {
ListView msgList;
ArrayList<StundenplanDetail> details;
AdapterView.AdapterContextMenuInfo info;
public void addVertretung (String Fach, String Raum, String Farbe) {
StundenplanDetail Detail;
Detail = new StundenplanDetail();
Detail.setFach(Fach);
Detail.setRaum(Raum);
Detail.setFarbe(Farbe);
details.add(Detail);
}
/**
* The fragment argument representing the section number for this
* fragment.
*/
XMLParser parser = new XMLParser();
String xml = null;
public static final String ARG_SECTION_NUMBER = "section_number";
public void loadArray (String dayArray) {
}
public DummySectionFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
try{
byte[] inputBuffer = new byte[20000];
File inputFile = new File("sdcard/Android/data/com.approfi.woehlerschule/data.woehler");
FileInputStream fileInputStream = new FileInputStream(inputFile);
fileInputStream.read(inputBuffer);
xml = new String(inputBuffer);
fileInputStream.close();
}catch(IOException e){
Log.d("Fehler:", e.toString());
}
View rootView = inflater.inflate(
R.layout.fragment_stundenplan_dummy, container, false);
if(Integer.toString(getArguments().getInt(ARG_SECTION_NUMBER)).equals("1")){
int splitpos1 = xml.indexOf("<Montag>");
int splitpos2 = xml.indexOf("</Montag>") + 9;
String xml2 = xml.substring(splitpos1, splitpos2);
org.w3c.dom.Document doc = parser.getDomElement(xml2);
NodeList nl = doc.getElementsByTagName("Stunde");
for (int i = 0; i < nl.getLength(); i++) {
Element e = (Element)nl.item(i);
String Fach = parser.getValue(e, "Fach"); // name child value
String Raum = parser.getValue(e, "Raum"); // cost child value
String Farbe = parser.getValue(e, "Farbe"); // description child value
Log.d("Fail:", Fach + Raum + Farbe);
}
}
/*if(Integer.toString(getArguments().getInt(ARG_SECTION_NUMBER)).equals("2")){
ListView listViewStundenplan = (ListView) rootView.findViewById(R.id.listViewStundenplan);
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(getActivity(), R.layout.list_item_stundenplan, dienstagArray);
listViewStundenplan.setAdapter(arrayAdapter);
}
if(Integer.toString(getArguments().getInt(ARG_SECTION_NUMBER)).equals("3")){
ListView listViewStundenplan = (ListView) rootView.findViewById(R.id.listViewStundenplan);
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(getActivity(), R.layout.list_item_stundenplan, mittwochArray);
listViewStundenplan.setAdapter(arrayAdapter);
}
if(Integer.toString(getArguments().getInt(ARG_SECTION_NUMBER)).equals("4")){
ListView listViewStundenplan = (ListView) rootView.findViewById(R.id.listViewStundenplan);
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(getActivity(), R.layout.list_item_stundenplan, donnerstagArray);
listViewStundenplan.setAdapter(arrayAdapter);
}
if(Integer.toString(getArguments().getInt(ARG_SECTION_NUMBER)).equals("5")){
ListView listViewStundenplan = (ListView) rootView.findViewById(R.id.listViewStundenplan);
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(getActivity(), R.layout.list_item_stundenplan, freitagArray);
listViewStundenplan.setAdapter(arrayAdapter);
}
*/
msgList = (ListView) rootView.findViewById(R.id.listViewStundenplan);
msgList.setAdapter(new StundenplanAdapter(details, this));
return rootView;
}
}
And that Adapter for my List View
public class StundenplanAdapter extends BaseAdapter {
private ArrayList<StundenplanDetail> _data;
Context _c;
StundenplanAdapter (ArrayList<StundenplanDetail> data, Context c){
_data = data;
_c = c;
}
public int getCount() {
return _data.size();
}
public Object getItem(int position) {
return _data.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null)
{
LayoutInflater vi = (LayoutInflater)_c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.list_item_stundenplan, null);
}
TextView fachText = (TextView)v.findViewById(R.id.textViewStundenplanFach);
TextView raumText = (TextView)v.findViewById(R.id.textViewStundenplanRaum);
View colorBlock = (View)v.findViewById(R.id.colorBlockStundenplan);
StundenplanDetail msg = _data.get(position);
fachText.setText(msg.fach);
raumText.setText(msg.raum);
colorBlock.setBackgroundColor(37000000);;
return v;
}
}
Now the problem is, that eclipse tells me that The constructor StundenplanAdapter(ArrayList<StundenplanDetail>, Stundenplan.DummySectionFragment) is undefined but i want to use my custom adapter. Every thing works. The List View in my Fragment and the Custom adapter but not if I want to use the custom adapter in my fragment-listview
I hope you can help me
thanks in advance,
MoBr114
Send your FragmentActivity context to your Adapter not Fragment itself!
Try :
msgList.setAdapter(new StundenplanAdapter(details, getActivity()));
You are passing the wrong argument to the Adapter in msgList.setAdapter(). It looks for the context of the Activity non the instance of the class DummySectionFragment.