populate ListFragment with Cursor items without ContentProvider - android

I'd like to use my own CursorAdapter class to populate a ListFragment. The cursor is returned from my DB API class. I don't use any ContentProvider.
The cursor is loaded properly, and ListFragment.getListAdapter().getCount() returns number of items from the cursor.
There is just no list showing on the UI ...
This is my ListFragment class:
public class ArticlesListFragment extends ListFragmen
public ArticlesListFragment(int userId, ArticleType type, DBAdapter db) {
ArticlesListFragment.userId = userId;
this.type = type;
this.dbAdapter = db;
Log.d(TAG, "Constructor: type=" + type);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setHasOptionsMenu(true);
mInflater = LayoutInflater.from(getActivity());
cursor = dbAdapter.getArticles(userId, type);
mAdapter = new ListAdapter(getActivity(), cursor, true);
setListAdapter(mAdapter);
//-----> When I call getListAdapter().getCount() here I get a proper number of articles.
}
}
And this is the ListAdapter::
public class ListAdapter extends CursorAdapter {
private Context mContext;
private final LayoutInflater mInflater;
public ListAdapter(Context context, Cursor c, boolean autoRequery) {
super(context, c, autoRequery);
mInflater = LayoutInflater.from(context);
mContext = context;
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
TextView title = (TextView) view.findViewById(R.id.article_title);
title.setText(cursor.getString(cursor
.getColumnIndex(Column._TITLE.name)));
TextView text = (TextView) view.findViewById(R.id.article_text);
text.setText(cursor.getString(cursor
.getColumnIndex(Column._TEXT.name)));
TextView date = (TextView) view.findViewById(R.id.article_date);
date.setText(cursor.getString(cursor
.getColumnIndex(Column._CREATED_DATE.name)));
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
final View view = mInflater.inflate(R.layout.articles_list_item,
parent, false);
return view;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (!mDataValid) {
throw new IllegalStateException(
"this should only be called when the cursor is valid");
}
if (!mCursor.moveToPosition(position)) {
throw new IllegalStateException(
"couldn't move cursor to position " + position);
}
View v;
if (convertView == null) {
v = newView(mContext, getCursor(), parent);
} else {
v = convertView;
}
bindView(v, mContext, getCursor());
return v;
}
}
Thank you
EDIT:
public class ArticlesFragment extends Fragment implements OnTabChangeListener {
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
dbAdapter = new DBAdapter(activity);
dbAdapter.open();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mRoot = inflater.inflate(R.layout.articles_tabs_fragment, null);
return mRoot;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setRetainInstance(true);
FragmentManager fm = getFragmentManager();
if (fm.findFragmentByTag(tabId) == null) {
fm.beginTransaction()
.replace(placeholder,
new ArticlesListFragment(userId, ArticleType
.valueOf(tabId), dbAdapter)).commit();
}
}
This is the R.layout.articles_tabs_fragment complete layout file.
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TabWidget
android:id="#android:id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="0"
android:orientation="horizontal" />
<FrameLayout
android:id="#android:id/tabcontent"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_weight="0" >
<FrameLayout
android:id="#+id/starredArticles"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
<FrameLayout
android:id="#+id/newArticles"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
<FrameLayout
android:id="#+id/readArticles"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</FrameLayout>
</LinearLayout>
This is my list item layout. What I notice while debugging is that CursorAdapter's getView() method is never called..
<LinearLayout
android:id="#+id/first_row"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="3dp" >
<TextView
android:id="#+id/article_title"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:ellipsize="middle"
android:paddingRight="5dp"
android:singleLine="true"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="#+id/article_date"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:gravity="center_vertical"
android:textSize="10dp" />
</LinearLayout>
<TextView
android:id="#+id/article_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/first_row"
android:layout_span="2"
android:textAppearance="?android:attr/textAppearanceSmall" />

Related

OnClickListener not working with fragments

