i have made a Master/Detail View which contains a TabHost in the Detailview.
i have to populate a list of tabs, and every tab has a listview as its content.
Now when i change my Item to display, after the third change or so, no more tab content is rendered(The indicators are rendered). But when i change the tab, the content gets rendered.
The onCreate Method of the DetailFragment is invoked when i change my item to display. The tabs are genrated and added to the tabhost. But after a few times i switched the item to display, the onCreateView Method of the OrderGroupTabFragment is not invoked anymore, without any reason to me.
Thankful for any help.
Here is my code:
DetailFragment:
/**
* A fragment representing a single Order detail screen. This fragment is either
* contained in a {#link OrderListActivity} in two-pane mode (on tablets) or a
* {#link OrderDetailActivity} on handsets.
*/
public class OrderDetailFragment extends Fragment implements IASyncMethodCallbacks {
private static Logger _logger = Logger.getLogger(OrderDetailFragment.class.getSimpleName());
/**
* The fragment argument representing the item ID that this fragment
* represents.
*
*/
public static final String ARG_ORDER = "order";
private TrafficSafetyOrder _order;
private TrafficSafetyOrderService _trafficSafetyOrderService;
private boolean _detached;
private FragmentTabHost tabHost;
/**
* Mandatory empty constructor for the fragment manager to instantiate the
* fragment (e.g. upon screen orientation changes).
*/
public OrderDetailFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
_detached = false;
_trafficSafetyOrderService = new TrafficSafetyOrderService();
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, final ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_order_detail,
container, false);
tabHost = (FragmentTabHost)rootView.findViewById(R.id.order_detail_tab_host);
tabHost.setup(getActivity(), ((FragmentActivity)getActivity()).getSupportFragmentManager() , android.R.id.tabcontent);
OrderListItem order = (OrderListItem)getArguments().getSerializable(ARG_ORDER);
try {
if(order != null)
_order = _trafficSafetyOrderService.getOrderForId(order.getId());
} catch (Exception e) {
_logger.log(Level.WARNING, e.getMessage(), e);
}
if (_order != null) {
OrderId orderId = _order.getOrderIdByOrderIdType(OrderIdTypes.GEB);
((TextView) rootView.findViewById(R.id.order_detail_header))
.setText("Auftrag: " + orderId.getName() + orderId.getId());
for (final Group formGroup : _order.getFormGroups()) {
System.out.println("Adding Tab " + formGroup.getDisplayText());
TabSpec spec = tabHost.newTabSpec(formGroup.getDisplayText());
System.out.println("Spec created " + formGroup.getDisplayText());
spec.setIndicator(formGroup.getDisplayText());
System.out.println("Indicator set " + formGroup.getDisplayText());
Bundle bundle = new Bundle();
System.out.println("Bundle created " + formGroup.getDisplayText());
bundle.putSerializable(OrderGroupTabFragment.ORDER_GROUP_LIST_ARG, formGroup.getItems());
System.out.println("Added items to bundle " + formGroup.getDisplayText());
tabHost.addTab(spec, OrderGroupTabFragment.class, bundle);
System.out.println("Tab added " + formGroup.getDisplayText());
}
}
return rootView;
}
#Override
public void onStart() {
super.onStart();
tabHost.setCurrentTab(0);
}
public TrafficSafetyOrder getOrder() {
return _order;
}
public void setOrder(TrafficSafetyOrder _order) {
this._order = _order;
}
#Override
public void onDestroyView() {
super.onDestroyView();
try {
_trafficSafetyOrderService.updateTrafficServiceOrder(_order);
} catch (Exception e) {
_logger.log(Level.WARNING, e.getMessage(), e);
}
}
#Override
public void onDetach() {
super.onDetach();
_detached = true;
}
#Override
public void onASyncMethodCompleted(Object receiver, Method method) {
if(_detached)// if fragment is already detached from Activity, do not execute callback
return;
Toast.makeText(getActivity(), receiver != null ? receiver.getClass().getSimpleName() : "NULL" + "." + method != null ? method.getName() : "NULL" + " executed succesfully", Toast.LENGTH_LONG).show();
}
}
OrderGroupTabFragment:
public class OrderGroupTabFragment extends android.support.v4.app.Fragment{
public static final String ORDER_GROUP_LIST_ARG = "ORDER_GROUP_ITEMS";
private List<GroupItem> groupItems;
private ListView listView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
System.out.println("Creating Order List View");
View view = inflater.inflate(R.layout.fragment_order_group_tab_list, null);
groupItems = (List<GroupItem>)getArguments().getSerializable(ORDER_GROUP_LIST_ARG);
listView = (ListView)view.findViewById(R.id.order_detail_tab_list_view);
listView.setAdapter(new GroupItemAdapter(getActivity(), groupItems));
System.out.println("Order List View Created");
return view;
}
}
GroupItemAdapter:
public class GroupItemAdapter extends ArrayAdapter<GroupItem> {
private Context _context;
public GroupItemAdapter(Context context, List<GroupItem> groupItems) {
super(context, R.layout.lvi_group_item , groupItems);
this._context = context;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if(convertView == null){
LayoutInflater li = (LayoutInflater) _context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = li.inflate(R.layout.lvi_group_item,
parent, false);
holder = new ViewHolder();
holder.header = (TextView)convertView.findViewById(R.id.tab_header);
holder.isVerified = (CheckBox)convertView.findViewById(R.id.tab_verification_checkbox);
convertView.setTag(holder);
}else{
holder = (ViewHolder) convertView.getTag();
}
GroupItem item = getItem(position);
holder.header = (TextView)convertView.findViewById(R.id.tab_header);
holder.isVerified = (CheckBox)convertView.findViewById(R.id.tab_verification_checkbox);
if(item != null)
holder.header.setText(item.getName());
return convertView;
}
private class ViewHolder {
TextView header;
CheckBox isVerified;
}
}
fragment_order_detail.xml:
<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">
<LinearLayout android:id="#+id/order_detail_button_bar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
style="#android:style/Widget.ActionBar">
<Button android:id="#+id/order_detail_button_undo"
android:layout_width="0dp"
android:layout_height="wrap_content"
style="#android:style/Widget.ActionButton"
android:drawableTop="#drawable/ic_action_undo"
android:text="Undo"
android:layout_weight="1"/>
<Button android:id="#+id/order_detail_button_redo"
android:layout_width="0dp"
android:layout_height="wrap_content"
style="#android:style/Widget.ActionButton"
android:drawableTop="#drawable/ic_action_redo"
android:text="Redo"
android:layout_weight="1"/>
<Button android:id="#+id/order_detail_button_submit"
android:layout_width="0dp"
android:layout_height="wrap_content"
style="#android:style/Widget.ActionButton"
android:drawableTop="#drawable/ic_action_tick"
android:text="Submit"
android:layout_weight="1"/>
</LinearLayout>
<TextView
style="?android:attr/textAppearanceLarge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="16dp"
android:layout_below="#id/order_detail_button_bar"
android:layout_alignParentStart="true"
android:id="#+id/order_detail_header"/>
<android.support.v4.app.FragmentTabHost android:id="#+id/order_detail_tab_host"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#id/order_detail_header">
<RelativeLayout android:layout_width="match_parent"
android:layout_height="match_parent">
<TabWidget android:id="#android:id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"/>
<FrameLayout android:id="#android:id/tabcontent"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#android:id/tabs"/>
</RelativeLayout>
</android.support.v4.app.FragmentTabHost>
fragment_order_group_tab_list.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/order_detail_tab_list_view"/>
</RelativeLayout>
lvi_group_item.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView android:id="#+id/tab_header"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"/>
<CheckBox android:id="#+id/tab_verification_checkbox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#id/tab_header"
android:layout_alignParentEnd="true"
android:layout_alignParentTop="true"
android:layout_toEndOf="#id/tab_header"
android:text="#string/lvi_group_item_verification_succesfull"
/>
</RelativeLayout>
gr33tz gangfish
Got it working.
I took the wrong fragmentmanager to pass to the tabhost.setup() method in my OnCreateView method in the DetailFragment.
tabHost.setup(getActivity(), getChildFragmentManager() , android.R.id.tabcontent);
Related
I am still learning android. Here I need help to toggle between Play and Pause source in ImageButton in the ListView.
There should be only one song in Play state at a time. So if clicked other should stop.
SongAdapter.java
public class SongAdapter extends ArrayAdapter<Song> {
public SongAdapter(#NonNull Context context, int resource, #NonNull List<Song> objects) {
super(context, resource, objects);
}
#NonNull
#Override
public View getView(final int position, #Nullable View convertView, #NonNull ViewGroup parent) {
View playlistItemView = convertView;
if (playlistItemView == null) {
playlistItemView = LayoutInflater.from(getContext()).inflate(R.layout.playlist_item, parent, false);
}
Song currentSong = getItem(position);
// get list item elements
ImageView albumCoverThumbnail = playlistItemView.findViewById(R.id.playlist_album_thumbnail);
TextView songTitle = playlistItemView.findViewById(R.id.playlist_song_title);
TextView songAlbumTitle = playlistItemView.findViewById(R.id.playlist_song_album_title);
TextView songArtist = playlistItemView.findViewById(R.id.playlist_song_artist);
final ImageButton songPlayButton = playlistItemView.findViewById(R.id.playlist_play_button);
// set data to the list item
assert currentSong != null;
albumCoverThumbnail.setImageResource(currentSong.getSongAlbumCoverId());
songTitle.setText(currentSong.getSongTitle());
songAlbumTitle.setText(currentSong.getSongAlbumTitle());
songArtist.setText(currentSong.getSongSingers());
// set song button action
songPlayButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
songPlayButton.setImageResource(R.drawable.ic_pause_black_24dp);
Toast.makeText(getContext(), "Button clicked for item " + position, Toast.LENGTH_LONG).show();
}
});
return playlistItemView;
}
}
Song.java
public class Song {
private String songAlbumTitle;
private String songTitle;
private String songSingers;
private int songAlbumCoverId;
public Song(String albumTitle, String title, String singers, int albumCoverId) {
songAlbumTitle = albumTitle;
songTitle = title;
songSingers = singers;
songAlbumCoverId = albumCoverId;
}
public String getSongAlbumTitle() {
return songAlbumTitle;
}
public String getSongTitle() {
return songTitle;
}
public String getSongSingers() {
return songSingers;
}
public int getSongAlbumCoverId() {
return songAlbumCoverId;
}
}
Activity.java
public class DreamVoyage extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dream_voyage);
// get view ids
ImageView albumCoverImage = findViewById(R.id.album_cover);
// get intent extras
Bundle bundle = getIntent().getExtras();
// check if bundle in not null and containing value
if (bundle != null) {
String albumTitle = bundle.getString("album_one_title");
String albumBand = bundle.getString("album_one_band");
int albumCover = bundle.getInt("album_one_cover");
albumCoverImage.setImageResource(albumCover);
TextView albumTitleText = findViewById(R.id.album_title);
TextView albumBandText = findViewById(R.id.album_band);
albumTitleText.setText(albumTitle);
albumBandText.setText(albumBand);
ArrayList<Song> songs = new ArrayList<Song>();
songs.add(new Song(albumTitle, "I do it for you", "Bryn Adams", albumCover));
songs.add(new Song(albumTitle, "Here I am", "Bryn Adams", albumCover));
SongAdapter songAdapter = new SongAdapter(this, 0, songs);
ListView listView = findViewById(R.id.playlist_view);
listView.setAdapter(songAdapter);
}
}
}
playlist_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="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:paddingTop="8dp"
android:paddingBottom="8dp"
android:background="#drawable/border_bottom"
android:orientation="horizontal">
<ImageView
android:id="#+id/playlist_album_thumbnail"
android:layout_width="32dp"
android:layout_height="32dp"
android:src="#drawable/album_three"
android:scaleType="centerCrop"
android:contentDescription="#string/album_thumbnail_desc"/>
<android.support.constraint.ConstraintLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1">
<TextView
android:id="#+id/playlist_song_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Mon voyage de rêve"
android:layout_marginLeft="8dp"
android:textColor="#000000"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintStart_toStartOf="parent"/>
<TextView
android:id="#+id/playlist_song_album_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Dream Voyage"
android:textSize="10sp"
android:textColor="#666666"
app:layout_constraintTop_toBottomOf="#+id/playlist_song_title"
app:layout_constraintStart_toStartOf="#id/playlist_song_title"/>
<TextView
android:id="#+id/playlist_song_credit_separator"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=" - "
android:textSize="10sp"
android:textColor="#666666"
app:layout_constraintTop_toBottomOf="#+id/playlist_song_title"
app:layout_constraintStart_toEndOf="#id/playlist_song_album_title"/>
<TextView
android:id="#+id/playlist_song_artist"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=" - John Doen, Jane Doe"
android:textSize="10sp"
android:textColor="#666666"
app:layout_constraintTop_toBottomOf="#+id/playlist_song_title"
app:layout_constraintStart_toEndOf="#id/playlist_song_credit_separator"/>
</android.support.constraint.ConstraintLayout>
<ImageButton
android:id="#+id/playlist_play_button"
android:layout_width="24dp"
android:layout_height="24dp"
android:padding="0dp"
android:layout_gravity="center_vertical"
android:background="#00FFFFFF"
android:src="#drawable/ic_play_arrow_black_24dp"
android:scaleType="centerCrop"/>
</LinearLayout>
Use a variable to store current playing items index
SongAdapter {
int playingIndex = -1 //-1 means no song is playing
.
.
.
}
Set play/pause drawable based on playingIndex and set the playingIndex in the songPlayButton.setOnClickListener
public View getView(final int position, ...) {
if(playingIndex == position)
songPlayButton.setImageResource(R.drawable.ic_play_black_24dp);
else
songPlayButton.setImageResource(R.drawable.ic_pause_black_24dp);
songPlayButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(position == playIndex)
playIndex = -1;
else
playIndex = position;
notifyDataSetChanged();
}
});
}
It should get the job done. But it forces a redraw of all rows. In RecyclerView there is the notifyItemChanged method which can force redraw on single item.
You may try using the method here to update single row https://stackoverflow.com/a/3727813/4907678
My suggestion is migrating to RecyclerView and using notifyItemChanged.
cheers!
I know this question was asked before but even after looking for all the answer
I couldn't find anything relevant. I am basically trying to display a list of items inside a fragment using recycler view, but it saysNo adapter attached; skipping layout even though I have attached an adapter.
Note: I am using a Tab Layout where there are three tabs and a fragment inside each Tab. I am trying to display the recycler view list in one of the fragment.
Here is my Adapter class:
public class SongAdapter extends RecyclerView.Adapter<SongAdapter.SongViewHolder> {
ArrayList<SongData> songList;
public SongAdapter(ArrayList songList) {
this.songList = songList;
}
//Getting hold of each item of the RecyclerView
public static class SongViewHolder extends RecyclerView.ViewHolder {
ImageView albumArt;
TextView Title,Artist;
public SongViewHolder(View itemView) {
super(itemView);
albumArt = (ImageView)itemView.findViewById(R.id.AlbumImage);
Title= (TextView)itemView.findViewById(R.id.Title);
Artist = (TextView)itemView.findViewById(R.id.Artist);
}
}
#Override
public SongViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.music_tiles,parent,false);
SongViewHolder svh= new SongViewHolder(view);
return svh;
}
#Override
public void onBindViewHolder(SongViewHolder holder, int position) {
SongData songData = songList.get(position);
holder.Title.setText(songData.Title);
holder.Artist.setText(songData.Artist);
holder.albumArt.setImageResource(songData.ImageId);
}
#Override
public int getItemCount() {
return songList.size();
}
#Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
}
}
Fragment code:
public class musicFrag extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
public musicFrag() {
// Required empty public constructor
}
// TODO: Rename and change types and number of parameters
public static musicFrag newInstance(String param1, String param2) {
musicFrag fragment = new musicFrag();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_music, container, false);
//Initializing RecyclerView , SongAdapter, LinerLayoutManager
SongData songData =new SongData();
RecyclerView recyclerView = (RecyclerView)view.findViewById(R.id.recyclerView);
recyclerView.setLayoutManager( new LinearLayoutManager(getActivity()));
SongAdapter songAdapter = new SongAdapter(songData.InitializeData());
recyclerView.setAdapter(songAdapter);
return view;
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}
Fragment layout:
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/constraintLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.dannproductions.musify.MainActivity$PlaceholderFragment">
<android.support.v7.widget.RecyclerView
android:id="#+id/recyclerView"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
SongData Class :
public class SongData {
String Title,Artist;
int ImageId;
public SongData() {
};
public SongData(String title, String Artist, int ImageId) {
this.Title = Title;
this.Artist = Artist;
this.ImageId = ImageId;
}
ArrayList<SongData> songList;
public ArrayList<SongData> InitializeData(){
songList = new ArrayList<SongData>();
songList.add(new SongData("Aman","Chatterjee",R.drawable.round));
songList.add(new SongData("Aman","Chatterjee",R.drawable.round));
songList.add(new SongData("Aman","Chatterjee",R.drawable.round));
songList.add(new SongData("Aman","Chatterjee",R.drawable.round));
songList.add(new SongData("Aman","Chatterjee",R.drawable.round));
return songList;
}
}
Here is the RecyclerView item layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v7.widget.CardView
android:id="#+id/card"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<de.hdodenhof.circleimageview.CircleImageView
android:id="#+id/AlbumImage"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_marginEnd="10dp"
android:src="#drawable/round"
app:civ_border_color="#d35400"
app:civ_border_width="4dp" />
<TextView
android:id="#+id/Title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="5dp"
android:layout_marginTop="30dp"
android:layout_toEndOf="#id/AlbumImage"
android:text="TextView"
android:textSize="25sp" />
<TextView
android:id="#+id/Artist"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/Title"
android:layout_centerHorizontal="true"
android:layout_toEndOf="#id/AlbumImage"
android:text="TextView" />
</RelativeLayout>
</android.support.v7.widget.CardView>
</LinearLayout>
I pasted your adapter and recyclerview code in my android studio. and i found no bug in your list filling code. Here is how your list looks.
So double check your tablayout and fragment code if you are having some issue.
I am trying to pass the Json data in the view pager, its not showing any errors. But it is also not displaying the images in the view pager, am not able to understand my error
JSON:http://www.souqalkhaleejia.com/webapis/banners.php
Banner.java
public class Banner extends Fragment {
ViewPager bannerpager;
ArrayList<Data> bannerdta = new ArrayList<Data>();
BannerAdapter bannerAdapter;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View bannerp = inflater.inflate(R.layout.banner, container, false);
bannerpager = (ViewPager) bannerp.findViewById(R.id.bannerpager);
bannerpager.setAdapter(bannerAdapter);
bannerAdapter = new BannerAdapter(bannerdta, getActivity());
loadbanner();
return bannerp;
}
private void loadbanner() {
String bannerurl = "http://www.souqalkhaleejia.com/webapis/banners.php";
JsonObjectRequest bannerreq = new JsonObjectRequest(Request.Method.GET, bannerurl, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray banners = response.getJSONArray("banners");
for (int i = 0; i < banners.length(); i++) {
JSONObject banner1 = banners.getJSONObject(i);
Data banndata = new Data();
banndata.setBannerimages(banner1.getString("image"));
bannerdta.add(banndata);
}
} catch (JSONException e) {
e.printStackTrace();
}
bannerAdapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getActivity(), "" + error, Toast.LENGTH_SHORT).show();
}
});
AppController.getInstance().addToRequestQueue(bannerreq);
}
}
Adapter.java
public class BannerAdapter extends PagerAdapter {
Context cntx;
private ArrayList<Data> blist;
private LayoutInflater binflater;
public BannerAdapter(ArrayList<Data> blist, Context cntx) {
this.blist = blist;
this.cntx = cntx;
binflater= (LayoutInflater) cntx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return blist.size();
}
#Override
public boolean isViewFromObject(View view, Object object) {
return object==view;
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
View view=binflater.inflate(R.layout.banner_layout,container,false);
NetworkImageView bannerimage= (NetworkImageView) view.findViewById(R.id.bannerimage);
Data bannerdata=blist.get(position);
ImageLoader imageLoader=AppController.getInstance().getImageLoader();
bannerimage.setImageUrl(bannerdata.getBannerimages(),imageLoader);
view.setTag(bannerdata);
container.addView(view);
Log.i("Banner", "instantiateItem() [position: " + position + "]" + " childCount:" + container.getChildCount());
return view;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
Log.i("Banner", "destroyItem() [position: " + position + "]" + " childCount:" + container.getChildCount());
}
#Override
public int getItemPosition(Object object) {
Data data= (Data) ((View) object).getTag();
int position=blist.indexOf(data);
if(position>=0){
return position;
}else {
return POSITION_NONE;
}
}
}
i am including the viewpager from another class to the home page
Home.xml
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<include
android:id="#+id/hmebar"
layout="#layout/toolbar" />
<FrameLayout
android:layout_width="match_parent"
android:layout_height="200dp"
>
<include layout="#layout/banner"/>
</FrameLayout>
</LinearLayout>
<ListView
android:id="#+id/nav_drawer"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="#drawable/hover"
android:choiceMode="singleChoice"
android:divider="#android:color/transparent"
android:dividerHeight="0dp" />
</android.support.v4.widget.DrawerLayout>
banner.xml(i had wrote viewpager xml here and included in the Home layout)
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.v4.view.ViewPager
android:id="#+id/bannerpager"
android:layout_width="match_parent"
android:layout_height="200dp"/>
</LinearLayout>
banner_layout.xml(Single viewpager is the image)
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<com.android.volley.toolbox.NetworkImageView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/bannerimage"/>
</LinearLayout>
You not update your bannerdta to bannerAdapter, so bannerAdapter.notifyDataSetChanged() will not work.
you can add method updateData(Data banndata) in BannerAdapter.class
pubilc void updateData(Data banndata) {
blist.add(banndata);
notifyDataSetChanged();
}
and after call network request successfull, usebannerAdapter.updateData(banndata)
I have a static tab in the position 0 which return data from the server. I want by the position return data from the server at that position 1,2,3 etc. I will post the code and I cant figure what is wrong in this code.
the fragment xml
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="match_parent"
tools:context="app.amplitudenet.com.materialapp.Fragmentos.AtendimentoHistorico">
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/IDProcolo1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Numero do Protocolo"
android:layout_marginLeft="12dp"
android:textSize="24dp"
android:layout_marginTop="12dp"
android:textColor="#color/colorPrimary"
android:textStyle="bold" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Histórico: "
android:id="#+id/textoHistorico"
android:textStyle="bold"
android:layout_below="#+id/IDProcolo1"
android:layout_alignBottom="#+id/Historico"
android:layout_alignLeft="#+id/IDProcolo1"
android:layout_alignStart="#+id/IDProcolo1" />
<TextView
android:id="#+id/Historico"
android:text="Número do Histórico"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#666"
android:layout_below="#+id/IDProcolo1"
android:layout_toRightOf="#+id/textoHistorico"
android:layout_toEndOf="#+id/textoHistorico" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Responsável: "
android:layout_marginTop="5dp"
android:id="#+id/textoDataCadastro"
android:textStyle="bold"
android:layout_below="#+id/Historico"
android:layout_marginLeft="12dp"
android:layout_marginStart="8dp"
/>
<TextView
android:id="#+id/FuncionarioHistorico"
android:text="Thiago Belão"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#666"
android:layout_alignTop="#+id/textoDataCadastro"
android:layout_toRightOf="#+id/textoDataCadastro"
android:layout_toEndOf="#+id/textoDataCadastro" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Data de Solução: "
android:layout_marginTop="5dp"
android:id="#+id/textoDataSolucaoHistorico"
android:textStyle="bold"
android:layout_below="#+id/textoDataCadastro"
android:layout_marginLeft="12dp"
android:layout_marginStart="8dp"
/>
<TextView
android:id="#+id/DataSolucaoHistorico"
android:text="19/11/2015"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#666"
android:layout_alignTop="#+id/textoDataSolucaoHistorico"
android:layout_toRightOf="#+id/textoDataSolucaoHistorico"
android:layout_toEndOf="#+id/textoDataSolucaoHistorico" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Etapa Finalizada : "
android:layout_marginTop="5dp"
android:id="#+id/textoEtapa"
android:textStyle="bold"
android:layout_below="#+id/textoDataSolucaoHistorico"
android:layout_marginLeft="12dp"
android:layout_marginStart="8dp"
/>
<TextView
android:id="#+id/Etapa"
android:text="Sim / Não"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#666"
android:layout_alignTop="#+id/textoEtapa"
android:layout_toRightOf="#+id/textoEtapa"
android:layout_toEndOf="#+id/textoEtapa" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Solicitação: "
android:layout_marginTop="5dp"
android:layout_marginLeft="12dp"
android:id="#+id/textoSolicitacaoHistorico"
android:layout_below="#+id/textoEtapa"
android:textStyle="bold"
/>
<TextView
android:id="#+id/textoHistoricoAtendimento"
android:text="Texto da Solicitação"
android:layout_width="fill_parent"
android:layout_marginTop="8dp"
android:layout_height="fill_parent"
android:textColor="#666"
android:textSize="14dp"
android:layout_marginLeft="12dp"
android:layout_below="#+id/textoSolicitacaoHistorico"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/IntPosicao"
android:text="1"
android:visibility="gone" />
</RelativeLayout>
the fragment code.java
public class AtendiementoOcorrencia extends ActionBarActivity {
private Toolbar toolbar;
ViewPager pager;
AtendimentoTabsAdpter adapter;
SlidingTabLayout tabs;
ArrayList<String>Titles;
public static final int CONNECTION_TIME = 1000 *15;
public static final String SERVIDOR = "http://www.creativeriopreto.com.br/app/";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_atendiemento_ocorrencia);
toolbar = (Toolbar) findViewById(R.id.app_bar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
Bundle id = getIntent().getExtras();
String get = id.getString("id");
String total = id.getString("total");
String codigo = id.getString("codigo");
int abas = Integer.parseInt(total);
Titles = Abas(abas+1);
int numerodeabas = abas + 1;
adapter = new AtendimentoTabsAdpter(getSupportFragmentManager(),Titles, numerodeabas);
pager = (ViewPager) findViewById(R.id.pagerAtendimento);
pager.setAdapter(adapter);
tabs = (SlidingTabLayout) findViewById(R.id.tabsAtendimento);
tabs.setDistributeEvenly(true);
tabs.setCustomTabColorizer(new SlidingTabLayout.TabColorizer() {
#Override
public int getIndicatorColor(int position) {
return getResources().getColor(R.color.selector);
}
});
tabs.setViewPager(pager);
tabs.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
TextView texto = (TextView) findViewById(R.id.IntPosicao);
texto.setText(String.valueOf(position));
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
}
public ArrayList<String> Abas(int numeroAbas) {
int i;
ArrayList<String> titulos = new ArrayList<>();
titulos.add("Detalhes");
for (i = 1; i < numeroAbas; i++)
{
titulos.add("Hist. Nº" + i);
}
return titulos;
}
}
the activity.java
public class AtendimentoHistorico extends Fragment {
Historico item;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View tela = inflater.inflate(R.layout.fragment_atendimento_historico, container, false);
Bundle id = getActivity().getIntent().getExtras();
String codigo = id.getString("codigo");
int codid = Integer.parseInt(codigo);
TextView posicao = (TextView) tela.findViewById(R.id.IntPosicao);
String coisocoisado = posicao.getText().toString();
int pos;
pos = Integer.parseInt(coisocoisado);
item = new Historico(codid,pos);
Autenticado(item);
return tela;
}
public void Autenticado(Historico historico) {
ServerRequests server = new ServerRequests(getActivity());
server.getDadosHistoricoBackground(historico, new GetHistoricoCallBack() {
#Override
public void done(Historico returnedHistorico) {
if (returnedHistorico == null)
{
Erro();
}
else
{
Bundle id = getActivity().getIntent().getExtras();
String get = id.getString("id");
TextView momo = (TextView) getActivity().findViewById(R.id.IDProcolo1);
momo.setText("Protocolo Nº "+get);
TextView momo1 = (TextView) getActivity().findViewById(R.id.FuncionarioHistorico);
if (returnedHistorico.Setor == "null")
{
momo1.setText(""+returnedHistorico.Funcionario);
}
else
{
momo1.setText(""+returnedHistorico.Setor);
}
TextView momo2 = (TextView) getActivity().findViewById(R.id.DataSolucaoHistorico);
momo2.setText(""+returnedHistorico.Data);
TextView momo3 = (TextView) getActivity().findViewById(R.id.Etapa);
momo3.setText(""+returnedHistorico.Etapa);
TextView momo4 = (TextView) getActivity().findViewById(R.id.textoHistoricoAtendimento);
momo4.setText(""+returnedHistorico.Solucao);
TextView momo5 = (TextView) getActivity().findViewById(R.id.Historico);
momo5.setText(""+returnedHistorico.Sequencia);
TextView momo6 = (TextView) getActivity().findViewById(R.id.txtFinalizado);
momo6.setText(""+returnedHistorico.Finalizado);
}
}
});
}
private void Erro() {
AlertDialog.Builder alerta = new AlertDialog.Builder(getActivity());
alerta.setMessage("Erro ao Carregar Histórico de Atendimento");
alerta.setPositiveButton("OK", null);
alerta.show();
}
}
the adpter code
public class AtendimentoTabsAdpter extends FragmentStatePagerAdapter {
ArrayList<String> Titles; // This will Store the Titles of the Tabs which are Going to be passed when ViewPagerAdapter is created
int NumbOfTabs; // Store the number of tabs, this will also be passed when the ViewPagerAdapter is created
SparseArray<Fragment> registeredFragments = new SparseArray<Fragment>();
// Build a Constructor and assign the passed Values to appropriate values in the class
public AtendimentoTabsAdpter(FragmentManager fm,ArrayList<String> mTitles, int mNumbOfTabsumb) {
super(fm);
this.Titles = mTitles;
this.NumbOfTabs = mNumbOfTabsumb;
}
//This method return the fragment for the every position in the View Pager
#Override
public Fragment getItem(int position) {
if(position == 0) // if the position is 0 we are returning the First tab
{
AtendimentoDetalhado tab1 = new AtendimentoDetalhado();
return tab1;
}
else // As we are having 2 tabs if the position is now 0 it must be 1 so we are returning second tab
{
AtendimentoHistorico tab2 = new AtendimentoHistorico();
return tab2;
}
}
// This method return the titles for the Tabs in the Tab Strip
#Override
public CharSequence getPageTitle(int position) {
return Titles.get(position);
}
// This method return the Number of tabs for the tabs Strip
#Override
public int getCount() {
return NumbOfTabs;
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
Fragment fragment = (Fragment) super.instantiateItem(container, position);
registeredFragments.put(position, fragment);
return fragment;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
registeredFragments.remove(position);
super.destroyItem(container, position, object);
}
public Fragment getRegisteredFragment(int position) {
return registeredFragments.get(position);
}
I have changed the adpater and make a list, updatated the method in my rest api now i have two tabs and all the data i want
I'm really new in Android. I have this problem, I have an Activity (MainActivity) and there is a NavigationDrawer, this switches two fragments - ActivitiesFragment and ReportFragments.
The problem is with ActivitiesFragments, data is not displayed.
I have my adapter ready and my layouts ready and the fragment. When I debugg my app, it actually brings data, but is not shown. This is my code:
ActivitiesAdapter
public class ActivitiesAdapter extends ArrayAdapter<Activities>
{
Context mContext;
int mLayoutResourceId;
public ActivitiesAdapter(Context context, int layoutResourceId)
{
super(context, layoutResourceId);
mContext = context;
mLayoutResourceId = layoutResourceId;
}
public View getView(int position, View convertView, ViewGroup parent)
{
View row = convertView;
final Activities currentItem = getItem(position);
if (row == null)
{
LayoutInflater inflater = ((Activity) mContext).getLayoutInflater();
row = inflater.inflate(mLayoutResourceId, parent, false);
}
row.setTag(currentItem);
final TextView tituloview = (TextView) row.findViewById(R.id.tituloAct);
tituloview.setText(currentItem.getTitle());
final TextView descrpview = (TextView) row.findViewById(R.id.descrAct);
descrpview.setText(currentItem.getDescription());
return row;
}
}
This is my fragment ActivitiesFragment
public class ActivitiesFragment extends Fragment
{
protected static final String TAG = "ActivitiesFragmment";
private MobileServiceClient mClient;
private MobileServiceTable<Activities> mActivitiesTable;
private ActivitiesAdapter mAdapter;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.act_listfragment, container, false);
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState)
{
super.onActivityCreated(savedInstanceState);
try
{
mClient = new MobileServiceClient("https://site.azure-mobile.net/",
"APPLICATIONKEYAPPLICATIONKEY",
getActivity().getApplicationContext()).withFilter(new ProgressFilter());
mActivitiesTable = mClient.getTable(Activities.class);
}
catch (MalformedURLException e)
{
createAndShowDialog(new Exception("There was an error creating the Mobile Service. Verify the URL"), "Error");
}
mAdapter = new ActivitiesAdapter(getActivity(), R.layout.act_itemlist);
ListView listViewToDo = (ListView) getView().findViewById(R.id.activities_fragment_list);
listViewToDo.setAdapter(mAdapter);
refreshItemsFromTable();
}
private void createAndShowDialog(Exception exception, String title)
{
createAndShowDialog(exception.toString(), title);
}
private void createAndShowDialog(String message, String title)
{
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity().getApplicationContext());
builder.setMessage(message);
builder.setTitle(title);
builder.create().show();
}
private void refreshItemsFromTable()
{
mActivitiesTable.execute(new TableQueryCallback<Activities>()
{
public void onCompleted(List<Activities> result, int count, Exception exception, ServiceFilterResponse response) {
if (exception == null) {
mAdapter.clear();
for (Activities item : result) {
mAdapter.add(item);
Log.i(TAG, "Titulo: " + item.getTitle());
}
} else {
createAndShowDialog(exception, "Error");
}
}
});
}
}
I don't know whats wrong, but I guess this block is not working on the OnActivityCreated method:
mAdapter = new ActivitiesAdapter(getActivity(), R.layout.act_itemlist);
ListView listViewToDo = (ListView) getView().findViewById(R.id.activities_fragment_list);
listViewToDo.setAdapter(mAdapter);
refreshItemsFromTable();
And here are my Layouts:
This is my frgament's layout:
<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:background="#e1e1e1"
android:orientation="vertical" >
<TextView
android:id="#+id/tvTituloActs"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/all_activities"
android:layout_marginLeft="16dp"
android:layout_marginTop="8dp"
android:textColor="#009ad2"
android:textAppearance="?android:attr/textAppearanceMedium" />
<ListView android:id="#+id/activities_fragment_list"
android:layout_marginTop="8dp"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FFFFFF"
android:layout_weight="1"
tools:listitem="#layout/act_itemlist"
android:drawSelectorOnTop="false"/>
<TextView android:id="#id/android:empty"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="No hay datos"/>
</LinearLayout>
This is the layout act_itemlist. The row layout:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="64dp"
android:orientation="horizontal">
<ImageView
android:id="#+id/icon"
android:layout_width="32dp"
android:layout_height="32dp"
android:layout_marginLeft="8dp"
android:gravity="center_vertical"
android:src="#drawable/done"
android:layout_gravity="center_vertical"/>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/tvTituloAct"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="8dp"
android:layout_marginTop="16dp"
android:textSize="16sp"/>
<TextView
android:id="#+id/tvDescrAct"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="8dp"
android:text="Description de la actividad" />
</LinearLayout>
</LinearLayout>
I really need help with this! Please if someone can see something that I'm missing please tell me!
Thanks!!!!
Try to swap these lines:
mAdapter = new ActivitiesAdapter(getActivity(), R.layout.act_itemlist);
ListView listViewToDo = (ListView) getView().findViewById(R.id.activities_fragment_list);
refreshItemsFromTable(); // populate first before attaching your adapter
listViewToDo.setAdapter(mAdapter);
I finally solved my problem. Everything was Ok, the only detail was the layout. It was on the fragments layout.
<TextView android:id="#id/android:empty"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="No hay datos"/>
This textview did not let to show the data so I deleted it and worked.
Thankk you for your help #LazyNinja