Ive tried to solve my Portrait/Landscape segment in my project using this tutorial:
http://www.cs.dartmouth.edu/~campbell/cs65/lecture09/lecture09.html
Everything seems to work fine (both landscape and portrait), but if i rotate from portrait to landscape or visa verse the app crashes with this: error
11-26 13:42:38.822 22594-22594/picturedtalk.com.picturedtalk E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: picturedtalk.com.picturedtalk, PID: 22594
java.lang.RuntimeException: Unable to start activity ComponentInfo{picturedtalk.com.picturedtalk/picturedtalk.com.picturedtalk.Signs.SignActivity}: android.app.Fragment$InstantiationException: Unable to instantiate fragment picturedtalk.com.picturedtalk.Signs.DetailsFragment: make sure class name exists, is public, and has an empty constructor that is public
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2338)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2390)
at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:3930)
at android.app.ActivityThread.access$900(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1327)
at android.os.Handler.dispatchMessage(Handler.java:110)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:5292)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:824)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:640)
at dalvik.system.NativeStart.main(Native Method)
Caused by: android.app.Fragment$InstantiationException: Unable to instantiate fragment picturedtalk.com.picturedtalk.Signs.DetailsFragment: make sure class name exists, is public, and has an empty constructor that is public
at android.app.Fragment.instantiate(Fragment.java:601)
at android.app.FragmentState.instantiate(Fragment.java:98)
at android.app.FragmentManagerImpl.restoreAllState(FragmentManager.java:1759)
at android.app.Activity.onCreate(Activity.java:899)
at picturedtalk.com.picturedtalk.Signs.SignActivity.onCreate(SignActivity.java:16)
Any suggestion how i can stop the app from crashing when changing from portrait to landscape view?
That part of my app:
SignActivity.java
public class SignActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.signs_layout);
}
}
ListFragment.java
public class ListFragment extends android.app.ListFragment {
private ArrayList<Signs> storage;
boolean mDualPane;
int mCurrentCheckPosition = 0;
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
SignAdapter adapter = new
SignAdapter(Storage.get(getActivity()).getStorageOfSigns());
setListAdapter(adapter);
//Check if the we are using layout-land version of the XML to figure out if
portrait/landscape
View detailsFrame = getActivity().findViewById(R.id.details);
mDualPane = detailsFrame != null && detailsFrame.getVisibility() == View.VISIBLE;
//restore last state
if (savedInstanceState != null) {
mCurrentCheckPosition = savedInstanceState.getInt("curChoice", 0);
}
if (mDualPane) {
//only select one item at the time
getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
showDetails(mCurrentCheckPosition);
} else {
getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
getListView().setItemChecked(mCurrentCheckPosition, true);
}
}
//Handle flipping during fragment use
//DOES NOT WORK
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
savedInstanceState.putInt("curChoice", mCurrentCheckPosition);
}
private void showDetails(int index) {
mCurrentCheckPosition = index;
if (mDualPane) {
getListView().setItemChecked(index, true);
DetailsFragment details = (DetailsFragment) getFragmentManager().findFragmentById(R.id.details);
if (details == null || details.getShownIndex() != index) {
UUID startId = ((SignAdapter) getListAdapter()).getItem(0).getId();
details = new DetailsFragment(startId);
// Execute a transaction, replacing any existing fragment
// with this one inside the frame.
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.details, details);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.commit();
}
} else {
Intent intent = new Intent();
intent.setClass(getActivity(), DetailsActivity.class);
intent.putExtra("index", index);
startActivity(intent);
}
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
if(!mDualPane){
Signs signs = ((SignAdapter) getListAdapter()).getItem(position);
Intent intent = new Intent(getActivity(),
picturedtalk.com.picturedtalk.Signs.DetailsActivity.class);
intent.putExtra(DetailsFragment.EXTRA_SIGN_ID, signs.getId());
startActivity(intent);
}
else{
UUID signId = ((SignAdapter) getListAdapter()).getItem(position).getId();
DetailsFragment fragment = new DetailsFragment(signId);
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.details, fragment);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.commit();
}
}
private class SignAdapter extends ArrayAdapter<Signs> {
public SignAdapter(ArrayList<Signs> sSigns) {
super(getActivity(), 0, sSigns);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
//If we were given a view, inflate one
if (convertView == null) {
convertView = getActivity().getLayoutInflater().inflate(R.layout.signs_row,
null);
}
//Configure the view for this Crime
Signs signs = getItem(position);
TextView titleTextView = (TextView) convertView.findViewById(R.id.label);
titleTextView.setText(signs.getName());
return convertView;
}
}}
DetailsActivity.java
public class DetailsActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
UUID mSignId;
mSignId = (UUID)getIntent().getSerializableExtra(DetailsFragment.EXTRA_SIGN_ID);
DetailsFragment details = new DetailsFragment(mSignId);
getFragmentManager().beginTransaction().replace(android.R.id.content, details).commit();
UUID STOPTHIs = mSignId;
}
else {
UUID mSignId;
mSignId = (UUID)getIntent().getSerializableExtra(DetailsFragment.EXTRA_SIGN_ID);
DetailsFragment details = new DetailsFragment(mSignId);
getFragmentManager().beginTransaction().add(android.R.id.content, details).commit();
}
}}
DetailsFragment.java
public class DetailsFragment extends Fragment {
public int getShownIndex() {
return getArguments().getInt("index", 0);
}
public static final String EXTRA_SIGN_ID = "sign_id";
private UUID extraSignId;
// private static DetailsFragment detailsFragment;
private View view;
private TextView title;
private ImageView illustrativeView;
private ImageView pictureView;
private VideoView videoView;
private Signs mSign;
private String TAG = "DETAILFRAGMENT";
public DetailsFragment(UUID signId) {
this.extraSignId = signId;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mSign = Storage.get(getActivity()).getSigns(extraSignId);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.signs_details, container, false);
title = (TextView) view.findViewById(R.id.title);
illustrativeView = (ImageView) view.findViewById(R.id.illustrateImage);
pictureView = (ImageView) view.findViewById(R.id.pictureImage);
videoView = (VideoView) view.findViewById(R.id.videoView);
title.setText(mSign.getName());
try {
Bitmap illuBitmap = BitmapFactory.decodeFile(mSign.getIllustrativeURL());
illustrativeView.setImageBitmap(illuBitmap);
} catch (Exception e) {
Log.d(TAG, "failed loading illustrative image");
}
try {
Bitmap picBitmap = BitmapFactory.decodeFile(mSign.getImageURL());
pictureView.setImageBitmap(picBitmap);
} catch(Exception e){
Log.d(TAG, "failed loading picture image");
}
try {
Uri uri = Uri.parse(mSign.getVideoURL());
videoView.setVideoURI(uri);
videoView.requestFocus();
videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mp.setLooping(true);
}
});
videoView.setOnErrorListener(new MediaPlayer.OnErrorListener() {
#Override
public boolean onError(MediaPlayer mp, int what, int extra) {
videoView.setBackgroundResource(R.drawable.simp);
return true;
}
});
videoView.start();
} catch (Exception e) {
Log.d(TAG, "failed loading video");
}
return view;
}}
Signs.java
public class Signs {
UUID id;
String name;
String videoURL;
String imageURL;
String illustrativeURL;
public Signs(String name, String imageURL,String videoURL, String illustrativeURL){
this.id = UUID.randomUUID();
this.name = name;
this.videoURL = videoURL;
this.imageURL = imageURL;
this.illustrativeURL = illustrativeURL;
}
public UUID getId() {
return id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getVideoURL() {
return videoURL;
}
public void setVideoURL(String videoURL) {
this.videoURL = videoURL;
}
public String getImageURL() {
return imageURL;
}
public void setImageURL(String imageURL) {
this.imageURL = imageURL;
}
public String getIllustrativeURL() {
return illustrativeURL;
}
public void setIllustrativeURL(String illustrativeURL) {
this.illustrativeURL = illustrativeURL;
}}
signs_layout.xml (layout)
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<fragment
android:id="#+id/titles"
android:layout_width="match_parent"
android:layout_height="match_parent"
class="picturedtalk.com.picturedtalk.Signs.ListFragment" />
signs_layout.xml (/layout-land)
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:baselineAligned="false"
android:orientation="horizontal" >
<fragment
android:id="#+id/titles"
android:layout_width="0px"
android:layout_height="match_parent"
android:layout_weight="1"
class="picturedtalk.com.picturedtalk.Signs.ListFragment" />
<FrameLayout
android:id="#+id/details"
android:layout_width="0px"
android:layout_height="match_parent"
android:layout_weight="3"
android:background="?android:attr/detailsElementBackground" />
</LinearLayout>
signs_details.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="50dp"
android:text="TitleHere"
android:id="#+id/title"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="98dp" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/illustrateImage"
android:layout_below="#id/title"
android:layout_toRightOf="#+id/pictureImage"
android:background="#drawable/signs_logo"/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/pictureImage"
android:layout_centerVertical="true"
android:layout_below="#+id/title"
android:layout_centerHorizontal="true"
android:background="#drawable/simp"/>
<VideoView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/videoView"
android:layout_below="#id/title"
android:layout_toLeftOf="#+id/pictureImage"/>
</RelativeLayout>
signs_listview.xml
<ListView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/listview"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
signs_row.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/label"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#+id/label"
android:textSize="20px" >
</TextView>
</LinearLayout>
You can avoid activity recreation by adding following to your application's manifest file.
as
android:configChanges="keyboardHidden|orientation|screenSize"
and
<activity
android:name=".your activity"
android:configChanges="orientation|keyboardHidden|screenSize"
android:label="#string/app_name" >
</activity>
Related
I have implemented the SwipeRefreshLayout in many of the pages,and it working fine. but here i got stuck with one specific implementation , where i have a SwipeRefreshLayout for the ViewPager and ViewPager holding the FragmentPagerAdapter.
In my case , I have a ViewPager with two tabs and each holding the fragment with RecyclerView. On main page I have a SwipeRefreshLayout and on the onRefresh i need to load the API and update the fragments in ViewPager. Updating is working fine but unfortunately RecyclerView inside the Fragment ( ViewPager tab Item ) not scrolling top and it always calling the SwipeToRefresh.
I am familiar with using the SwipeRefreshLayout with RecyclerView, but here the problem is the main child of the SwipeRefreshLayout is ViewPager and it having the Fragment inside it and that fragment is holding the RecyclerView.
I have a thought of moving the SwipeRefreshLayout inside the fragments for the RecyclerView , but again here i have challenges like both the Fragments is having the same API. So that i am using the SwipeRefreshLayout directly on ViewPager to refresh my data.
Here is some of my codes.
MainContacts.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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="match_parent">
<LinearLayout
android:id="#+id/ll_no_records"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_centerInParent="true"
android:gravity="center"
android:orientation="vertical"
android:visibility="gone">
<ImageView
android:id="#+id/iv_retry"
android:layout_width="60dp"
android:layout_height="60dp"
android:layout_gravity="center"
android:contentDescription="#string/todo"
android:src="#drawable/ic_reload" />
<TextView
android:id="#+id/textError"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="25dp"
android:gravity="center"
android:text="#string/no_contact_found"
android:textAppearance="#style/Base.TextAppearance.AppCompat.Medium"
android:textColor="#color/colorDarkGray" />
</LinearLayout>
<LinearLayout
android:id="#+id/ll_process"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_centerInParent="true"
android:alpha="1"
android:gravity="center"
android:orientation="vertical"
android:visibility="visible">
<ProgressBar
android:id="#+id/progress"
android:layout_width="50dp"
android:layout_height="40dp"
android:layout_gravity="center"
android:indeterminate="true" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="#string/fetching"
android:textAppearance="#style/Base.TextAppearance.AppCompat.Medium"
android:textColor="#color/colorDarkGray" />
</LinearLayout>
<android.support.v4.widget.SwipeRefreshLayout
android:id="#+id/swipeRefreshLayout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:id="#+id/contacts_screen"
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<android.support.design.widget.TabLayout
android:id="#+id/my_contacts_tabs"
style="#style/MyCustomTabLayout"
android:layout_width="match_parent"
app:tabBackground="#color/colorWhite"
android:layout_height="wrap_content" />
<android.support.v4.view.ViewPager
android:id="#+id/my_contacts_view_pager"
android:layout_width="match_parent"
android:layout_height="0px"
android:layout_weight="1"
android:background="#android:color/transparent" >
</android.support.v4.view.ViewPager>
</LinearLayout>
</android.support.v4.widget.SwipeRefreshLayout>
</RelativeLayout>
contacts.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:hc="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:id="#+id/ll_no_records"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_centerInParent="true"
android:gravity="center"
android:orientation="vertical"
android:visibility="gone">
<ImageView
android:id="#+id/iv_retry"
android:layout_width="60dp"
android:layout_height="60dp"
android:layout_gravity="center"
android:contentDescription="#string/todo"
android:src="#drawable/ic_reload" />
<TextView
android:id="#+id/textError"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="25dp"
android:gravity="center"
android:text="#string/no_contact_found"
android:textAppearance="#style/Base.TextAppearance.AppCompat.Medium"
android:textColor="#color/colorDarkGray" />
</LinearLayout>
<com.diegocarloslima.fgelv.lib.FloatingGroupExpandableListView
android:id="#+id/contactList"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#id/searchContainer"
android:animateLayoutChanges="true"
android:childDivider="#android:color/transparent" />
</RelativeLayout>
MainFragment ( Which i am using to load the child fragments , SwipeTORefreshLayout + ViewPager here)
public class MainFragment extends BaseFragment {
private TextView mTextError;
private LinearLayout llNoRecords, ll_process;
private ImageView iv_retry;
private MaterialSearchView materialSearchView;
PHCJsonResponseContactDetailModel mContactResponseModel;
int expandableListSelectionType = ExpandableListView.PACKED_POSITION_TYPE_NULL;
boolean actionModeEnabled;
private Activity mActivity;
SwipeRefreshLayout mSwipeRefreshLayout;
private ViewPager viewPager;
TabLayout tabLayout;
ContactsTabPagerAdapter mAdapter;
ArrayList<PHCContactDetailModel> mContactList =new ArrayList<>();
ArrayList<PHCContactDetailModel> mFavoriteList;
boolean isSwipeToRefresh;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
mActivity = getActivity();
View view = inflater.inflate(R.layout.phc_contact_fragment, container, false);
getViewId(view);
setListener();
if (isNetworkAvailable()) {
if(((MainDrawerActivity)mActivity).getPHCContactFragmentData()==null)
getAllContactData();
else
updateWidgets();
} else {
showNoNetworkToast();
llNoRecords.setVisibility(View.VISIBLE);
mTextError.setText(getResources().getText(R.string.no_internet_retry));
}
return view;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public void onResume() {
super.onResume();
}
/*#Override
public void onPrepareOptionsMenu(final Menu menu) {
getActivity().getMenuInflater().inflate(R.menu.menu_fragment_group, menu);
}*/
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.menu_fragment_contacts, menu);
MenuItem item = menu.findItem(R.id.action_search);
materialSearchView.setMenuItem(item);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.action_create_group) {
Intent createGroupIntent = new Intent(getActivity(), PHCCreateGroupActivity.class);
createGroupIntent.putExtra("comeFrom", PHCAppConstant.GROUP_ADD);
getActivity().startActivity(createGroupIntent);
}
return super.onOptionsItemSelected(item);
}
private void setListener() {
iv_retry.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (isNetworkAvailable()) {
getAllContactData();
} else {
showNoNetworkToast();
}
}
});
}
private void getViewId(View view) {
mTextError = (TextView) view.findViewById(R.id.textError);
ll_process = (LinearLayout) view.findViewById(R.id.ll_process);
llNoRecords = (LinearLayout) view.findViewById(R.id.ll_no_records);
iv_retry = (ImageView) view.findViewById(R.id.iv_retry);
viewPager = (ViewPager) view.findViewById(R.id.my_contacts_view_pager);
tabLayout = (TabLayout) view.findViewById(R.id.my_contacts_tabs);
mSwipeRefreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.swipeRefreshLayout);
mSwipeRefreshLayout.setColorSchemeResources(R.color.colorPrimary,
android.R.color.holo_green_dark,
android.R.color.holo_orange_dark,
android.R.color.holo_blue_dark);
mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
if(mContactResponseModel!=null && mContactResponseModel.getData().size() >0)
{
isSwipeToRefresh = true;
getAllContactData();
}
}
});
materialSearchView = (MaterialSearchView) getActivity().findViewById(R.id.search_view);
}
private void getAllContactData() {
if (isNetworkAvailable()) {
// showProgress();
PHCApiInterface apiService = PHCApiClient.getClient(getActivity()).create(PHCApiInterface.class);
Call<PHCJsonResponseContactDetailModel> call = apiService.contactData(getApplicationData(getActivity()).getAuthToken(), getApplicationData(getActivity()).getUserID());
call.enqueue(new Callback<PHCJsonResponseContactDetailModel>() {
#Override
public void onResponse(Call<PHCJsonResponseContactDetailModel> call, Response<PHCJsonResponseContactDetailModel> response) {
Log.d(TAG, "getContacts URL " + response.raw().request().url());
Log.d(TAG, "getContacts Resp " + new Gson().toJson(response.body()));
mContactResponseModel = response.body();
((MainDrawerActivity)mActivity).setPHCContactFragmentData(mContactResponseModel);
if(mSwipeRefreshLayout.isRefreshing())
{
// cancel the Visual indication of a refresh
mSwipeRefreshLayout.setRefreshing(false);
}
if(isSwipeToRefresh)
{
isSwipeToRefresh=false;
updateWidgets();
}
else
updateWidgets();
}
#Override
public void onFailure(Call<PHCJsonResponseContactDetailModel> call, Throwable t) {
if(mSwipeRefreshLayout.isRefreshing())
{
// cancel the Visual indication of a refresh
mSwipeRefreshLayout.setRefreshing(false);
}
isSwipeToRefresh=false;
dismissProgress();
mTextError.setVisibility(View.VISIBLE);
}
});
} else {
isSwipeToRefresh=false;
if(mSwipeRefreshLayout.isRefreshing())
{
// cancel the Visual indication of a refresh
mSwipeRefreshLayout.setRefreshing(false);
}
showNoNetworkAlert();
}
}
private void updateWidgets() {
if (mContactResponseModel.getStatusCode() == 401 || mContactResponseModel.getStatusCode() == 402) {
showSessionExpireAlert(mContactResponseModel.getStatusMessage(), mContactResponseModel.getStatusCode());
return;
}
if (mContactResponseModel != null && mContactResponseModel.getStatusCode() == 1) {
dismissProgress();
mTextError.setVisibility(View.GONE);
mContactList = mContactResponseModel.getData();
mFavoriteList = mContactResponseModel.getData();
if(mContactList!=null && mContactList.size()>0)
{
llNoRecords.setVisibility(View.GONE);
mAdapter = new ContactsTabPagerAdapter(getActivity().getApplicationContext(), getChildFragmentManager(), mContactList , mFavoriteList);
viewPager.setAdapter(mAdapter);
tabLayout.setupWithViewPager(viewPager);
}
else {
llNoRecords.setVisibility(View.VISIBLE);
}
} else {
dismissProgress();
mTextError.setVisibility(View.VISIBLE);
}
}
public void dismissProgress() {
ll_process.setVisibility(View.GONE);
super.dismissProgress();
}
private void initiateContactChat(final PHCFacilityDetailsModel facilityDetailsModel, final int groupPosition, final int childPosition) {
String header = getApplicationData(getActivity()).getAuthToken();
PHCApiInterface apiService = PHCApiClient.getClient(getActivity()).create(PHCApiInterface.class);
Call<PHCContactInitiateChatResponseModel> call = apiService.initiateContactChat(header, facilityDetailsModel.getUserId(), getApplicationData(getActivity()).getUserID(), 0);
call.enqueue(new Callback<PHCContactInitiateChatResponseModel>() {
#Override
public void onResponse(Call<PHCContactInitiateChatResponseModel> call, Response<PHCContactInitiateChatResponseModel> response) {
Log.d(TAG, "initiateContactChat URL " + response.raw().request().url());
Log.d(TAG, "initiateContactChat Resp " + new Gson().toJson(response.body()));
PHCContactInitiateChatResponseModel mContactInitiateChatModel = response.body();
if (mContactInitiateChatModel != null && mContactInitiateChatModel.getStatusCode() == 1) {
Intent chatIntent = new Intent(getActivity(), PHCChatActivity.class);
// chatIntent.putExtra("headerName",mData.get(groupPosition).getFacilityDetails().get(childPosition).getUserName());
chatIntent.putExtra("headerName", facilityDetailsModel.getUserName());
chatIntent.putExtra("groupId", mContactInitiateChatModel.getData().getGroupId());
getActivity().startActivity(chatIntent);
}
}
#Override
public void onFailure(Call<PHCContactInitiateChatResponseModel> call, Throwable t) {
Toast.makeText(getActivity(), "Something went wrong! Please try again", Toast.LENGTH_SHORT).show();
}
});
}
}
ContactsTabPagerAdapter.java
public class ContactsTabPagerAdapter extends FragmentPagerAdapter {
/**
* The Page count.
*/
final int PAGE_COUNT = 2;
private String[] tabTitles = { "Contacts", "Favorites" };
private ArrayList<PHCContactDetailModel> mContactsList;
private ArrayList<PHCContactDetailModel> mFavoritesList;
Context mContext ;
public ContactsTabPagerAdapter(Context context, FragmentManager fm ,ArrayList<PHCContactDetailModel> contacts , ArrayList<PHCContactDetailModel> favs) {
super(fm);
this.mContext = context;
this.mContactsList = contacts;
this.mFavoritesList=favs;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
ContactsFragment mContactsFragment =new ContactsFragment();
Bundle bundle=new Bundle();
bundle.putSerializable("Contacts", (Serializable) mContactsList);
mContactsFragment.setArguments(bundle);
return mContactsFragment;
case 1:
FavoritesFragment mFavoritesFragment=new FavoritesFragment();
Bundle pastBundle=new Bundle();
pastBundle.putSerializable("Favorites", (Serializable) mFavoritesList);
mFavoritesFragment.setArguments(pastBundle);
return mFavoritesFragment;
}
return null;
}
#Override
public int getCount() {
return 2;
}
#Override
public CharSequence getPageTitle(int position) {
// Generate title based on item position
return tabTitles[position];
}
/**
* Update.
*
* #param lContactsList contact list to update
* #param lFavoritesList favorites list to update
*/
//call this method to update fragments in ViewPager dynamically
public void update(ArrayList<PHCContactDetailModel> lContactsList, ArrayList<PHCContactDetailModel> lFavoritesList) {
this.mContactsList = lContactsList;
this.mFavoritesList = lFavoritesList;
notifyDataSetChanged();
}
#Override
public int getItemPosition(Object object) {
if (object instanceof UpdatableFragment) {
((UpdatableFragment) object).update(mContactsList, mFavoritesList);
}
//don't return POSITION_NONE, avoid fragment recreation.
return super.getItemPosition(object);
}
}
ContactsFragment.java
public class ContactsFragment extends BaseFragment implements UpdatableFragment{
private static final String TAG = "ContactFragmentTab";
private FloatingGroupExpandableListView mContactExpandableList;
private PHCContactAdapter mAdapter;
WrapperExpandableListAdapter wrapperAdapter;
boolean actionModeEnabled;
private LinearLayout llNoRecords;
private ArrayList<PHCContactDetailModel> mContactsData;
public ContactsFragment() {
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
}
#SuppressWarnings("unchecked")
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_contacts, container, false);
getViewId(rootView);
Bundle bundle= getArguments();
if(bundle !=null)
{
Log.d(TAG, "bundle is not empty");
mContactsData= (ArrayList<PHCContactDetailModel>) bundle.getSerializable("Contacts");
}
System.out.print("Contacts Size::" + mContactsData.size());
if(mContactsData!=null)
{
updateWidgets();
}
return rootView;
}
private void updateWidgets() {
mAdapter = new PHCContactAdapter(getActivity(), mContactsData, new ListShowingHidingListener() {
#Override
public void listHideAndShow(boolean isData) {
if (isData) {
llNoRecords.setVisibility(View.GONE);
mContactExpandableList.setVisibility(View.VISIBLE);
listUpdate();
} else {
llNoRecords.setVisibility(View.VISIBLE);
mContactExpandableList.setVisibility(View.GONE);
}
}
});
wrapperAdapter = new WrapperExpandableListAdapter(mAdapter);
mContactExpandableList.setAdapter(wrapperAdapter);
try {
for (int i = 0; i < wrapperAdapter.getGroupCount(); i++) {
mContactExpandableList.expandGroup(i);
}
} catch (Exception e) {
Log.e("Exception in Expand", "" + e);
}
}
private void listUpdate() {
try {
for (int i = 0; i < wrapperAdapter.getGroupCount(); i++) {
mContactExpandableList.expandGroup(i);
}
} catch (Exception e) {
Log.e("Exception in Expand", "" + e);
}
}
private void getViewId(View view) {
// mContactExpandableList = (ExpandableListView) view.findViewById(R.id.contactList);
mContactExpandableList = (FloatingGroupExpandableListView) view.findViewById(R.id.contactList);
}
#Override
public void update(ArrayList<PHCContactDetailModel> contactsData, ArrayList<PHCContactDetailModel> favoritesData) {
this.mContactsData = contactsData;
updateWidgets();
}
}
similarly i have Favorites example as well. Mostly both will look like same, that's why not posting it here.
Sorry for posting the long question. Any help regarding this. Apologies for my poor English. Thanks in Advance.
i've had a problem, when i've tried to view this below fragment showing "skipping layout". Can any one help me out how to solve this problem please.
I'm getting this "No adapter attached; skipping layout." when i CLICK any imageview on ThirdFragment UI ayout, not when the images display in Thirdfragment UI layout.
ThirdFrament.java
public class ThirdFragment extends Fragment implements RecyclerViewAdapter.ItemListener {
static final String url = "https://jsonparsingdemo-cec5b.firebaseapp.com/jsonData/moviesData.txt" ;
RecyclerView recyclerView;
RecyclerViewAdapter adapter;
AutoFitGridLayoutManager layoutManager;
private static List<JsonURLFullModel> cart;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView= inflater.inflate(R.layout.fragment_third, container, false);
recyclerView = (RecyclerView) rootView.findViewById(R.id.recyclerView);
new JSONTask().execute(url, this);
// Inflate the layout for this fragment
return rootView;
}
public class JSONTask extends AsyncTask<Object, String, ThirdFragModel> {
// Url , , return_value_of_doInBackground
//private ProgressDialog dialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
//dialog.show(); // this is for ProgressDialog
}
#Override
protected ThirdFragModel doInBackground(Object... params) {
//send and receive data over the web
// can be used to send and receive "streaming" data whose length is not
// known in advance
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0].toString());
RecyclerViewAdapter.ItemListener itemListener = (RecyclerViewAdapter.ItemListener) params[1];
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream(); // this is used to store
// the response, response is always stream
reader = new BufferedReader(new InputStreamReader(stream));
// BufferedReader reads the stream line by line and then store in the reader
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String finalJson = buffer.toString(); // this contails whole JSON data from the URL
JSONObject parentObject = new JSONObject(finalJson);
JSONArray parentArray = parentObject.getJSONArray("movies"); // "movies" is the JSON Array-object in JSON data URL
List<JsonURLFullModel> movieModelList = new ArrayList<>();
//StringBuffer finalBufferedaData = new StringBuffer();
for (int i = 0; i < parentArray.length(); i++) {
JSONObject finalObject = parentArray.getJSONObject(i); // getting first json object from JSON ARRAY "movies"
JsonURLFullModel movieModel = new JsonURLFullModel();
movieModel.setMovie(finalObject.getString("movie"));
movieModel.setImage(finalObject.getString("image"));
movieModelList.add(movieModel); // adding the final object in list
//finalBufferedaData.append(movieName +"-"+ year +"\n");
}
ThirdFragModel thirdFragModel= new ThirdFragModel(itemListener,movieModelList);
return thirdFragModel;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
if (connection != null)
connection.disconnect();
try {
if (reader != null)
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(ThirdFragModel result) {
super.onPostExecute(result);
//jsonfull.setText(result);
//dialog.dismiss(); // closing dialog, before the content load in ListView(i.e until application lodading it will run, then dialog closes)
adapter = new RecyclerViewAdapter(getActivity(), result.getMovieModelList(), result.getItemListener());
/**
AutoFitGridLayoutManager that auto fits the cells by the column width defined.
**/
layoutManager = new AutoFitGridLayoutManager(getActivity(), 500);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(adapter);
/**
Simple GridLayoutManager that spans two columns
**/
/*GridLayoutManager manager = new GridLayoutManager(this, 2, GridLayoutManager.VERTICAL, false);
recyclerView.setLayoutManager(manager);*/
//AnimationUtils.animate(jsonFullL1, true);
}
}
public void moveToLoginActivity() {
Intent intent = new Intent(getActivity(), LoginActivity.class);
startActivity(intent);
}
#Override
public void onItemClick(int mPosition,List<JsonURLFullModel> mValues ) {
Log.d("Fragposition",mPosition+":"+mValues);
Toast.makeText(getActivity(), mValues.get(mPosition).getMovie() + " is clicked", Toast.LENGTH_SHORT).show();
//Intent intent = new Intent(getActivity(), FullScreenViewActivity.class);
Intent intent = new Intent(getActivity(), FullScreenViewInitialActivity.class);
intent.putExtra("position", mPosition);
intent.putExtra("values", (Serializable) mValues);
startActivity(intent);
}
public static List<JsonURLFullModel> getCart() {
if(cart == null) {
cart = new Vector<JsonURLFullModel>();
}
return cart;
}
}
Here is my adapter class which we used in ThirdFragment class as shown above
RecyclerViewAdapter.java
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> {
static List<JsonURLFullModel> mValues;
Context mContext;
private ItemListener mListener;
static int mPosition;
public RecyclerViewAdapter(Context context, List<JsonURLFullModel> values, ItemListener itemListener) {
mValues = values;
mContext = context;
mListener=itemListener;
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public TextView textView;
public ImageView imageView;
public RelativeLayout relativeLayout;
JsonURLFullModel item;
public ViewHolder(View v) {
super(v);
v.setOnClickListener(this);
textView = (TextView) v.findViewById(R.id.textView1);
imageView = (ImageView) v.findViewById(R.id.imageView1);
relativeLayout = (RelativeLayout) v.findViewById(R.id.relativeLayout);
}
public void setData(final JsonURLFullModel item) {
this.item = item;
Log.d("INFO",item.getImage());
//https://futurestud.io/tutorials/picasso-image-resizing-scaling-and-fit
Picasso.with(mContext)
.load(item.getImage())
.error(R.drawable.ferrari)
.noPlaceholder()
.noFade()
.fit()
.into(imageView, new com.squareup.picasso.Callback() {
#Override
public void onSuccess() {
//Success image already loaded into the view
Log.d("INFO","success");
}
#Override
public void onError() {
//Error placeholder image already loaded into the view, do further handling of this situation here
Log.d("INFO","error");
}
});
/*imageView.post(new Runnable() {
#Override
public void run(){
Glide.with(mContext).load(item.getImage()).asBitmap().override(1080, 600).into(imageView);
}
});*/
textView.setText(item.getMovie());
}
#Override
public void onClick(View view) {
if (mListener != null) {
mListener.onItemClick(getAdapterPosition(),mValues); // this.getPosition() is depricated
// in API 22 and we got getAdapterPosition()
}
}
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(mContext).inflate(R.layout.recycler_view_item, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(ViewHolder Vholder, int position) {
Vholder.setData(mValues.get(position));
mPosition=position;
}
#Override
public int getItemCount() {
return mValues.size();
}
//Below interface implimentation can be found in ThirdFragment
// you can write below interface separetly or in you can write in this class like below
public interface ItemListener {
void onItemClick(int mPosition, List<JsonURLFullModel> mValues);
}
}
FullScreenViewInitialActivity.java
public class FullScreenViewInitialActivity extends FragmentActivity {
ImageFragmentPagerAdapter imageFragmentPagerAdapter;
ViewPager viewPager;
static ArrayList<JsonURLFullModel> mValues;
static int position;
Button addToBagButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fullscreen_view_initial);
addToBagButton = (Button) findViewById(R.id.b_add_to_bag);
Intent i = getIntent();
position=i.getIntExtra("position",0);
Log.d("Acposition",""+position);
mValues = (ArrayList<JsonURLFullModel>) getIntent().getSerializableExtra("values");
imageFragmentPagerAdapter = new ImageFragmentPagerAdapter(getSupportFragmentManager());
viewPager = (ViewPager) findViewById(R.id.intial_pager);
viewPager.setAdapter(imageFragmentPagerAdapter);
viewPager.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
CircleIndicator circleIndicator = (CircleIndicator) findViewById(R.id.imageIndicator);
circleIndicator.setViewPager(viewPager);
/*viewPager.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
Intent intent = new Intent(FullScreenViewInitialActivity.this, FullScreenViewActivity.class);
intent.putExtra("position", position);
intent.putExtra("values", (Serializable) mValues);
startActivity(intent);
}
});*/
final List<JsonURLFullModel> cart = ThirdFragment.getCart();
final JsonURLFullModel selectedProduct = mValues.get(position);
addToBagButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
cart.add(selectedProduct);
Log.d("cart",""+cart.size());
//finish();
Button b_add_to_bag = (Button) findViewById(R.id.b_add_to_bag);
b_add_to_bag.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent reviewOrderIntent = new Intent(FullScreenViewInitialActivity.this, FullScreenViewReviewActivity.class);
startActivity(reviewOrderIntent);
}
});
}
});
if(cart.contains(selectedProduct)) {
addToBagButton.setEnabled(false);
addToBagButton.setText("Item in Cart");
}
}
public static class ImageFragmentPagerAdapter extends FragmentPagerAdapter {
public ImageFragmentPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public int getCount() {
return mValues.size();
}
#Override
public Fragment getItem(int position) {
SwipeFragment fragment = new SwipeFragment();
return SwipeFragment.newInstance(position);
}
}
public static class SwipeFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View swipeView = inflater.inflate(R.layout.swipe_fragment, container, false);
ImageView imageView = (ImageView) swipeView.findViewById(R.id.imageView);
/*Bundle bundle = getArguments();
int position = bundle.getInt("position");*/
//JsonURLFullModel imageFileName = mValues.get(position);
try {
BitmapFactory.Options options = new BitmapFactory.Options();
/*options.inJustDecodeBounds = true;
options.inPreferredConfig = Bitmap.Config.ARGB_8888;*/
URL url = new URL(mValues.get(position).getImage());
Log.d("position",""+position);
Bitmap bitmap = BitmapFactory.decodeStream(url.openConnection().getInputStream(),null, options);
if (bitmap != null)
imageView.setImageBitmap(bitmap);
else
System.out.println("The Bitmap is NULL");
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getActivity(), mValues.get(position).getMovie(), Toast.LENGTH_SHORT).show();
}
});
return swipeView;
}
static SwipeFragment newInstance(int position) {
SwipeFragment swipeFragment = new SwipeFragment();
Bundle bundle = new Bundle();
bundle.putInt("position", position);
swipeFragment.setArguments(bundle);
return swipeFragment;
}
}
}
third_fragment.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout 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"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:fitsSystemWindows="true"
tools:context=".MainActivity">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.RecyclerView
android:id="#+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="vertical"
/>
<!--removed from recycler view
app:layout_behavior="#string/appbar_scrolling_view_behavior"-->
</RelativeLayout>
</android.support.design.widget.CoordinatorLayout>
recycler_view_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<android.support.v7.widget.CardView
android:id="#+id/cardView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/colorAccent"
card_view:cardCornerRadius="#dimen/margin10"
card_view:cardElevation="#dimen/margin10"
card_view:cardMaxElevation="#dimen/margin10"
card_view:contentPadding="#dimen/margin10"
card_view:cardPreventCornerOverlap="false"
android:layout_marginStart="10dp"
android:layout_marginEnd="10dp">
<RelativeLayout
android:id="#+id/relativeLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:layout_gravity="center">
<ImageView
android:id="#+id/imageView1"
android:layout_width="match_parent"
android:layout_height="150dp"
android:scaleType="fitXY"
android:padding="5dp"
android:layout_alignParentTop="true"/>
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:textColor="#color/colorPrimary"
android:layout_marginTop="10dp"
android:layout_below="#+id/imageView1" />
</RelativeLayout>
</android.support.v7.widget.CardView>
</LinearLayout>
activity_fullscreen_view_initial
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:layout_alignParentTop="true"
android:orientation="vertical">
<ScrollView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:fillViewport="true"
android:layout_weight="1">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_above="#+id/cart_button_layout"
android:layout_alignParentTop="true"
android:orientation="vertical">
<android.support.v4.view.ViewPager
android:id="#+id/intial_pager"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
<me.relex.circleindicator.CircleIndicator
android:id="#+id/imageIndicator"
android:layout_width="match_parent"
android:layout_height="48dp"
android:layout_alignBottom="#+id/intial_pager"
android:layout_marginBottom="10dp" />
</LinearLayout>
</ScrollView>
<ScrollView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:fillViewport="true"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<include
layout="#layout/full_screen_size_picker"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
</ScrollView>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/cart_button_layout"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:gravity="bottom"
android:paddingLeft="5dp"
android:paddingRight="5dp"
android:layout_alignParentBottom="true"
android:orientation="horizontal">
<Button
android:id="#+id/b_save"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="5dp"
android:layout_weight="1"
android:background="#D3D3D3"
android:text="save"
android:textColor="#000000" />
<Button
android:id="#+id/b_add_to_bag"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:layout_weight="1"
android:background="#color/colorPrimary"
android:text="add to bag"
android:textColor="#FFF" />
</LinearLayout>
</LinearLayout>
swipe_fragment.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/imageView"
android:layout_gravity="center_horizontal"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
</LinearLayout>
Try setting the setting the RecyclerView with an empty Adapter before you execute your AsyncTask.
View rootView= inflater.inflate(R.layout.fragment_third, container, false);
recyclerView = (RecyclerView) rootView.findViewById(R.id.recyclerView);
-->recyclerView.setAdapter(new RecyclerViewAdapter(getActivity(), new ArrayList<>(), null);
new JSONTask().execute(url, this);
Then create a method in the RecyclerViewAapter to load the the populated List<JsonURLFullModel> from the AsyncTask's onPostExecute.
public void loadJson(List<JsonURLFullModel> jsonList){
mValues = jsonList;
notifyDataSetChanged();
}
If that doesn't work trying loading on the Ui thread from Asynctask using runOnUiThread
runOnUiThread(new Runnable() {
#Override
public void run() {
adapter.loadJson(...)
}
});
Edit 1 Adding loadJson to your RecyclerViewAapter.class
#Override
public int getItemCount() {
return mValues.size();
}
public void loadJson(List<JsonURLFullModel> jsonList){
mValues = jsonList;
notifyDataSetChanged();
}
//Below interface implimentation can be found in ThirdFragment
// you can write below interface separetly or in you can write in this class like below
public interface ItemListener {
void onItemClick(int mPosition, List<JsonURLFullModel> mValues);
}
Call the method in your PostExecute
#Override
protected void onPostExecute(ThirdFragModel result) {
super.onPostExecute(result);
//jsonfull.setText(result);
//dialog.dismiss(); // closing dialog, before the content load in ListView(i.e until application lodading it will run, then dialog closes)
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
adapter.loadJson(result.getMovieModelList());
}
});
}
Also add your the Layout manager for the RecyclerView in onCreateView
View rootView= inflater.inflate(R.layout.fragment_third, container, false);
recyclerView = (RecyclerView) rootView.findViewById(R.id.recyclerView);
-->recyclerView.setAdapter(new RecyclerViewAdapter(getActivity(), new ArrayList<>(), null);
layoutManager = new AutoFitGridLayoutManager(getActivity(), 500);
recyclerView.setLayoutManager(layoutManager);
Just started learning android. Help please. I have three fragments, each has a button that must run one of the streams of the media player. How can I find the button of my activity in the fragment that would later attach to it a specific stream?
Tried to make a reference to the button so that:
btnStart = (Button) titleAdapter.frags[0].getView().findViewById(R.id.btnStart);
Did not work, an error java.lang.NullPointerException, what I'm doing wrong
public class TitleAdapter extends FragmentPagerAdapter {
private final String titles[] = new String[] { "FragA", "FragB", "FragC" };
private final Fragment frags[] = new Fragment[titles.length];
public TitleAdapter(FragmentManager fm) {
super(fm);
frags[0] = new FragmentA();
frags[1] = new FragmentB();
frags[2] = new FragmentC();
}
#Override
public CharSequence getPageTitle(int position) {
Log.v("TitleAdapter - getPageTitle=", titles[position]);
return titles[position];
}
#Override
public Fragment getItem(int position) {
Log.v("TitleAdapter - getItem=", String.valueOf(position));
return frags[position];
}
#Override
public int getCount() {
return frags.length;
}
}
code MainActivity.java:
public class MainActivity extends FragmentActivity {
final static String LOG_TAG = "myLogs";
static MediaPlayer mediaPlayer;
static AudioManager am;
static CheckBox pdaStream;
static Button btnNews;
ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mViewPager = (ViewPager) findViewById(R.id.pager);
TitleAdapter titleAdapter = new TitleAdapter(getSupportFragmentManager());
mViewPager.setAdapter(titleAdapter);
mViewPager.setCurrentItem(1);
mViewPager.setOffscreenPageLimit(2);
pdaStream = (CheckBox) findViewById(R.id.pdaStream);
am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
SeekBar music = (SeekBar)findViewById(R.id.seekBar1);
initBar(music, AudioManager.STREAM_MUSIC);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.news:
Intent intent = new Intent(this, RSSActivity.class);
startActivity(intent);
break;
default:
break;
}
return super.onOptionsItemSelected(item);
}
public static void initBar(SeekBar bar, final int stream) {
bar.setMax(am.getStreamMaxVolume(stream));
bar.setProgress(am.getStreamVolume(stream));
bar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
public void onProgressChanged(SeekBar bar, int progress,
boolean fromUser) {
am.setStreamVolume(stream, progress,
AudioManager.FLAG_PLAY_SOUND);
}
public void onStartTrackingTouch(SeekBar bar) {
// no-op
}
public void onStopTrackingTouch(SeekBar bar) {
// no-op
}
});
}
}
code fragments similar, here's one of them
code FragmentA.java:
public class FragmentA extends Fragment {
final static String LOG_TAG = "myLogs";
private static ProgressBar progressBar;
static CheckBox pdaStream;
public FragmentA() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_a, container, false);
final Button Play = (Button) rootView.findViewById(R.id.btnStart);
progressBar = (ProgressBar) rootView.findViewById(R.id.progressBar);
progressBar.setVisibility(View.GONE);
pdaStream = (CheckBox) getActivity().findViewById(R.id.pdaStream);
return rootView;
} }
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/RelativeLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/background"
tools:context=".MainActivity" >
<android.support.v4.view.PagerTabStrip
android:id="#+id/pager_title_strip"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="top"
android:background="#drawable/bg_pager"
android:paddingBottom="4dp"
android:paddingTop="4dp"
android:textColor="#fff" />
</android.support.v4.view.ViewPager>
<SeekBar
android:id="#+id/seekBar1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_marginBottom="60dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:thumb="#drawable/seek" />
<CheckBox
android:id="#+id/pdaStream"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_marginBottom="10dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="70dp"
android:text="#string/chkbox" />
</RelativeLayout>
fragment_a.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/RelativeLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Button
android:id="#+id/btnStart"
android:layout_width="70dp"
android:layout_height="70dp"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:textSize="16sp"
android:onClick="onClick"
android:background="#drawable/play_button"/>
<ProgressBar
android:id="#+id/progressBar"
style="?android:attr/progressBarStyleLarge"
android:layout_width="150dp"
android:layout_height="150dp"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true" />
</RelativeLayout>
public static Fragment getCurrentFragment(ViewPager pager, FragmentPagerAdapter adapter) {
try {
Method m = adapter.getClass().getSuperclass().getDeclaredMethod("makeFragmentName", int.class, long.class);
Field f = adapter.getClass().getSuperclass().getDeclaredField("mFragmentManager");
f.setAccessible(true);
FragmentManager fm = (FragmentManager) f.get(adapter);
m.setAccessible(true);
String tag = null;
tag = (String) m.invoke(null, pager.getId(), (long) pager.getCurrentItem());
return fm.findFragmentByTag(tag);
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (NoSuchFieldException e) {
e.printStackTrace();
}
return null;
}
Then put a public getter for button in FragmentA.java,
public Button getPlayButton()
{
return Play;
}
in your Fragment activity,
Fragment currenFragment = getCurrentFragmet(mViewPager,titleAdapter);
if(currenFragment!=null){
// cast the fragment to FragmentA class, then call getter
((FragmentA)currentFragment).getPlayButton();
}
use following code in onActivityCreated() of fragment
btnStart = (Button) getView().findViewById(R.id.btnStart);
I am trying to add the same class several times to a viewpager to show different info which is read from a sqlite DB. The thing is when the view is created, always override the objects, textviews etc..., in the current view and not in the fragment for each page.
names = new ArrayList<String>();
for (int d : descritions) {
Description temp = DBCompanies.getDescriptionById(db_path,
GSSettings.DBCODE, d, Locale.getDefault().getLanguage(),
GSSettings.DEFAULTLANGUAGE, false);
names.add(temp.getTitle());
}
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
// mViewPager.setCurrentItem(0);
mViewPager.refreshDrawableState();
...
How can I avoid this behavior?
thanks.
EDIT:
I added more code to clarify my question:
framecompany100.xml
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/ly_main"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:scrollbarDefaultDelayBeforeFade="500"
android:scrollbarFadeDuration="200"
android:scrollbarThumbVertical="#drawable/scrollbar_vertical_thumb_company" >
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<Gallery
android:id="#+id/ga_image"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_margin="2dp" />
<RelativeLayout
android:id="#+id/ly_details"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/ga_image" >
<ImageView
android:id="#+id/iv_options"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_margin="5dp"
android:src="#drawable/ic_button_options" />
<RelativeLayout
android:id="#+id/ly_details_text"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_marginRight="5dp"
android:layout_toRightOf="#+id/iv_options"
android:background="#77ffffff" >
<TextView
android:id="#+id/tv_address" android:text="kldfjhskdjhfksj"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:textSize="15sp" />
</RelativeLayout>
</RelativeLayout>
<TextView
android:id="#+id/tv_description"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/ly_details"
android:layout_marginLeft="10dp"
android:layout_marginTop="5dp"
android:textSize="15sp"
android:textStyle="bold" />
</RelativeLayout>
and the class for this layout:
FrameCompany100.java
public class FrameCompany100 extends Fragment implements OnClickListener,
PictureUpdater, FragmentName {
private Bundle data = new Bundle();
private Gallery image;
private Description description;
private BaseAdapter adapter;
private String db_path;
private GuiParams main_params;
private Company company;
private String name = "";
#Override
public void onCreate(Bundle savedInstanceState) {
data = this.getArguments();
if (savedInstanceState != null)
data = savedInstanceState;
db_path = "/data/data/" + getActivity().getPackageName()
+ GSSettings.DB_PATH;
description = DBCompanies.getDescriptionById(db_path,
GSSettings.DBCODE, data.getInt("descriptionId"), Locale
.getDefault().getLanguage(), "es", false);
company = DBCompanies.getCompany(db_path, GSSettings.DBCODE,
description.getCompanyId());
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.framecompany100, container, false);
}
void init() {
try {
Display display = getActivity().getWindowManager()
.getDefaultDisplay();
int height = display.getHeight();
final int width = display.getWidth();
// params
main_params = DBCompanies.getGuiParams(db_path, GSSettings.DBCODE,
description.getCompanyId(), GSSettings.body);
if (main_params == null || main_params.getBackgroundcolor() == null
|| main_params.getBackgroundcolor().equals("")
|| main_params.getTextcolor() == null
|| main_params.getTextcolor().equals(""))
main_params = DBApp.getGuiParam(db_path, GSSettings.DBCODE,
GSSettings.body);
// main Layout
RelativeLayout ly_main = (RelativeLayout) getActivity()
.findViewById(R.id.ly_main);
try {
ly_main.setBackgroundColor(Color.parseColor(main_params
.getBackgroundcolor()));
} catch (Exception e) {
}
Typeface font_body = null;
try {
font_body = Typeface.createFromAsset(getActivity().getAssets(),
"fonts/" + main_params.getFont());
} catch (Exception e) {
font_body = Typeface.createFromAsset(
getActivity().getAssets(),
"fonts/"
+ DBApp.getGuiParam(db_path, GSSettings.DBCODE,
GSSettings.body).getFont());
}
TextView tv_description = (TextView) getActivity().findViewById(
R.id.tv_description);
try {
tv_description.setTextColor(Color.parseColor(main_params
.getTextcolor()));
} catch (Exception e) {
}
if (description == null) {
tv_description.setText(R.string.nodescription);
} else {
tv_description.setText(description.getText());
}
TextView tv_address = (TextView) getActivity().findViewById(
R.id.tv_address);
try {
tv_address.setTextColor(Color.parseColor(main_params
.getTextcolor()));
} catch (Exception e) {
}
.....
}
#Override
public void onResume() {
init();
// ((MainLayout) getActivity()).setDescription(description);
super.onResume();
}
the FragmentPagerAdapter
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int i) {
Description temp = DBCompanies.getDescriptionById(db_path,
GSSettings.DBCODE, descritions[i], Locale.getDefault()
.getLanguage(), GSSettings.DEFAULTLANGUAGE, false);
Fragment fragment = null;
try {
fragment = new CompanyLayout100();
((FragmentName) fragment).setName(temp.getTitle());
Bundle bundle = new Bundle();
bundle.putInt("descriptionId", temp.getId());
fragment.setArguments(bundle);
} catch (Exception e) {
}
return fragment;
}
#Override
public int getCount() {
return descritions.length;
// return fragments.size();
}
#Override
public CharSequence getPageTitle(int position) {
String name = "";
try {
name = names.get(position);
} catch (Exception e) {
}
return name;
}
}
what's happening is, the viewpager create the view for these frames but always is entering the data in the visible frame. I think is because the layout.xml is the same so there is only one id and all object are pointing at the visible layout.
You need a FragmentPagerAdapter that creates the instance ...
public class PagerAdapter extends FragmentPagerAdapter {
int pages;
public PagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public int getCount() {
return pages;
}
#Override
public Fragment getItem(int position) {
return MyFragment.newInstance(position);
}
public void setPages(int no) {
pages = no;
}
}
So in the main activity you attach the PagerAdapter ...
adapter = new PagerAdapter(getSupportFragmentManager());
adapter.setPages(noPages);
pager.setAdapter(adapter);
Finally you need your Fragment including the newInstance method. Check out this http://android-developers.blogspot.de/2011/08/horizontal-view-swiping-with-viewpager.html for more.
Cheers!
Edit #1: MyFragment; note: it is essential to pass the position as an argument
public class MyFragment extends SherlockFragment {
private static final String KEY_POSITION="position";
static MyFragment newInstance(int position) {
MyFragment frag=new MyFragment();
Bundle args=new Bundle();
args.putInt(KEY_POSITION, position);
frag.setArguments(args);
return(frag);
}
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState) {
View result=inflater.inflate(R.layout.editor, container, false);
EditText editor=(EditText)result.findViewById(R.id.editor);
int position=getArguments().getInt(KEY_POSITION, -1);
editor.setHint(String.format(getString(R.string.hint), position + 1));
return(result);
}
}
I've been trying to show on my main fragmentActivity a tabHost which contains a ListView.
However my listView doesn't appear at all. the elements are uploading but the view isn't showing them.
The fragment which show the tabHost
public class GestionListeNote extends Fragment implements OnTabChangeListener {
private static final String TAG = "FragmentTabs";
public static final String TAB_ALL = "All";
public static final String TAB_TOPAY = "To Pay";
public static final String TAB_PAID = "Paid";
public static final String TAB_SEND = "Send";
private View mRoot;
private TabHost mTabHost;
private int mCurrentTab;
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mRoot = inflater.inflate(R.layout.tabs_fragment, null);
mTabHost = (TabHost) mRoot.findViewById(android.R.id.tabhost);
setupTabs();
return mRoot;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setRetainInstance(true);
mTabHost.setOnTabChangedListener(this);
mTabHost.setCurrentTab(mCurrentTab);
// manually start loading stuff in the first tab
updateTab(TAB_ALL, R.id.tab_1);
}
private void setupTabs() {
mTabHost.setup(); // important!
mTabHost.addTab(newTab(TAB_ALL, R.string.allNotes, R.id.tab_1));
mTabHost.addTab(newTab(TAB_TOPAY, R.string.notesToPay, R.id.tab_2));
mTabHost.addTab(newTab(TAB_PAID, R.string.notesPaid, R.id.tab_3));
mTabHost.addTab(newTab(TAB_SEND, R.string.notesSend, R.id.tab_4));
}
private TabSpec newTab(String tag, int labelId, int tabContentId) {
Log.d(TAG, "buildTab(): tag=" + tag);
View indicator = LayoutInflater.from(getActivity()).inflate(
R.layout.tab,
(ViewGroup) mRoot.findViewById(android.R.id.tabs), false);
((TextView) indicator.findViewById(R.id.text)).setText(labelId);
TabSpec tabSpec = mTabHost.newTabSpec(tag);
tabSpec.setIndicator(indicator);
tabSpec.setContent(tabContentId);
return tabSpec;
}
#Override
public void onTabChanged(String tabId) {
Log.d(TAG, "onTabChanged(): tabId=" + tabId);
if (TAB_ALL.equals(tabId)) {
updateTab(tabId, R.id.tab_1);
mCurrentTab = 0;
Log.d(TAG, "current tab=" + mCurrentTab);
return;
}
if (TAB_TOPAY.equals(tabId)) {
updateTab(tabId, R.id.tab_2);
mCurrentTab = 1;
Log.d(TAG, "current tab=" + mCurrentTab);
return;
}
if (TAB_PAID.equals(tabId)) {
updateTab(tabId, R.id.tab_3);
mCurrentTab = 2;
Log.d(TAG, "current tab=" + mCurrentTab);
return;
}
if (TAB_SEND.equals(tabId)) {
updateTab(tabId, R.id.tab_4);
mCurrentTab = 3;
Log.d(TAG, "current tab=" + mCurrentTab);
return;
}
}
private void updateTab(String tabId, int placeholder) {
FragmentManager fm = getFragmentManager();
if (fm.findFragmentByTag(tabId) == null) {
fm.beginTransaction()
.replace(placeholder, new ListeNotesFragment(tabId), tabId)
.commit();
}
}
That's my ListFragment who show my elements
public class ListeNotesFragment extends ListFragment implements
LoaderCallbacks<Void> {
private static final String TAG = "FragmentTabs";
private String mTag;
private MyAdapter mAdapter;
private ArrayList<String> mItems;
private LayoutInflater mInflater;
private int mTotal;
private int mPosition;
private static final String[] All = { "Lorem", "ipsum", "dolor", "sit",
"amet", "consectetur", "adipiscing", "elit", "Fusce", "pharetra",
"luctus", "sodales" };
private static final String[] ToPay = { "I", "II", "III", "IV", "V",
"VI", "VII", "VIII", "IX", "X", "XI", "XII", "XIII", "XIV", "XV" };
private static final String[] Paid = { "Test" };
private static final String[] Send = { "Test" };
private static final int SLEEP = 1000;
private final int allBarColor = R.color.all_bar;
private final int topayBarColor = R.color.topay_bar;
private final int paidBarColor = R.color.paid_bar;
private final int sendBarColor = R.color.send_bar;
public ListeNotesFragment() {
}
public ListeNotesFragment(String tag) {
mTag = tag;
mTotal = GestionListeNote.TAB_ALL.equals(mTag) ? All.length
: (GestionListeNote.TAB_TOPAY.equals(mTag) ? ToPay.length
: (GestionListeNote.TAB_PAID.equals(mTag) ? Paid.length
: Send.length ) );
Log.d(TAG, "mTotal =" + mTotal);
Log.d(TAG, "Constructor: tag=" + tag);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// this is really important in order to save the state across screen
// configuration changes for example
setRetainInstance(true);
mInflater = LayoutInflater.from(getActivity());
// you only need to instantiate these the first time your fragment is
// created; then, the method above will do the rest
if (mAdapter == null) {
mItems = new ArrayList<String>();
mAdapter = new MyAdapter(getActivity(), mItems);
}
getListView().setAdapter(mAdapter);
// initiate the loader to do the background work
getLoaderManager().initLoader(0, null, this);
}
#Override
public Loader<Void> onCreateLoader(int id, Bundle args) {
AsyncTaskLoader<Void> loader = new AsyncTaskLoader<Void>(getActivity()) {
#Override
public Void loadInBackground() {
try {
// simulate some time consuming operation going on in the
// background
Thread.sleep(SLEEP);
} catch (InterruptedException e) {
}
return null;
}
};
// somehow the AsyncTaskLoader doesn't want to start its job without
// calling this method
loader.forceLoad();
Log.d(TAG, "Stop sleep");
return loader;
}
#Override
public void onLoadFinished(Loader<Void> loader, Void result) {
// add the new item and let the adapter know in order to refresh the
// views
mItems.add(GestionListeNote.TAB_ALL.equals(mTag) ? All[mPosition]
: (GestionListeNote.TAB_TOPAY.equals(mTag) ? ToPay[mPosition]
: (GestionListeNote.TAB_PAID.equals(mTag) ? Paid[mPosition]
: Send[mPosition]) ) );
mAdapter.notifyDataSetChanged();
Log.d(TAG, "item =" + mItems.get(mPosition));
// advance in your list with one step
mPosition++;
if (mPosition < mTotal - 1) {
getLoaderManager().restartLoader(0, null, this);
Log.d(TAG, "onLoadFinished(): loading next...");
} else {
Log.d(TAG, "onLoadFinished(): done loading!");
}
}
#Override
public void onLoaderReset(Loader<Void> loader) {
}
private class MyAdapter extends ArrayAdapter<String> {
public MyAdapter(Context context, List<String> objects) {
super(context, R.layout.list_item, R.id.text, objects);
Log.d(TAG, "affiche contenu");
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
Wrapper wrapper;
Log.d(TAG, "affiche vue");
if (view == null) {
view = mInflater.inflate(R.layout.list_item, null);
wrapper = new Wrapper(view);
view.setTag(wrapper);
} else {
wrapper = (Wrapper) view.getTag();
}
wrapper.getTextView().setText(getItem(position));
wrapper.getBar().setBackgroundColor(
GestionListeNote.TAB_ALL.equals(mTag) ? getResources().getColor(allBarColor)
: (GestionListeNote.TAB_TOPAY.equals(mTag) ? getResources().getColor(topayBarColor)
: (GestionListeNote.TAB_PAID.equals(mTag) ? getResources().getColor(paidBarColor)
:getResources().getColor(sendBarColor)) ) );
return view;
}
}
// use an wrapper (or view holder) object to limit calling the
// findViewById() method, which parses the entire structure of your
// XML in search for the ID of your view
private class Wrapper {
private final View mRoot;
private TextView mText;
private View mBar;
public Wrapper(View root) {
mRoot = root;
Log.d(TAG, "initialise view");
}
public TextView getTextView() {
if (mText == null) {
mText = (TextView) mRoot.findViewById(R.id.text);
Log.d(TAG, "initialise TextView");
}
Log.d(TAG, "initialise view");
return mText;
}
public View getBar() {
if (mBar == null) {
mBar = mRoot.findViewById(R.id.bar);
Log.d(TAG, "initialise view");
}
Log.d(TAG, "initialise view");
return mBar;
}
}
below the xml
main
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<fragment
android:layout_width="match_parent"
android:layout_height="wrap_content"
class="org.newnote.android.AddNoteButton" />
<fragment
android:id="#+id/tabs_fragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
class="org.newnote.android.GestionListeNote" />
liste_item
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="#dimen/list_item_height"
android:gravity="left|center_vertical">
<View
android:id="#+id/bar"
android:layout_width="10dp"
android:layout_height="fill_parent" />
<TextView
android:id="#+id/text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingLeft="10dp"
android:gravity="center" />
tabs_fragment
<TabHost xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#android:id/tabhost"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#EFEFEF" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TabWidget
android:id="#android:id/tabs"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<FrameLayout
android:id="#android:id/tabcontent"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<FrameLayout
android:id="#+id/tab_1"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
<FrameLayout
android:id="#+id/tab_2"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
<FrameLayout
android:id="#+id/tab_3"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
<FrameLayout
android:id="#+id/tab_4"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</FrameLayout>
</LinearLayout>
Tab
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="80dp"
android:layout_height="#dimen/tab_height"
android:gravity="center"
android:padding="#dimen/tab_padding"
android:background="#drawable/tab_selector">
<TextView
android:id="#+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:textSize="#dimen/text_small"
android:textStyle="bold"
android:textColor="#drawable/tab_text_selector" />
I don't understand why my fragment doesn't show the elements
Hope you could help me.
You appear to be missing onCreateView for your ListFragment