I'm cant get the onclicklistener to work with fragments. I've searched stackoverflow and tried all the tips but i still cant get it to work. So i do my first post here. I've tried adding android:focusable="false", android:clickable="false" and android:descendantFocusability="blocksDescendants" to the layouts with no luck. Ive removed them because they make no difference. I've tried other solutions as well but none of them works. This is my first post so if i posted something wrong let me know and ill redo it, I've borrowed someones customlist just to get a working example.
Here is one of the fragments i want a clickable list in
public class ActivitiesFragment extends Fragment {
ListView list;
String[] maintitle ={
"Aktivitet 1","Aktivitet 2",
"Aktivitet 3","Aktivitet 4",
"Aktivitet 5",
};
String[] subtitle ={
"A","B",
"C","D",
"E",
};
Integer[] imgid={
R.drawable.ic_dashboard_black_24dp,R.drawable.ic_dashboard_black_24dp,
R.drawable.ic_dashboard_black_24dp,R.drawable.ic_dashboard_black_24dp,
R.drawable.ic_dashboard_black_24dp,
};
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_activities, container, false);
MyListAdapter adapter = new MyListAdapter(getActivity(), maintitle, subtitle,imgid);
list = (ListView) rootView.findViewById(R.id.list);
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if(position == 0) {
Toast.makeText(getActivity().getApplicationContext(),"One",Toast.LENGTH_SHORT).show();
}
else if(position == 1) {
Toast.makeText(getActivity().getApplicationContext(),"Two",Toast.LENGTH_SHORT).show();
}
else if(position == 2) {
Toast.makeText(getActivity().getApplicationContext(),"Three",Toast.LENGTH_SHORT).show();
}
else if(position == 3) {
Toast.makeText(getActivity().getApplicationContext(),"Four",Toast.LENGTH_SHORT).show();
}
else if(position == 4) {
Toast.makeText(getActivity().getApplicationContext(),"Five",Toast.LENGTH_SHORT).show();
}
}
});
return rootView;
}
}
Here is the Adapter:
public class MyListAdapter extends ArrayAdapter<String> {
private final Activity context;
private final String[] maintitle;
private final String[] subtitle;
private final Integer[] imgid;
public MyListAdapter(Activity context, String[] maintitle,String[] subtitle, Integer[] imgid) {
super(context, R.layout.mylist, maintitle);
// TODO Auto-generated constructor stub
this.context=context;
this.maintitle=maintitle;
this.subtitle=subtitle;
this.imgid=imgid;
}
public View getView(int position,View rowView,ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
rowView = inflater.inflate(R.layout.mylist, null,true);
TextView titleText = (TextView) rowView.findViewById(R.id.title);
ImageView imageView = (ImageView) rowView.findViewById(R.id.icon);
TextView subtitleText = (TextView) rowView.findViewById(R.id.subtitle);
titleText.setText(maintitle[position]);
imageView.setImageResource(imgid[position]);
subtitleText.setText(subtitle[position]);
return rowView;
}
}
The xml for the fragment:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:id="#+id/list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="50dp"/>
</RelativeLayout>
The xml for the list:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<ImageView
android:id="#+id/icon"
android:layout_width="60dp"
android:layout_height="60dp"
android:padding="5dp"/>
<LinearLayout android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Medium Text"
android:textStyle="bold"
android:textAppearance="?android:attr/textAppearanceMedium"
android:layout_marginLeft="10dp"
android:layout_marginTop="5dp"
android:padding="2dp"
android:textColor="#4d4d4d" />
<TextView
android:id="#+id/subtitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView"
android:layout_marginLeft="10dp" />
</LinearLayout>
</LinearLayout>
Here's whole implementation of RecyclerView with item click listener.
Fragment:
public class MyFragment extends Fragment implements ItemClickListener {
RecyclerView rvList;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_activities, container, false);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
rvList = view.findViewById(R.id.rvList);
ArrayList<ItemData> list = new ArrayList<>();
list.add(new ItemData("Aktivitet 1","A",R.drawable.ic_dashboard_black_24dp))
list.add(new ItemData("Aktivitet 2","B",R.drawable.ic_dashboard_black_24dp))
list.add(new ItemData("Aktivitet 3","C",R.drawable.ic_dashboard_black_24dp))
list.add(new ItemData("Aktivitet 4","D",R.drawable.ic_dashboard_black_24dp))
list.add(new ItemData("Aktivitet 5","E",R.drawable.ic_dashboard_black_24dp))
RVAdapter adapter = new RVAdapter(this, list);
rvList.setLayoutManager(new LinearLayoutManager(getContext()));
rvList.setAdapter(adapter);
}
#Override
public void onItemClicked(ItemData data, int position) {
// item click will be listened here
Toast.makeText(getContext(), String.valueOf(position), Toast.LENGTH_SHORT).show();
}
}
Fragment Layout: frag.xml
<?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="match_parent"
android:orientation="vertical">
<android.support.v7.widget.RecyclerView
android:id="#+id/rvList"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
Layout for the list: item.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="horizontal">
<ImageView
android:id="#+id/icon"
android:layout_width="60dp"
android:layout_height="60dp"
android:padding="5dp" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginTop="5dp"
android:padding="2dp"
android:text="Medium Text"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#4d4d4d"
android:textStyle="bold" />
<TextView
android:id="#+id/subtitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:text="TextView" />
</LinearLayout>
</LinearLayout>
RecyclerView ViewHolder:
public class RecyclerVH extends RecyclerView.ViewHolder {
private TextView titleText;
private ImageView imageView;
private TextView subtitleText;
public RecyclerVH(#NonNull View itemView) {
super(itemView);
titleText = itemView.findViewById(R.id.title);
imageView = itemView.findViewById(R.id.icon);
subtitleText = itemView.findViewById(R.id.subtitle);
}
void bind(ItemData data) {
titleText.setText(data.getMainTitle());
imageView.setImageResource(data.getImgId());
subtitleText.setText(data.getSubTitle());
}
}
RecyclerView Adapter:
public class RVAdapter extends RecyclerView.Adapter<RecyclerVH> {
private ArrayList<ItemData> list;
private ItemClickListener listener;
public RVAdapter(ItemClickListener listener, ArrayList<ItemData> list) {
this.list = list;
this.listener = listener;
}
#NonNull
#Override
public RecyclerVH onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
return new RecyclerVH(LayoutInflater.from(parent.getContext()).inflate(R.layout.item, parent, false));
}
#Override
public void onBindViewHolder(#NonNull final RecyclerVH holder, int position) {
holder.bind(list.get(position));
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
listener.onItemClicked(list.get(holder.getAdapterPosition()),
holder.getAdapterPosition());
}
});
}
#Override
public int getItemCount() {
return list.size();
}
}
interface ItemClickListener {
void onItemClicked(ItemData data, int position);
}
Update 1:
Add these lines to the root tag of item layout:
android:focusable="true"
android:clickable="true"
Like this:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:focusable="true"
android:clickable="true"
android:orientation="horizontal">
...
</LinearLayout>
Time ago I had a similar problem, with an ImageView in my list item. My solution was changing android:focusable to false inside the ImageView block. I never knew why, but it worked fine.
Anyway, I strongly recommend to start using RecyclerView and ViewHolder pattern. https://developer.android.com/guide/topics/ui/layout/recyclerview
It's much more powerful, flexible and a major enhancement over ListView.

