I am using fragNav and bottombar plugin. I am trying to make a fullscreen fragment through a FrameLayout. By default, those plugins came with an actionBar which i delete in my theme with "Theme.AppCompat.Light.NoActionBar". But Once i did this there is still a white bar on top on my screen. When i look at hierarchyView it appears that my FrameLayout is not matching the parent but all my xml are setup with match_parent width and height..
MainActivity.java
public class MainActivity extends AppCompatActivity {
private BottomBar mBottomBar;
private FragNavController fragNavController;
private final int TAB_FIRST = FragNavController.TAB1;
private final int TAB_SECOND = FragNavController.TAB2;
private final int TAB_THIRD = FragNavController.TAB3;
private final int TAB_FOURTH = FragNavController.TAB4;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
List<Fragment> fragments = new ArrayList<>(4);
fragments.add(FirstFragment.newInstance(0));
fragments.add(SecondFragment.newInstance(0));
fragments.add(ThirdFragment.newInstance(0));
fragments.add(FourthFragment.newInstance(0));
fragNavController = new FragNavController(getSupportFragmentManager(), R.id.container, fragments);
//BottomBar menu
mBottomBar = BottomBar.attach(this, savedInstanceState);
mBottomBar.setItems(R.menu.bottombar_menu);
mBottomBar.setOnMenuTabClickListener(new OnMenuTabClickListener() {
#Override
public void onMenuTabSelected(#IdRes int menuItemId) {
//switch between tabs
switch (menuItemId) {
case R.id.bottomBarItemOne:
fragNavController.switchTab(TAB_FIRST);
break;
case R.id.bottomBarItemSecond:
fragNavController.switchTab(TAB_SECOND);
break;
case R.id.bottomBarItemThird:
fragNavController.switchTab(TAB_THIRD);
break;
case R.id.bottomBarItemFourth:
fragNavController.switchTab(TAB_FOURTH);
break;
}
}
#Override
public void onMenuTabReSelected(#IdRes int menuItemId) {
if (menuItemId == R.id.bottomBarItemOne) {
fragNavController.clearStack();
}
}
});
}
#Override
public void onBackPressed () {
if (fragNavController.getCurrentStack().size() > 1) {
fragNavController.pop();
} else {
super.onBackPressed();
}
}
#Override
protected void onSaveInstanceState (Bundle outState){
super.onSaveInstanceState(outState);
// Necessary to restore the BottomBar's state, otherwise we would
// lose the current tab on orientation change.
mBottomBar.onSaveInstanceState(outState);
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:id="#+id/container"
android:background="#color/black">
</FrameLayout>
FirstFragment.java
public class FirstFragment extends Fragment {
public class SwipeDeckAdapter extends BaseAdapter {
private List<String> data;
private Context context;
public SwipeDeckAdapter(List<String> data, Context context) {
this.data = data;
this.context = context;
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int position) {
return data.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View v = convertView;
if(v == null){
LayoutInflater inflater = getActivity().getLayoutInflater();
// normally use a viewholder
v = inflater.inflate(R.layout.card_view, parent, false);
}
((TextView) v.findViewById(R.id.textView2)).setText(data.get(position));
v.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String item = (String)getItem(position);
Log.i("MainActivity", item);
}
});
return v;
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_home,container,false);
final SwipeDeck cardStack = (SwipeDeck) view.findViewById(R.id.swipe_deck);
cardStack.setHardwareAccelerationEnabled(true);
Button btn = (Button) view.findViewById(R.id.undobutton);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
cardStack.swipeTopCardLeft(180);
}
});
Button btn2 = (Button) view.findViewById(R.id.joinbutton);
btn2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
cardStack.swipeTopCardRight(180);
}
});
final ArrayList<String> testData = new ArrayList<>();
testData.add("0");
testData.add("1");
testData.add("2");
testData.add("3");
testData.add("4");
final SwipeDeckAdapter adapter = new SwipeDeckAdapter(testData, getActivity() );
cardStack.setAdapter(adapter);
cardStack.setEventCallback(new SwipeDeck.SwipeEventCallback() {
#Override
public void cardSwipedLeft(int position) {
Log.i("MainActivity", "card was swiped left, position in adapter: " + position);
}
#Override
public void cardSwipedRight(int position) {
Log.i("MainActivity", "card was swiped right, position in adapter: " + position);
}
#Override
public void cardsDepleted() {
Log.i("MainActivity", "no more cards");
}
#Override
public void cardActionDown() {
Log.i("MainActivity", "Down");
} ;
#Override
public void cardActionUp() {
Log.i("MainActivity", "Up");
};
});
return view;
}
public static FirstFragment newInstance(int index) {
FirstFragment f = new FirstFragment();
Bundle args = new Bundle();
args.putInt("index", index);
f.setArguments(args);
return f;
}
}
fragment_first.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:background="#color/black"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="io.MainActivity"
android:fitsSystemWindows="true">
<com.daprlabs.cardstack.SwipeLinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:swipedeck="http://schemas.android.com/apk/res-auto"
android:id="#+id/framelayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:weightSum="10">
<com.daprlabs.cardstack.SwipeDeck
android:id="#+id/swipe_deck"
android:layout_weight="8"
android:layout_width="match_parent"
android:layout_height="0dp"
swipedeck:card_spacing="0dp"
swipedeck:max_visible="3"
swipedeck:render_above="true"
swipedeck:rotation_degrees="15"
swipedeck:opacity_end="0.33">
</com.daprlabs.cardstack.SwipeDeck>
<RelativeLayout
android:id="#+id/rl"
android:layout_weight="2"
android:layout_width="match_parent"
android:layout_height="0dp">
<RelativeLayout
android:id="#+id/container"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true">
<Button
android:id="#+id/undobutton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Undo"
android:onClick="onClick"/>
<Button
android:id="#+id/joinbutton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#id/undobutton"
android:text="Join"
android:onClick="onClick"/>
</RelativeLayout>
</RelativeLayout>
</com.daprlabs.cardstack.SwipeLinearLayout>
In your parent RelativeLayout in fragment_first can you remove the android:fitsSystemWindows="true", I think that may be the cause of the issue.
Related
LogCat
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.GridView.setAdapter(android.widget.ListAdapter)' on a null object reference
at ye.ansarallah.al_ansar.HomeActivity.onCreate(HomeActivity.java:37)
HomeActivity:
public class HomeActivity extends AppCompatActivity {
Integer[] MyImageArray = {
R.drawable.w1, R.drawable.w2, R.drawable.w3
};
GridView MyGridView;
ImageView MyCurrentWallpaper;
Drawable MyDrawable;
WallpaperManager MyWallmanger;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MyGridView = findViewById(R.id.mygridview);
MyCurrentWallpaper = findViewById(R.id.myImageView);
MyGridView.setAdapter(new ImageAdapter(getApplicationContext()));
UpdateMyWallpaper();
}
private void UpdateMyWallpaper() {
MyWallmanger = WallpaperManager.getInstance(getApplicationContext());
MyDrawable = MyWallmanger.getDrawable();
MyCurrentWallpaper.setImageDrawable(MyDrawable);
}
public class ImageAdapter extends BaseAdapter {
Context myContext;
ImageAdapter(Context applicationContext) {
myContext = applicationContext;
}
#Override
public int getCount() {
return MyImageArray.length;
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(final int i, View view, ViewGroup viewGroup) {
ImageView GridImageView;
if (view == null) {
GridImageView = new ImageView(myContext);
GridImageView.setLayoutParams(new GridView.LayoutParams(512, 512));
GridImageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
} else {
GridImageView = (ImageView) view;
}
GridImageView.setImageResource(MyImageArray[i]);
GridImageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
MyWallmanger.setResource(MyImageArray[i]);
} catch (IOException e) {
e.printStackTrace();
}
UpdateMyWallpaper();
}
});
return GridImageView;
}
}
}
activity_home.XML:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".HomeActivity">
<ImageView
android:id="#+id/myImageView"
android:layout_width="match_parent"
android:layout_height="300dp"
android:scaleType="centerCrop"
android:src="#drawable/w1" />
<GridView
android:id="#+id/mygridview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:columnWidth="100dp"
android:numColumns="auto_fit"
android:stretchMode="spacingWidth"
android:verticalSpacing="1dp" />
</LinearLayout>
MyGridView is null. It means that there is no view with id=R.id.mygridview in layout.
Maybe it is because you use setContentView(R.layout.activity_main), but provided source xml for activity_home.XML.
I've two types of Fragment in PageView. The first one is TextFragment containing TextView and having set tag on it. The other ones are ImageFragments containing ImageView and having no tag. Images are loaded asynchronously from asset folder.
The problem is that the second (and sometimes also some other) fragment does not show the content or the content appears just for a while and then disappears. When I remove/comment the line where the tag is set, everything starts to work perfectly.
Do you know how to have the fragment appear correctly even with the tag set?
Here is the code (using appcompat). Keep in mind that the tag is needed (in my app) although it's not queried here in the code.
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context="example.com.testfragment.MainActivity">
<android.support.v4.view.ViewPager
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/core_pager"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</RelativeLayout>
MainActivity.java
public class MainActivity extends AppCompatActivity {
private static final String TEXTFR_TAG = "TEXTFR_TAG";
static final String MYDATAFOLDER = "mydata";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ViewPager viewPager = (ViewPager) findViewById(R.id.core_pager);
final String[] imgs = getImages();
viewPager.setAdapter(new FragmentStatePagerAdapter(getSupportFragmentManager()) {
#Override
public int getCount() {
return imgs.length + 1;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return TextFragment.newInstance(getSupportFragmentManager(), TEXTFR_TAG);
default:
return ImageFragment.newInstance(imgs[position - 1]);
}
}
});
}
private String[] getImages() {
try {
return this.getAssets().list(MYDATAFOLDER);
} catch (IOException e) {
return new String[0];
}
}
}
fragment_text.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"
android:background="#android:color/darker_gray">
<TextView android:layout_width="match_parent" android:layout_height="match_parent"
android:id="#+id/textfragment_textview"/>
</LinearLayout>
TextFragment.java
public class TextFragment extends Fragment {
public TextFragment() {
}
static TextFragment newInstance(FragmentManager fragmentManager, String tag) {
TextFragment instance = new TextFragment();
fragmentManager
.beginTransaction()
.replace(R.id.core_pager, instance, tag) // <--- REMOVING THIS FIXES THE PROBLEM
.commit();
return instance;
}
#Override
public View onCreateView(final LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.fragment_text, container, false);
((TextView)root.findViewById(R.id.textfragment_textview)).setText("SOME TEXT");
return root;
}
}
fragment_image.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"
android:background="#android:color/white">
<ImageView android:layout_width="match_parent" android:layout_height="match_parent"
android:id="#+id/imagefragment_imageview"/>
</LinearLayout>
ImageFragment.java
public class ImageFragment extends Fragment {
private static final String ARG_IMG = "ARG_IMG";
public ImageFragment() {
}
static ImageFragment newInstance(String imagePath) {
ImageFragment instance = new ImageFragment();
Bundle args = new Bundle();
args.putString(ARG_IMG, imagePath);
instance.setArguments(args);
return instance;
}
#Override
public View onCreateView(final LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_image, container, false);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
if(view == null) {
return;
}
final Bundle args = getArguments();
final ImageView iv = (ImageView) view.findViewById(R.id.imagefragment_imageview);
new AsyncTask<Void, Void, Drawable>() {
#Override
protected Drawable doInBackground(Void... voids) {
String imgFile = args.getString(ARG_IMG);
try {
Context context = getContext().getApplicationContext();
return Drawable.createFromStream(context.getAssets().open(MainActivity.MYDATAFOLDER + '/' + imgFile), null);
} catch (Exception e) {
Log.e("MyAPP", "Error: ", e);
}
return null;
}
#Override
protected void onPostExecute(Drawable drawable) {
if(drawable != null) {
iv.setImageDrawable(drawable);
} else {
Log.d("MyAPP", "No drawable");
}
}
}.execute();
}
}
I've created a RecyclerView in Android Studio like in an other fragment. The problem is that all is working for the first look but after creating a row object and stating the app I can't see any entries. I've did this RecyclerView the the same way as my old one which works great.. I've searched a lot but I can find the error.
This is my fragment xml:
<android.support.v4.widget.SwipeRefreshLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/training_swiperefresh"
android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/trainingtTitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:layout_marginTop="0dp"
android:layout_marginBottom="16dp"
android:textStyle="bold"
android:textColor="#color/colorPrimary"
android:text="#string/trainingTitle" />
<android.support.v7.widget.RecyclerView
android:id="#+id/training_recycler_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:scrollbars="vertical"
android:layout_below="#+id/trainingtTitle" />
</RelativeLayout>
</android.support.v4.widget.SwipeRefreshLayout>
This is the row-layout for the RecyclerView:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:focusable="true"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:clickable="true"
android:background="?android:attr/selectableItemBackground"
android:orientation="vertical">
<!-- Plan icon -->
<ImageView
android:id="#+id/planImage"
android:layout_width="24dp"
android:layout_height="24dp"
android:layout_centerVertical="true"
android:layout_alignParentStart="true"
android:layout_marginRight="8dp"
android:layout_marginTop="1dp"
android:layout_marginBottom="1dp"
android:contentDescription="Icon"
android:src="#drawable/ic_menu_train" />
<!-- Plan title -->
<TextView
android:id="#+id/planTitle"
android:textColor="#color/colorBlack"
android:layout_width="match_parent"
android:layout_marginLeft="40dp"
android:layout_marginRight="40dp"
android:layout_marginTop="14dp"
android:textSize="16dp"
android:layout_height="wrap_content" />
<!-- Plan type -->
<TextView
android:id="#+id/planType"
android:layout_below="#id/planTitle"
android:layout_marginLeft="40dp"
android:layout_marginRight="40dp"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<!-- Plan date -->
<TextView
android:id="#+id/planDate"
android:layout_width="match_parent"
android:layout_below="#id/planType"
android:layout_marginLeft="42dp"
android:layout_marginRight="40dp"
android:layout_marginBottom="14dp"
android:layout_height="wrap_content" />
<!-- Plan view -->
<ImageView
android:id="#+id/planView"
android:layout_width="24dp"
android:layout_height="24dp"
android:layout_alignParentEnd="true"
android:layout_centerVertical="true"
android:layout_marginTop="1dp"
android:layout_marginBottom="1dp"
android:contentDescription="Icon"
android:src="#drawable/ic_menu_show" />
<View
android:layout_width="fill_parent"
android:layout_height="1dip"
android:layout_below="#id/planDate"
android:layout_marginLeft="42dp"
android:background="#DCDCDC" />
</RelativeLayout>
This is my Fragment where I call the Adapter:
public class TrainingFragment extends Fragment {
private OnFragmentInteractionListener mListener;
// Variables for Recycler View
private List<Plans> planList = new ArrayList<>();
private RecyclerView trainingRecyclerView;
private PlansAdapter pAdapter;
public TrainingFragment() {
// Required empty public constructor
}
//Change the title in action bar
public void onResume() {
super.onResume();
String titleString = getResources().getString(R.string.title_activity_navigation_drawer_training);
// Set title bar
((NavigationDrawerActivity) getActivity())
.setActionBarTitle(titleString);
}
public static TrainingFragment newInstance() {
TrainingFragment fragment = new TrainingFragment();
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Menü bekannt geben, dadurch kann Fragment Menü-Events verarbeiten
setHasOptionsMenu(true);
}
//Fragment XML geben, sowie als Menü setzen
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.menu_training, menu);
// Declare ImageView and Animation for rotation animation
MenuItem reloadButton = (MenuItem) menu.findItem(R.id.menu_reloadbutton);
final Animation rotation = AnimationUtils.loadAnimation(getActivity(), R.anim.animation_rotate);
//if (reloadButton != null) {
// //reloadButton.setImageResource(R.drawable.ic_menu_reloadentry);
// reloadButton.getActionView().setOnClickListener(new View.OnClickListener() {
// #Override
// public void onClick(View view) {
// rotation.setRepeatCount(Animation.INFINITE);
// view.startAnimation(rotation);
// }
// });
//}
}
//AddEntry click abfangen und verarbeiten
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Wir prüfen, ob Menü-Element mit der ID "action_daten_aktualisieren"
// ausgewählt wurde und geben eine Meldung aus
int id = item.getItemId();
if (id == R.id.menu_reloadbutton) {
// Text ausgeben
//Toast.makeText(getActivity(), "Liste aktualisieren gedrückt!", Toast.LENGTH_LONG).show();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_training, container, false);
// Get Refresh Layout
SwipeRefreshLayout swipeRefreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.training_swiperefresh);
// Change color for the refresh layout
swipeRefreshLayout.setColorSchemeColors(Color.rgb(99, 195, 195));
trainingRecyclerView = (RecyclerView) view.findViewById(R.id.training_recycler_view);
pAdapter = new PlansAdapter(planList, getContext());
RecyclerView.LayoutManager pLayoutManager = new LinearLayoutManager(getActivity().getApplicationContext());
trainingRecyclerView.setLayoutManager(pLayoutManager);
trainingRecyclerView.setItemAnimator(new DefaultItemAnimator());
trainingRecyclerView.setAdapter(pAdapter);
preparePlansData();
return view;
}
private void preparePlansData() {
// Set plan data
Plans plan = new Plans("ABC-Bestellung", "Muskelaufbau", "Datum: 21.04.1997");
// Add Object to list
planList.add(plan);
plan = new Plans("test", "tttt", "ttttt");
planList.add(plan);
// Notify data changes
pAdapter.notifyDataSetChanged();
}
// 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);
}
#Override
public void onStart() {
super.onStart();
try {
mListener = (OnFragmentInteractionListener) getActivity();
} catch (ClassCastException e) {
throw new ClassCastException(getActivity().toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}
This is my Adapter:
public class PlansAdapter extends RecyclerView.Adapter<PlansAdapter.MyPlanHolder> {
private List<Plans> planList;
private final Context customContext;
public class MyPlanHolder extends RecyclerView.ViewHolder {
public TextView planTitle, planType, planDate;
public MyPlanHolder(View view) {
super(view);
planTitle = (TextView) view.findViewById(R.id.planTitle);
planType = (TextView) view.findViewById(R.id.planType);
planDate = (TextView) view.findViewById(R.id.planDate);
}
}
public PlansAdapter(List<Plans> planList, Context customContext) {
this.planList = planList;
this.customContext = customContext;
}
#Override
public MyPlanHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.plans_list_row, parent, false);
return new MyPlanHolder(itemView);
}
#Override
public void onBindViewHolder(MyPlanHolder holder, int position) {
final Plans plan = planList.get(position);
holder.planTitle.setText(plan.getPlanTitle());
holder.planType.setText(plan.getPlanType());
holder.planDate.setText(plan.getPlanDate());
}
#Override
public int getItemCount() {
return 0;
}
}
And finaly my object class for the elements:
public class Plans {
private String planTitle, planType, planDate;
public Plans(String planTitle, String planType, String planDate) {
this.planTitle = planTitle;
this.planType = planType;
this.planDate = planDate;
}
public void setPlanTitle(String planTitle) {
this.planTitle = planTitle;
}
public String getPlanTitle() {
return planTitle;
}
public void setPlanType(String planType) {
this.planType = planType;
}
public String getPlanType() {
return planType;
}
public void setPlanDate(String planDate) {
this.planDate = planDate;
}
public String getPlanDate() {
return planDate;
}
}
I hope that you can find the issue.
Inside Adapter's getItemCount() method you are returning 0 as size of list.You should change it as return planList.size()
Your code is fine except in your adapter you are returning 0 in getItemCount() method.
Here's the updated code :
public class PlansAdapter extends RecyclerView.Adapter<PlansAdapter.MyPlanHolder> {
private List<Plans> planList;
private final Context customContext;
public class MyPlanHolder extends RecyclerView.ViewHolder {
public TextView planTitle, planType, planDate;
public MyPlanHolder(View view) {
super(view);
planTitle = (TextView) view.findViewById(R.id.planTitle);
planType = (TextView) view.findViewById(R.id.planType);
planDate = (TextView) view.findViewById(R.id.planDate);
}
}
public PlansAdapter(List<Plans> planList, Context customContext) {
this.planList = planList;
this.customContext = customContext;
}
#Override
public MyPlanHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.plans_list_row, parent, false);
return new MyPlanHolder(itemView);
}
#Override
public void onBindViewHolder(MyPlanHolder holder, int position) {
final Plans plan = planList.get(position);
holder.planTitle.setText(plan.getPlanTitle());
holder.planType.setText(plan.getPlanType());
holder.planDate.setText(plan.getPlanDate());
}
#Override
public int getItemCount() {
return planList.size();
}
}
I want to display UUID and Minor code of found beacons using listview in android.
I think I have problem with custom adapter.
Here is my actual code:
FoundBeacons.java
public class FoundBeacon extends Activity implements BeaconConsumer {
private BeaconManager beaconManager;
private ListView listview;
private ArrayList<Beacon> beaconList;
private AdapterBeacon bAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_found_beacon);
beaconManager = BeaconManager.getInstanceForApplication(this);
beaconManager.bind(this);
beaconList = new ArrayList<Beacon>();
this.bAdapter = new AdapterBeacon(this, beaconList);
listview = (ListView) findViewById(R.id.listview);
listview.setAdapter(bAdapter);
}
#Override
public void onBeaconServiceConnect() {
beaconManager.addRangeNotifier(new RangeNotifier() {
#Override
public void didRangeBeaconsInRegion(final Collection<Beacon> beacons, Region region) {
if (beacons.size() > 0) {
runOnUiThread(new Runnable() {
#Override
public void run() {
bAdapter.copyBeacons(beacons);
listview.setAdapter(bAdapter);
}
});
}
}
});
try {
beaconManager.startRangingBeaconsInRegion(new Region("myRangingUniqueId", null, null, null));
} catch (RemoteException e) {
}
}
}
AdapterBeacon.java
public class AdapterBeacon extends ArrayAdapter<Beacon> {
private Context context;
private ArrayList<Beacon> allBeacons;
private LayoutInflater mInflater;
private boolean mNotifyOnChange = true;
public AdapterBeacon(Context context, ArrayList<Beacon> mBeacons) {
super(context, R.layout.row_beacon);
this.context = context;
this.allBeacons = new ArrayList<Beacon>(mBeacons);
this.mInflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
return allBeacons .size();
}
#Override
public Beacon getItem(int position) {
return allBeacons .get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public int getPosition(Beacon item) {
return allBeacons .indexOf(item);
}
#Override
public int getViewTypeCount() {
return 1; //Number of types + 1 !!!!!!!!
}
#Override
public int getItemViewType(int position) {
return 1;
}
public void copyBeacons(Collection<Beacon> beacons)
{
allBeacons.clear();
for (Beacon b : beacons)
{
allBeacons.add(b);
}
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
int type = getItemViewType(position);
if (convertView == null) {
holder = new ViewHolder();
switch (type) {
case 1:
convertView = mInflater.inflate(R.layout.row_beacon,parent, false);
holder.name = (TextView) convertView.findViewById(R.id.t1);
holder.description = (TextView) convertView.findViewById(R.id.t2);
break;
}
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.name.setText(allBeacons.get(position).getId1().toString());
holder.description.setText(allBeacons.get(position).getId2().toString());
holder.pos = position;
return convertView;
}
#Override
public void notifyDataSetChanged() {
super.notifyDataSetChanged();
mNotifyOnChange = true;
}
public void setNotifyOnChange(boolean notifyOnChange) {
mNotifyOnChange = notifyOnChange;
}
//---------------static views for each row-----------//
static class ViewHolder {
TextView name;
TextView description;
int pos; //to store the position of the item within the list
}
}
activity_found_beacon.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_found_beacon"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.pio.pd_inz_ibeacon.FoundBeacon">
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:id="#+id/listview" />
row_beacon.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/t1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="text"/>
<TextView
android:id="#+id/t2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="text"/>
<TextView
android:id="#+id/t3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="text"/>
I'm trying to make a drobdown navigation menu so i can move between my pages using SherlockFragmentActivity and SerlockListFragment
but every time i'm starting my app it's give this following error:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.download.manager/com.download.manager.Main}: java.lang.RuntimeException: Your content must have a ListView whose id attribute is android.R.id.list
this is SherlockFragmentActivity class
public class Main extends SherlockFragmentActivity implements OnNavigationListener{
private static final String KEY_MODELS="models";
private static final String KEY_POSITION="position";
private static final String[] labels= { "All", "Downloads","Completed","Later" };
private CharSequence[] models=new CharSequence[4];
private DownloadList frag=null;
private int lastPosition=-1;
ActionBar act;
ViewPager myviewpager;
int mSelectedPageIndex=1;
DownloadService downloadservice;
Intent serviceIntent ;
#Override
public void onCreate(Bundle state) {
super.onCreate(state);
frag=(DownloadList)getSupportFragmentManager().findFragmentById(android.R.id.content);
if (frag==null) {
frag=new DownloadList();
getSupportFragmentManager().beginTransaction().add(android.R.id.content, frag).commit();
}
if (state != null) {
models=state.getCharSequenceArray(KEY_MODELS);
}
if (downloadservice==null)
downloadservice= new DownloadService();
ArrayAdapter<String> nav=null;
act=getSupportActionBar();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH)
{
nav= new ArrayAdapter<String>( act.getThemedContext(),android.R.layout.simple_spinner_item,labels);
}
else
{
nav=new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,labels);
}
nav.setDropDownViewResource(android.R.layout.simple_list_item_1);
act.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
act.setDisplayShowTitleEnabled(false);
act.setHomeButtonEnabled(false);
act.setListNavigationCallbacks(nav, this);
if (state != null) {
act.setSelectedNavigationItem(state.getInt(KEY_POSITION));
}
serviceIntent= new Intent(Main.this,downloadservice.getClass());
if (startService(serviceIntent)==null)
startService(serviceIntent);
act.setTitle("");
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater infalter = getSupportMenuInflater();
infalter.inflate(R.menu.mymenu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId()==R.id.sub1)
{
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("Downlaod New File");
alert.setMessage("Enter URL");
final EditText input = new EditText(this);
alert.setView(input);
input.setText("http://205.196.123.184/ddpha7c5b8lg/616c36j0d1xbztf /Lecture+ppt+Ch2.ppt");
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String value = input.getText().toString();
Log.d("value",value);
}
});
alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
}
});
alert.show();
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
}
#Override
public boolean onNavigationItemSelected(int itemPosition, long itemId) {
lastPosition=itemPosition;
return false;
}
this is SherlockListFragment class
public class DownloadList extends SherlockListFragment {
int index=0;
Button downloadButton;
Button pauseButton;
Button resumeButton;
TextView textLink;
TextView progressbar;
DownloadService downloadservice= new DownloadService();
MyAdapter listadapter;
Intent serviceIntent ;
String state;
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
getActivity().setContentView(R.layout.downloadlist);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup
container,BundlesavedInstanceState) {
View rootView = inflater.inflate(R.layout.downloadlist, container, false);
return rootView;
}
int getIndex()
{
return index;
}
public class MyAdapter extends ArrayAdapter<NewDownload>
{
private final List<NewDownload> list;
private final Activity context;
Thread t;
public MyAdapter(Context context,List<NewDownload> list) {
super(context, R.layout.list_item, list);
this.context = (Activity) context;
this.list = list;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) getActivity().
getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View row = inflater.inflate(R.layout.list_item, null);
pauseButton = (Button) row.findViewById(R.id.btn1);
resumeButton = (Button) row.findViewById(R.id.btn2);
textLink = (TextView) row.findViewById(R.id.tv1);
progressbar = (TextView) row.findViewById(R.id.progressBar1);
textLink.setText(downloadservice.
downloads.get(position).getName());
progressbar.setBottom(downloadservice.
downloads.get(position).getDownloadedSize());
progressbar.setTop(downloadservice.
downloads.get(position).getTotalSize());
final int p = position;
final NewDownload r = list.get(p);
if (r.state=="downloading")
{
progressbar.setText("DownLoading...");
pauseButton.setEnabled(true);
resumeButton.setEnabled(false);
}
else if (r.state=="pause")
{
pauseButton.setEnabled(false);
resumeButton.setEnabled(true);
progressbar.setText(r.state);
}
pauseButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
downloadservice.pause(p);
setListAdapter(listadapter );
}
});
resumeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (getActivity().startService(serviceIntent)==null)
getActivity().startService(serviceIntent);
downloadservice.resume(p);
setListAdapter(listadapter );
}
});
return row;
}
}
this is downloadlist.xml
<ListView
android:id="#+id/list" xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
this is list_item.XML
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/tv1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="File Name" />
<TextView
android:id="#+id/progressBar1"
android:layout_width="306dp"
android:layout_height="wrap_content"
/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<Button
android:id="#+id/btn1"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="34dp"
android:layout_gravity="center_horizontal"
android:text="Pause" />
<Button
android:id="#+id/btn2"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="34dp"
android:layout_gravity="right"
android:text="Resume" />
</LinearLayout>
</LinearLayout>
So any one can tell me where is my mistake ?
This error:
Your content must have a ListView whose id attribute is android.R.id.list
means you must use:
<ListView
android:id="#android:id/list"
...
in download.xml.