I have a listview with multiple items and one button to start a new activity. I'm getting Null Pointer Exception when I run my app. How and where shoud I set the OnClickListener to run properly?
Also, how can I pass with Intent the arraylist named listaIngrediente?
Here is my code
main_activity.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: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="com.example.radu.fridgecheck.MainActivity"
android:orientation="vertical">
<ListView
android:id="#+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1">
</ListView>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/find_recipies"
android:id="#+id/find"
android:layout_weight="0"/>
</LinearLayout>
list_item.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="wrap_content"
android:orientation="vertical"
android:padding="6dip" >
<CheckBox
android:id="#+id/checkBox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:focusable="false"
android:focusableInTouchMode="false"/>
<TextView
android:id="#+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/checkBox"
android:layout_alignBottom="#+id/checkBox"
android:layout_toRightOf="#+id/checkBox"
android:text="TextView" />
</RelativeLayout>
Adapter
public class Adapter extends ArrayAdapter<Ingredient> {
public LayoutInflater inflater;
public ArrayList<Ingredient> listaIngrediente;
ArrayList<String> ingredienteDisponibile;
private Activity activity;
public Adapter(Activity activity, int textResourceId, ArrayList<Ingredient> ingrediente) {
super(activity, textResourceId, ingrediente);
this.activity=activity;
this.listaIngrediente=ingrediente;
try {
inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
} catch (Exception e) {
e.printStackTrace();
}
}
public int getCount() {
return listaIngrediente.size();
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (convertView == null) {
v = inflater.inflate(R.layout.list_item, null);
}
final Ingredient ingredients = getItem(position);
final TextView display_ingredients = (TextView) v.findViewById(R.id.name);
display_ingredients.setText(ingredients.getNameI());
final CheckBox checkBox = (CheckBox) v.findViewById(R.id.checkBox);
ListView listView = (ListView) v.findViewById(R.id.listView1);
Button button = (Button) v.findViewById(R.id.button);
listView.addFooterView(button);
Button find = (Button) v.findViewById(R.id.find);
find.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(getContext(), ShowRecipes.class);
Bundle args = new Bundle(); /// nu reusesc sa transfer obiectele
args.putSerializable("ARRAYLIST",listaIngrediente);
i.putExtra("BUNDLE",args);
activity.startActivity(i);
}
});
v.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(!ingredients.isSelected()) {
checkBox.setChecked(true);
ingredients.setSelected(true);
}
else{
checkBox.setChecked(false);
ingredients.setSelected(false);
}
}
});
return v;
}
}
You have to write that in MainActivity class, because your button is in main_activity.xml
In MainActivity, write this method
public void showRecipes(View view) {
Intent i = new Intent(getContext(), ShowRecipes.class);
Bundle args = new Bundle(); /// nu reusesc sa transfer obiectele
args.putSerializable("ARRAYLIST",listaIngrediente);
i.putExtra("BUNDLE",args);
startActivity(i);
}
In Xml add onClick
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/find_recipies"
android:id="#+id/find"
android:onClick="showRecipes"
/>`
More Information on click Events
http://developer.android.com/guide/topics/ui/controls/button.html#HandlingEvents
Related
Basically I am trying to code a onClickListener for a button in MainActivity.java .
This Button is defined in a resource file : main_resource.xml inside a ListView and not in activity_main.xml.
I am getting the error :
Trying to define a onClick Listener on null item.
Button btn = (Button) findViewById(R.id.mybutton);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
myFancyMethod(v);
}
});
Here is my main_resource.xml :
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
android:id="#+id/relativeLayout1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android"
android:padding="5dip">
<TextView
android:layout_height="wrap_content"
android:text="TextView"
android:layout_width="wrap_content"
android:id="#+id/ridedetails"
android:layout_marginLeft="2dip">
</TextView>
<EditText
android:layout_height="wrap_content"
android:hint="Quote Price"
android:layout_width="wrap_content"
android:id="#+id/PriceQuotation"
android:layout_below="#+id/ridedetails"
android:layout_marginLeft="2dip">
</EditText>
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/PriceQuotation"
android:layout_marginStart="61dp"
android:layout_toEndOf="#+id/PriceQuotation"
android:text="Button" />
</RelativeLayout>
Here is my activity_main.xml :
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.SwipeRefreshLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/myrefresh"
android:focusable="false"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v4.widget.DrawerLayout
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start">
<include
layout="#layout/app_bar_home"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<android.support.design.widget.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:headerLayout="#layout/nav_header_home"
app:menu="#menu/activity_home_drawer" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".PreviousRide"
>
<ListView
android:id="#+id/incomingrides"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginStart="30dp"
android:layout_marginTop="80dp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"></ListView>
</LinearLayout>
</android.support.v4.widget.DrawerLayout>
</android.support.v4.widget.SwipeRefreshLayout>
Here I am not using any Custom Adapter Class : I am injecting the data into my list view using the following ArrayAdapter code written in onRefresh() of Swipe Refresh Widget ::
final ArrayAdapter<String > adapter=new ArrayAdapter<String>(getApplicationContext(),
R.layout.home_resource, R.id.ridedetails, allNames);
l1.setAdapter(adapter);
// L1 is the listView Reference
You have to create custom class for adapter
Here is sample code for adapter.
public class MyAdapter extends ArrayAdapter<String> {
private int resourceId;
private List<String> sites = null;
private Context context;
public MyAdapter(Context context, int resource, List<String> objects) {
super(context, resource, objects);
this.context = context;
this.resourceId = resource;
this.sites = objects;
}
#Override
public String getItem(int position) {
return sites.get(position);
}
#Override
public int getCount() {
return sites.size();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
String name = getItem(position);
View view = convertView;
if (view == null) {
LayoutInflater vi = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = vi.inflate(resourceId, null);
}
TextView mTextView = (TextView) view.findViewById(R.id.ridedetails);
mTextview.setText(name);
Button mButton = (Button) view.findViewById(R.id.button);
mButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(context, name, Toast.LENGTH_SHORT).show();
}
});
return view;
}
}
set adapter in listview like below code.
l1.setAdapter(new MyAdapter(getApplicationContext(), R.layout.home_resource, allNames));
you should put your onClickListener in Adapter Not in Main Activity
Your Adapter
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
Button btn = (Button ) v.findViewById(R.id.btn);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
myFancyMethod(v);
}
})
}
I have a problem ,I create recyclerview and its work fine at the first search data from api , it display fine but when I try to search with new data ( second time ) it is not display anything i try to test and debug every every thing work fine and new data enter to adapter and get the result fine and set adapter to recyclerview but it is not showing any thing
I try several method like use only one adapter and change it's list of Date and use notifyDataSetChange but not work still only show at the first time
Below activity is use to search get date ( use in searching data )
fromDate to toDate
DeliveryReportActivity.java
public class DeliveryReportActivity extends AppCompatActivity
implements DateDialogFromFragment.SelectDateFromInterface,
DateDialogToFragment.SelectDateToInterface {
Button btn_from;
Button btn_to;
EditText et_fromDate;
EditText et_toDate;
Button search_btn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_delivery_report);
btn_from=(Button)findViewById(R.id.btn_fromDate);
btn_to=(Button)findViewById(R.id.btn_toDate);
et_fromDate = (EditText) findViewById(R.id.from_date);
et_toDate = (EditText) findViewById(R.id.to_date);
search_btn=(Button)findViewById(R.id.search_delivery_report_btn);
et_fromDate.setText(new SimpleDateFormat("yyyy-MM-dd").format(new
Date()));
et_toDate.setText(new SimpleDateFormat("yyyy-MM-dd").format(new
Date()));
btn_from.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DateDialogFromFragment dateDialogFragment = new
DateDialogFromFragment();
android.app.FragmentTransaction ft =
getFragmentManager().beginTransaction();
dateDialogFragment.show(ft, "DatePicker");
}
});
btn_to.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DateDialogToFragment dateDialogFragment = new
DateDialogToFragment();
android.app.FragmentTransaction ft =
getFragmentManager().beginTransaction();
dateDialogFragment.show(ft, "DatePicker");
}
});
search_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Bundle bundle=new Bundle();
bundle.putString("from",et_fromDate.getText().toString()+ "
00:00:00");
bundle.putString("to",et_toDate.getText().toString()+" 23:59:59");
Intent intent =new
Intent(DeliveryReportActivity.this,DeliveryReportListActivity.class);
intent.putExtras(bundle);
startActivity(intent);
}
});
}
#Override
public void onGetSelectFromDate(String fromDate) {
et_fromDate.setText(fromDate);
}
#Override
public void onGetSelectToDate(String toDate) {
et_toDate.setText(toDate);
}
}
and it's view activity_delivery_report.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="20dp"
android:orientation="vertical"
tools:context="com.exatech.groupsmsandroid.activity.
deliveryReport.DeliveryReportActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:id="#+id/btn_fromDate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/From"
android:textSize="18dp" />
<EditText
android:id="#+id/from_date"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="2017-12-26" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="50dp"
android:orientation="horizontal">
<Button
android:id="#+id/btn_toDate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/to" />
<EditText
android:id="#+id/to_date"
android:text="2017-12-26"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Button
android:layout_centerInParent="true"
android:gravity="center"
android:layout_marginTop="20dp"
android:id="#+id/search_delivery_report_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#color/colorPrimary"
android:text="#android:string/search_go" />
</RelativeLayout>
</LinearLayout>
after I press the search button it's start new activity that show my recylerview the new activity is
DeliveryReportListActivity .java
public class DeliveryReportListActivity extends AppCompatActivity implements
DeliveryReportService.DeliveryReportServiceInterface {
private static final String TAG = "GSMS";
private Bundle bundle;
private RecyclerView recyclerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_delivery_report_list);
recyclerView = (RecyclerView) findViewById(R.id.delivery_report_rv);
}
#Override
protected void onResume() {
super.onResume();
bundle = getIntent().getExtras();
String from = bundle.getString("from");
String to = bundle.getString("to");
DeliveryReportService.getInstance(this).
getDeliveryReportFromDateToDate(from, to);// Call api get deliver
}
#Override
public void onGetDeliveryReport(Response<List<DeliveryReportResource>>
listResponse) {// response
Log.i(TAG, "onGetDeliveryReport: listResponse.body():" +
listResponse.body());
DeliveryReportAdapter deliveryReportAdapter = new
DeliveryReportAdapter(DeliveryReportListActivity.this, listResponse.body());
recyclerView.setAdapter(deliveryReportAdapter);
deliveryReportAdapter.notifyDataSetChanged();
Toast.makeText(DeliveryReportListActivity.this, "Delivery Report Success
", Toast.LENGTH_SHORT).show();
}
#Override
public void onDeliveryConnectionFailed() {
Toast.makeText(DeliveryReportListActivity.this, "Connect Error ",
Toast.LENGTH_SHORT).show();
}
}
and it's view activity_delivery_report_list.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.exatech.groupsmsandroid.activity.deliveryReport.
DeliveryReportListActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:text="#string/text"
android:layout_weight="3"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:layout_weight="4"
android:text="#string/phone_no"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:layout_weight="4"
android:text="#string/status"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
<android.support.v7.widget.RecyclerView
android:id="#+id/delivery_report_rv"
android:layout_width="match_parent"
app:layoutManager="LinearLayoutManager"
android:layout_height="match_parent"
tools:listitem="#layout/delivery_report_list_content"/>
</LinearLayout>
Below is Myadapter Class
**DeliveryReportAdapter.java**
public class DeliveryReportAdapter extends
RecyclerView.Adapter<DeliveryReportAdapter.ViewHolder> {
List<DeliveryReportResource> listDeliveryReport;
Context context;
public DeliveryReportAdapter(Context context, List<DeliveryReportResource>
listDeliveryReport) {
this.listDeliveryReport = listDeliveryReport;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view =
LayoutInflater.from(parent.getContext()).
inflate(R.layout.delivery_report_list_content, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(final ViewHolder holder, int position) {
holder.item = listDeliveryReport.get(position);
holder.text.setText(holder.item.getText());
CustomAdapterFroDeliveryReport adapterFroDeliveryReport = new
CustomAdapterFroDeliveryReport(context, R.layout.two_text_contect,
listDeliveryReport.get(position).getSmsSubscribedRecipientsResourceList());
holder.phoneNoAndStatus.setAdapter(adapterFroDeliveryReport);
holder.view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context, "click message no=" +
holder.item.getText(), Toast.LENGTH_SHORT).show();
}
});
}
#Override
public int getItemCount() {
return listDeliveryReport.size();
}
class ViewHolder extends RecyclerView.ViewHolder {
View view;
TextView text;
ListView phoneNoAndStatus;
DeliveryReportResource item;
public ViewHolder(View itemView) {
super(itemView);
view = itemView;
text = (TextView) itemView.findViewById(R.id.message_tv);
phoneNoAndStatus = (ListView)
itemView.findViewById(R.id.phoneNo_and_status_lv);
}
}
}
Try to create an adapter once and then update items
Add next code to your adapter class
ArrayList<DeliveryReportResource> listDeliveryReport = new ArrayList<DeliveryReportResource>();
public DeliveryReportAdapter(Context context) {
this.context = context;
}
public void updateItems(List<DeliveryReportResource> list) {
listDeliveryReport.clear();
listDeliveryReport.addAll(list);
notifyDataSetChanged();
}
Then create adapter once in onCreate() and place it as global variable
And now you should call adapter.updateItems(...) every time you want to change data
I am creating an app that has a fragment where a user can open a spinner using a button and select a food item. The food item will then be displayed under the button in a list. I have tried creating textviews and making invisible textviews and setting the text later, but none have worked. I was wondering if anyone knew of a better way of creating this that I'm not seeing.
<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="com.lastineindustries.ingredismartv2.Kitchen">
<!-- TODO: Update blank fragment layout -->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button
android:text="Add An Ingredient"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/add"
android:textSize="30sp"
android:layout_gravity="center" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="320dp"
android:layout_height="match_parent"
android:id="#+id/main"
android:orientation="vertical">
</LinearLayout>
<LinearLayout
android:layout_width="60dp"
android:layout_height="match_parent"
android:id="#+id/valueButton"
android:orientation="vertical">
</LinearLayout>
</LinearLayout>
</LinearLayout>
Is this what you want?
Then, read my code.
code of ChooseFoodFragment.java and its layout file:
public class ChooseFoodFragment extends Fragment{
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_choose_food, container, false);
initViews(v);
return v;
}
private Button btn_add;
private ListView listView;
private List<String> mData = new ArrayList<>();
private ArrayAdapter<String> mAdapter;
private void initViews(View v) {
listView = v.findViewById(R.id.list);
mAdapter = new ArrayAdapter<>(getActivity(), android.R.layout.simple_list_item_1, mData);
listView.setAdapter(mAdapter);
btn_add = v.findViewById(R.id.add);
btn_add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ChooseFoodDialog dialog = new ChooseFoodDialog();
dialog.setOnSelectedListener(new ChooseFoodDialog.OnSelectedListener() {
#Override
public void onSelected(String name) {
mData.add(name);
mAdapter.notifyDataSetChanged();// update the list of selected food
}
});
dialog.show(getFragmentManager(), "");//show the spinner items to select
}
});
}
}
fragment_choose_food.xml,just remove other views except the root view and the button, then add a ListView.
<?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="com.lastineindustries.ingredismartv2.Kitchen">
<!-- TODO: Update blank fragment layout -->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button
android:id="#+id/add"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Add An Ingredient"
android:textSize="30sp" />
<ListView
android:id="#+id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="16dp" />
</LinearLayout>
</FrameLayout>
the code of ChooseFoodDialog.java and its layout file.
public class ChooseFoodDialog extends DialogFragment {
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = LayoutInflater.from(getContext()).inflate(R.layout.dialog_choose_food, container, false);
initViews(v);
return v;
}
private ListView lv;
private List<String> mData = new ArrayList<>();
private void initViews(View v) {
// prepare some temp data
for (int i = 0; i < 10; i++) {
mData.add("Ingredients_" + i);
}
lv = v.findViewById(R.id.lv_ingredients);
ArrayAdapter<String> adapter = new ArrayAdapter<>(getContext(), android.R.layout.simple_list_item_1, mData);
lv.setAdapter(adapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
String ingredient = mData.get(i);
if (mListener != null) {
mListener.onSelected(ingredient);// when the item of food is selected
}
dismiss();
}
});
}
private OnSelectedListener mListener;
public void setOnSelectedListener(OnSelectedListener listener) {
mListener = listener;
}
interface OnSelectedListener {
void onSelected(String name);
}
}
dialog_choose_food.xml,that's simple.
<?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">
<ListView
android:id="#+id/lv_ingredients"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
run the program, check it.
You should use ListView or RecyclerView for such tasks. Check out example from official Android documentation: link.
Past few days I've been working on fixed footer for my recyclerview but so far I didn't get the result that I expected. I've already taken a look existing questions but got same result as before.It seems I 'm still missing a point but I can't figure out... Therefore I'm waiting for your suggestions. Thanks!
Here is the current view of layout, I want that FOOTER part to be sticky at bottom of recyclerview.
DrawerAdapter.java
public class DrawerAdapter extends RecyclerView.Adapter<DrawerAdapter.DrawerViewHolder> {
// Class for view types.
private class VIEW_TYPES {
public static final int Header = 0;
public static final int Normal = 1;
public static final int Footer = 2;
}
private ArrayList<DrawerItem> drawerMenuList;
private String userProfileName;
private String userProfileMail;
private Drawable userProfilePic;
private OnItemSelecteListener mListener;
public DrawerAdapter(ArrayList<DrawerItem> drawerMenuList, String name, String mail, Drawable profileImage) {
this.drawerMenuList = drawerMenuList;
this.userProfileMail = mail;
this.userProfileName = name;
this.userProfilePic = profileImage;
}
#Override
public DrawerViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view;
if (viewType == VIEW_TYPES.Header) {
view = LayoutInflater.from(parent.getContext()).inflate(R.layout.header, parent, false);
} else if (viewType == VIEW_TYPES.Footer) {
view = LayoutInflater.from(parent.getContext()).inflate(R.layout.footer, parent, false);
} else {
view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_row, parent, false);
}
return new DrawerViewHolder(view, viewType);
}
#Override
public void onBindViewHolder(DrawerViewHolder holder, int position) {
// If item's position 0 it's a header.
if (position == 0) {
holder.headerName.setText(userProfileName);
holder.headerMail.setText(userProfileMail);
holder.headerProfile.setImageDrawable(userProfilePic);
} else if (position == 5) { // If position is 5 then it's footer.
holder.headerName.setText("FOOTER");
} else { // it's a menu item.
holder.title.setText(drawerMenuList.get(position - 1).getTitle());
holder.icon.setImageResource(drawerMenuList.get(position - 1).getIcon());
}
}
#Override
public int getItemCount() {
return drawerMenuList.size() + 1;
}
#Override
public int getItemViewType(int position) {
if (position == 0) {
return VIEW_TYPES.Header;
} else if (position == 5) {
return VIEW_TYPES.Footer;
} else {
return VIEW_TYPES.Normal;
}
}
class DrawerViewHolder extends RecyclerView.ViewHolder {
TextView title;
TextView headerName;
ImageView icon;
TextView headerMail;
ImageView headerProfile;
public DrawerViewHolder(View itemView, int viewType) {
super(itemView);
if (viewType == VIEW_TYPES.Header) {
headerName = (TextView) itemView.findViewById(R.id.header_name);
headerMail = (TextView) itemView.findViewById(R.id.header_email);
headerProfile = (ImageView) itemView.findViewById(R.id.circleView);
} else if (viewType == VIEW_TYPES.Footer) {
headerName = (TextView) itemView.findViewById(R.id.textView3);
} else {
title = (TextView) itemView.findViewById(R.id.title);
icon = (ImageView) itemView.findViewById(R.id.icon);
}
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mListener.onItemSelected(view, getAdapterPosition());
}
});
}
}
// To set click listener.
public interface OnItemSelecteListener {
void onItemSelected(View v, int position);
}
public void setOnItemClickLister(OnItemSelecteListener mListener) {
this.mListener = mListener;
}
}
MainActivity.java
for (int i = 0; i < navMenuTitles.length; i++) {
Log.e("I", String.valueOf(i));
mDrawerItemList.add(new DrawerItem(navMenuTitles[i], navMenuIcons.getResourceId(i, -1)));
}
mDrawerItemList.add(new DrawerItem());
mRecyclerView = (RecyclerView) findViewById(R.id.drawerRecyclerView);
mDrawerAdapter = new DrawerAdapter(mDrawerItemList, logged_user.name, logged_user.email, draw_userImage);
mLinearLayoutManager = new CustomGridLayoutManager(HomeScreenActivity.this){
#Override
public boolean canScrollVertically() {
return false;
}
};
mRecyclerView.setLayoutManager(mLinearLayoutManager);
mRecyclerView.setAdapter(mDrawerAdapter);
mDrawerLayout = (DrawerLayout) findViewById(R.id.DrawerLayout);
mDrawerToggle = new ActionBarDrawerToggle(HomeScreenActivity.this, mDrawerLayout, mToolbar, R.string.openDrawer, R.string.closeDrawer) {
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
// code here will execute once the drawer is opened( As I dont want anything happened whe drawer is
// open I am not going to put anything here)
}
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
// Code here will execute once drawer is closed
}
}; // Drawer Toggle Object Made
mDrawerLayout.addDrawerListener(mDrawerToggle); // Drawer Listener set to the Drawer toggle
mDrawerToggle.syncState(); // Finally we set the drawer toggle sync State
mDrawerAdapter.setOnItemClickLister(new DrawerAdapter.OnItemSelecteListener() {
#Override
public void onItemSelected(View v, int position) {
Log.e("CLICK", "You clicked at position: " + position);
}
});
drawer_layout.xml
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/DrawerLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentBottom="true"
android:elevation="7dp">
<FrameLayout
android:id="#+id/containerView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" />
<android.support.v7.widget.RecyclerView
android:id="#+id/drawerRecyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentBottom="true"
android:layout_gravity="left"
android:background="#ffffff"
app:reverseLayout="false"
app:stackFromEnd="false">
</android.support.v7.widget.RecyclerView>
footer.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="bottom"
android:layout_alignParentBottom="true"
android:background="#ffffff"
android:layout_alignBottom="#id/drawerRecyclerView"
android:foregroundGravity="bottom">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentStart="false"
android:layout_alignParentEnd="true"
android:background="#f16666"
android:foregroundGravity="bottom"
android:gravity="center_horizontal|bottom"
android:paddingTop="#dimen/_15sdp"
android:paddingBottom="#dimen/_15sdp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="TEST"
android:id="#+id/textView3"
android:layout_gravity="center_horizontal"
android:layout_alignParentBottom="true"
android:gravity="center_horizontal|bottom" />
</LinearLayout>
</RelativeLayout>
In your drawer_layout.xml put RecyclerView inside a RelativeLayout and set alignParentTop to true. Then remove your footer view from your RecyclerView and put that inside the RelativeLayout below RecyclerView like this:
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/DrawerLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentBottom="true"
android:elevation="7dp">
<FrameLayout
android:id="#+id/containerView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" />
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.RecyclerView
android:id="#+id/drawerRecyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentTop="true"
android:layout_gravity="left"
android:background="#ffffff"
app:reverseLayout="false"
app:stackFromEnd="false" />
<include layout="#layout/footer" />
</RelativeLayout>
</android.support.v4.widget.DrawerLayout>
You could also take a look at NavigationView so you don't have to customize your drawer list. Here is a tutorial on how to use this. It is pretty easy to use and requires less code. You could then take a look at this answer on how to put a footer in NavigationView.
I am using LinearLayout with weight-ing (created multiple dimens files with different values). For me it works as excepted:
<?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:background="#color/white"
android:orientation="vertical"
<include layout="#layout/header" />
<android.support.v7.widget.RecyclerView
android:id="#+id/recycleView"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="0.5"
tools:layout_height="0dp"
tools:listitem="#layout/row" />
<TextView
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="#dimen/footer_weight"
android:padding="#dimen/extra_padding"
android:paddingEnd="#dimen/small_padding"
android:paddingLeft="#dimen/small_padding"
android:paddingRight="#dimen/small_padding"
android:paddingStart="#dimen/small_padding"
android:text="#string/contact"
android:textColor="#color/grey" />
</LinearLayout>
I'm really new in Android. I have this problem, I have an Activity (MainActivity) and there is a NavigationDrawer, this switches two fragments - ActivitiesFragment and ReportFragments.
The problem is with ActivitiesFragments, data is not displayed.
I have my adapter ready and my layouts ready and the fragment. When I debugg my app, it actually brings data, but is not shown. This is my code:
ActivitiesAdapter
public class ActivitiesAdapter extends ArrayAdapter<Activities>
{
Context mContext;
int mLayoutResourceId;
public ActivitiesAdapter(Context context, int layoutResourceId)
{
super(context, layoutResourceId);
mContext = context;
mLayoutResourceId = layoutResourceId;
}
public View getView(int position, View convertView, ViewGroup parent)
{
View row = convertView;
final Activities currentItem = getItem(position);
if (row == null)
{
LayoutInflater inflater = ((Activity) mContext).getLayoutInflater();
row = inflater.inflate(mLayoutResourceId, parent, false);
}
row.setTag(currentItem);
final TextView tituloview = (TextView) row.findViewById(R.id.tituloAct);
tituloview.setText(currentItem.getTitle());
final TextView descrpview = (TextView) row.findViewById(R.id.descrAct);
descrpview.setText(currentItem.getDescription());
return row;
}
}
This is my fragment ActivitiesFragment
public class ActivitiesFragment extends Fragment
{
protected static final String TAG = "ActivitiesFragmment";
private MobileServiceClient mClient;
private MobileServiceTable<Activities> mActivitiesTable;
private ActivitiesAdapter mAdapter;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.act_listfragment, container, false);
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState)
{
super.onActivityCreated(savedInstanceState);
try
{
mClient = new MobileServiceClient("https://site.azure-mobile.net/",
"APPLICATIONKEYAPPLICATIONKEY",
getActivity().getApplicationContext()).withFilter(new ProgressFilter());
mActivitiesTable = mClient.getTable(Activities.class);
}
catch (MalformedURLException e)
{
createAndShowDialog(new Exception("There was an error creating the Mobile Service. Verify the URL"), "Error");
}
mAdapter = new ActivitiesAdapter(getActivity(), R.layout.act_itemlist);
ListView listViewToDo = (ListView) getView().findViewById(R.id.activities_fragment_list);
listViewToDo.setAdapter(mAdapter);
refreshItemsFromTable();
}
private void createAndShowDialog(Exception exception, String title)
{
createAndShowDialog(exception.toString(), title);
}
private void createAndShowDialog(String message, String title)
{
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity().getApplicationContext());
builder.setMessage(message);
builder.setTitle(title);
builder.create().show();
}
private void refreshItemsFromTable()
{
mActivitiesTable.execute(new TableQueryCallback<Activities>()
{
public void onCompleted(List<Activities> result, int count, Exception exception, ServiceFilterResponse response) {
if (exception == null) {
mAdapter.clear();
for (Activities item : result) {
mAdapter.add(item);
Log.i(TAG, "Titulo: " + item.getTitle());
}
} else {
createAndShowDialog(exception, "Error");
}
}
});
}
}
I don't know whats wrong, but I guess this block is not working on the OnActivityCreated method:
mAdapter = new ActivitiesAdapter(getActivity(), R.layout.act_itemlist);
ListView listViewToDo = (ListView) getView().findViewById(R.id.activities_fragment_list);
listViewToDo.setAdapter(mAdapter);
refreshItemsFromTable();
And here are my Layouts:
This is my frgament's layout:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#e1e1e1"
android:orientation="vertical" >
<TextView
android:id="#+id/tvTituloActs"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/all_activities"
android:layout_marginLeft="16dp"
android:layout_marginTop="8dp"
android:textColor="#009ad2"
android:textAppearance="?android:attr/textAppearanceMedium" />
<ListView android:id="#+id/activities_fragment_list"
android:layout_marginTop="8dp"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FFFFFF"
android:layout_weight="1"
tools:listitem="#layout/act_itemlist"
android:drawSelectorOnTop="false"/>
<TextView android:id="#id/android:empty"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="No hay datos"/>
</LinearLayout>
This is the layout act_itemlist. The row layout:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="64dp"
android:orientation="horizontal">
<ImageView
android:id="#+id/icon"
android:layout_width="32dp"
android:layout_height="32dp"
android:layout_marginLeft="8dp"
android:gravity="center_vertical"
android:src="#drawable/done"
android:layout_gravity="center_vertical"/>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/tvTituloAct"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="8dp"
android:layout_marginTop="16dp"
android:textSize="16sp"/>
<TextView
android:id="#+id/tvDescrAct"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="8dp"
android:text="Description de la actividad" />
</LinearLayout>
</LinearLayout>
I really need help with this! Please if someone can see something that I'm missing please tell me!
Thanks!!!!
Try to swap these lines:
mAdapter = new ActivitiesAdapter(getActivity(), R.layout.act_itemlist);
ListView listViewToDo = (ListView) getView().findViewById(R.id.activities_fragment_list);
refreshItemsFromTable(); // populate first before attaching your adapter
listViewToDo.setAdapter(mAdapter);
I finally solved my problem. Everything was Ok, the only detail was the layout. It was on the fragments layout.
<TextView android:id="#id/android:empty"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="No hay datos"/>
This textview did not let to show the data so I deleted it and worked.
Thankk you for your help #LazyNinja