Android Custom Spinner unable to select an option and show it

I have a problem with spinner it do not let me select one item. I tried a lot of things and that still not working.
The picture shows that the spinner is in blank when the activity load
When I clicked the arrow it shows the items
but when I choose one, nothing happends.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Activities.Inspeccion.DatosGeneralesActivity">
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/scrollView"
>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginLeft="15dp"
android:layout_marginRight="15dp"
android:layout_marginTop="15dp"
>
<TextView
android:id="#+id/tvSubestacionTitulo"
android:layout_below="#+id/imgLogo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/strSubestacion"
android:textSize="18sp"
android:textColor="#color/colorPrimaryDark"
android:textStyle="bold"
/>
<TextView
android:id="#+id/tvSubestacionDato"
android:layout_below="#+id/tvSubestacionTitulo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="12sp"
android:text="Prueba"
/>
<Spinner
android:id="#+id/spinnerSubEstacion"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/tvSubestacionDato"
>
</Spinner>
</RelativeLayout>
</ScrollView>
</RelativeLayout>
This is the Layout of the activity.
<?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="wrap_content"
android:orientation="horizontal">
<TextView
android:id="#+id/tvNumeroOpcion"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_marginLeft="15dp"
android:layout_marginTop="5dp"
android:text="1"
android:textColor="#color/black"
android:textSize="14sp" />
<TextView
android:id="#+id/tvDescriptionOption"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_marginLeft="15dp"
android:layout_marginTop="5dp"
android:text="Guatemala"
android:textColor="#color/black"
android:textSize="14sp" />
</LinearLayout>
That is the custom layout for the spinner
Public class ComboAdapter extends BaseAdapter{
private List<Combo> combos;
private Activity activity;
private LayoutInflater inflater;
public ComboAdapter(List<Combo> combos, Activity activity) {
this.combos = combos;
this.inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return combos.size();
}
#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 view = convertView;
if (convertView == null){
view = inflater.inflate(R.layout.combo_list_item, null);
TextView tvId = (TextView) view.findViewById(R.id.tvNumeroOpcion);
TextView tvDescripcion = (TextView) view.findViewById(R.id.tvDescriptionOption);
tvId.setText(combos.get(position).getId());
tvDescripcion.setText(combos.get(position).getDescripcion());
}
return view;
}
#Override
public View getDropDownView(int position, View convertView,
ViewGroup parent) {
return getView(position, convertView,parent);
}
}
That is my Adapter
And below is my activity.
public class DatosGeneralesActivity extends AppCompatActivity {
private TextView tvSubestacionDato;
private List<Combo> listaCombo;
private Spinner spinnerSubestacion;
private ArrayAdapter<Combo> adapterSubestacion;
String seleccion;
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_datos_generales);
//Inicializando textos
tvSubestacionDato = (TextView) findViewById(R.id.tvSubestacionDato);
//Inicializanco listas
listaCombo = new ArrayList<>();
//Inivializando spinners
spinnerSubestacion = (Spinner) findViewById(R.id.spinnerSubEstacion);
AppService service = API.getCombos().create(AppService.class);
Call<List<Combo>> subestacionCall = service.getSubestacion();
subestacionCall.enqueue(new Callback<List<Combo>>() {
#Override
public void onResponse(Call<List<Combo>> call, Response<List<Combo>> response) {
listaCombo.clear();
listaCombo.addAll(response.body());
}
#Override
public void onFailure(Call<List<Combo>> call, Throwable t) {
}
});
//final ComboAdapter adapter = new ComboAdapter(listaCombo, DatosGeneralesActivity.this);
final ArrayAdapter<Combo> adapter = new ArrayAdapter<Combo>(this, R.layout.support_simple_spinner_dropdown_item, listaCombo);
spinnerSubestacion.setAdapter(adapter);
spinnerSubestacion.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
adapter.notifyDataSetChanged();
Toast.makeText(DatosGeneralesActivity.this, ""+position, Toast.LENGTH_SHORT).show();
tvSubestacionDato.setText(listaCombo.get(position).getDescripcion());
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
Try this changes:
Call adapter like:
ComboAdapter adapter = new ComboAdapter(DatosGeneralesActivity.this,
R.layout.combo_list_item, R.id.tvDescriptionOption, listaCombo);
now in adapter class:
public ComboAdapter(Activity context,int resouceId, int textviewId, List<Combo> list){
super(context,resouceId,textviewId, list);
this.combos = list;
this.inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
Also inside your getView() method inflate layout like:
if (convertView == null){
view = inflater.inflate(R.layout.combo_list_item, parent , false);

How to get proper item in listview?

I writing test application and I get a strange behavior of mainActivity.listItem, when I click on item yet another item can get visible,it can get dissapear by scrolling.I'm confused.Thanks!
MainActivity
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
stethoInit();
mainActivity = DataBindingUtil.setContentView(this, R.layout.activity_main);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN) {
cursor = getContentResolver().query(MyProvider.CONTENT_URI, null, null, null, null, null);
}
String[] from = new String[]{MyProvider.ID, MyProvider.TEXT};
int[] to = new int[]{R.id.t_id, R.id.t_text};
scAdapter = new SimpleCursorAdapter(this, R.layout.item, cursor, from, to, 0);
mainActivity.listItem.setAdapter(scAdapter);
scAdapter.notifyDataSetChanged();
mainActivity.listItem.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
FrameLayout v = (FrameLayout)view.findViewById(R.id.updateLayout);
Log.d("!!!",v.toString());
v.setVisibility(View.VISIBLE);
}
});
mainActivity.insert.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Fragment insertFragment = new Insert();
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.container, insertFragment);
ft.addToBackStack(null);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.commit();
}
});
}
item.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<FrameLayout
android:id="#+id/updateLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:visibility="gone">
<!-- TODO: Update blank fragment layout -->
<EditText
android:id="#+id/updateTextField"
android:layout_width="match_parent"
android:layout_height="50dp"
android:ems="10"
android:hint="#string/insertTextFieldHint"
android:focusable="false"
android:inputType="textPersonName" />
<Button
android:id="#+id/uodateRecButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="125dp"
android:layout_marginTop="65dp"
android:focusable="false"
android:text="#string/updateRecButton" />
</FrameLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<CheckBox
android:id="#+id/checkBox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:focusable="false"/>
<TextView
android:id="#+id/t_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1" />
<TextView
android:id="#+id/t_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1" />
</LinearLayout>
UPDATE
I solved this problem by extending SimpleCursorAdapter ,maybe someone share with another solution?
private class MyAdapter extends SimpleCursorAdapter{
private int layout;
public MyAdapter(Context context, int layout, Cursor c, String[] from, int[] to, int flags) {
super(context, layout, c, from, to, flags);
this.layout = layout;
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
String id = cursor.getString(colId);
String title = cursor.getString(colText);
TextView idView = (TextView)view.findViewById(R.id.t_id);
idView.setText(id);
TextView textView = (TextView)view.findViewById(R.id.t_text);
textView.setText(title);
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
View view = getLayoutInflater().inflate(layout,parent,false);
return view;
}
#Override
public int getItemViewType(int position) {
return position;
}
#Override
public int getViewTypeCount() {
return getCount();
}
}

ListFragment doesn't show changes in present time

All! I'am new in android app. Now I have some problem. I can't see the result of changing list right away (after updating listView in my ListFragment).
For example, i called method addNewItem and I didn't see any changes on the screen. But if I touch ListFragment I will see all my changes.
ListFragment:
public class PointsListFragment extends ListFragment {
PlaceItemsAdapter adapter;
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
adapter = new PlaceItemsAdapter(
getActivity(), R.layout.place_list_item,
new ArrayList<PlaceItem>());
setListAdapter(adapter);
adapter.notifyDataSetChanged();
}
public void addNewItem(int id, String address) {
adapter.items.add(new PlaceItem(id, address));
adapter.notifyDataSetChanged();
}
private class PlaceItemsAdapter extends ArrayAdapter<PlaceItem> {
private final int viewResourceId;
final public ArrayList<PlaceItem> items;
#Override
public int getCount() {
return items.size();
}
#Nullable
#Override
public PlaceItem getItem(int position) {
return items.get(position);
}
public PlaceItemsAdapter(Context context, int viewResourceId, ArrayList<PlaceItem> items) {
super(context, viewResourceId, items);
this.items = items;
this.viewResourceId = viewResourceId;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(viewResourceId, null);
}
PlaceItem placeItem = getItem(position);
TextView placeIdTextView = (TextView) v.findViewById(R.id.placeId);
placeIdTextView.setText(String.valueOf(placeItem.getId()));
TextView placeAddressView = (TextView) v.findViewById(R.id.placeAddress);
placeAddressView.setText(placeItem.getAddress());
if (selectedValue == position) {
v.setBackgroundResource(R.drawable.active_item);
}
return v;
}
}
}
My activity xml
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"[enter image description here][1]
android:padding="2dp">
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:background="#color/forBorder"
android:orientation="horizontal">
<Spinner
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/spinner"
android:layout_weight="1" />
<TextView
android:text="проложить маршрут"
android:textColor="#android:color/white"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#android:drawable/ic_media_ff" />
</LinearLayout>
<fragment
class="com.restfulrobot.cdcapplication.PointsListFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/list_frag" />
</LinearLayout>
Image Example
Thank you, ALL! I found the answer! I called method from another class (no Activity or Fragment). And now I also call method from another class, but i do it through Handler. And it really works fine now!
Something like that:
Message msg = mainActivityHandler.obtainMessage(MainActivity.NEW_MESSAGE, someObjectToAdd);
mainActivityHandler.sendMessage(msg);

Android GridView: getView() in adapter never gets called

I am Trying to insert GridView in fragment. I have developed custom adapter to populate the gridview. Now everything is working fine but the gridview is not displaying in the fragment. I have check the getCount() method it is returning total length. So that means data is there but it is not displaying. I am pretty new with gridview so have no idea why it is happening. I tried the following answer but they didn't help me either.
Android: getView in adapter never called
Custom Adapter getView() method is not called
Gridview not displaying in fragment
Here is my code:
Tile Fragment Class:
public class TileFragment extends Fragment
{
public TileFragment(){
}
GridView gv;
Context context;
public static String [] prgmNameList={"Let Us C","c++","JAVA","Jsp","Microsoft .Net","Android","PHP","Jquery","JavaScript"};
public static int [] prgmImages={R.mipmap.dicover_disable,R.mipmap.discover_active, R.mipmap.home_disable,
R.mipmap.home_active,R.mipmap.lists_disable,R.mipmap.lists_active,
R.mipmap.profile_disable,R.mipmap.profile_active,R.mipmap.ic_search };
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
#SuppressLint("InflateParams")
// View v = LayoutInflater.from(getActivity()).inflate(R.layout.tile_fragment, null);
View v = inflater.inflate(R.layout.tile_fragment, container, false);
gv = (GridView) v.findViewById(R.id.gridView1);
gv.setAdapter(new CustomAdapter(getActivity(), prgmNameList,prgmImages));
return v;
}
#Override
public void onActivityCreated(Bundle savedInstanceState)
{
super.onActivityCreated(savedInstanceState);
}
}
Custom Adapter:
public class CustomAdapter extends BaseAdapter {
String [] result;
Context context;
int [] imageId;
private static LayoutInflater inflater=null;
public CustomAdapter(FragmentActivity tileFragment, String[] prgmNameList, int[] prgmImages) {
result=prgmNameList;
imageId=prgmImages;
context = tileFragment;
inflater = ( LayoutInflater )context.
getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return imageId.length;
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
public class Holder
{
TextView tv;
ImageView img;
}
#SuppressLint("ViewHolder")
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
Holder holder=new Holder();
View rowView;
rowView = inflater.inflate(R.layout.programlist, null);
holder.tv=(TextView) rowView.findViewById(R.id.textView1);
holder.img=(ImageView) rowView.findViewById(R.id.imageView1);
holder.tv.setText(result[position]);
holder.img.setImageResource(imageId[position]);
rowView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context, "You Clicked " + result[position], Toast.LENGTH_LONG).show();
}
});
return rowView;
}
}
tile_fragment:
<?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="match_parent" >
<GridView
android:id="#+id/gridView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/textView1"
android:numColumns="3"
android:visibility="visible">
</GridView>
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="25sp"
android:textStyle="bold"
android:text=" Computer Languages..." />
</RelativeLayout>
prgramlist
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ImageView
android:id="#+id/imageView1"
android:layout_gravity="center"
android:layout_width="88dp"
android:layout_height="88dp"
android:layout_marginTop="5dp"
android:layout_marginBottom="5dp"
android:src="#mipmap/ic_launcher" />
<TextView
android:id="#+id/textView1"
android:layout_gravity="center"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="15dp"
android:layout_marginTop="5dp"
android:layout_marginBottom="5dp"
android:text="TextView" />
</LinearLayout>
This is how I am adding the fragment:
HomeFragment:
public class HomeFragment extends Fragment
{
public HomeFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
FragmentTabHost mTabHost = new FragmentTabHost(getActivity());
mTabHost.setup(getActivity(), getChildFragmentManager());
Bundle b = new Bundle();
b.putString("key", "Tile");
mTabHost.addTab(mTabHost.newTabSpec("tile").setIndicator("Tile"), TileFragment.class, b);
//
b = new Bundle();
b.putString("key", "Map");
mTabHost.addTab(mTabHost.newTabSpec("map").setIndicator("Map"), ProfileFragment.class, b);
return mTabHost;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
//
}
Any Help will be appreciated ...
Try this:
mTabHost.setup(getActivity(), getChildFragmentManager(), R.layout.my_parent_fragment);
where R.layout.my_parent_fragment is your layout fragment where you have the tabhost.
Once you have verified that the GridView is displayed correctly in an Activity, we could deduce that this is not a problem with the Gridview neither the Adapter, the problem come from your FragmentTabHost definition or setup. You are returning your tabHost from your onCreateView(), for that you must set your layout or container in your tabHost, if you don't do this, how the fragment know where find your layout?
For more info, api here
Can't figure out the root of the problem but try this:
View rowView = convertView;
if(rowView != null) {
rowView = inflater.inflate(R.layout.programlist, null);
}
Try using this layout.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:orientation="vertical"
android:layout_height="match_parent" >
<GridView
android:id="#+id/gridView1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:numColumns="3"
>
</GridView>
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="25sp"
android:textStyle="bold"
android:text=" Computer Languages..." />
</LinearLayout>

Categories

Resources