Can anybody help me making the arraylist final ArrayList<PieEntry> entries = new ArrayList<>();
Parcelable in my code so I can access it in methods in both fragment a and b
- Fragment a code:
public class SecondFragment extends Fragment {
// Store instance variables
private String title;
private int page;
// newInstance constructor for creating fragment with arguments
public static SecondFragment newInstance(int page, String title) {
SecondFragment fragmentSecond = new SecondFragment();
Bundle args = new Bundle();
args.putInt("someInt", page);
args.putString("someTitle", title);
fragmentSecond.setArguments(args);
return fragmentSecond;
}
// Store instance variables based on arguments passed
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
page = getArguments().getInt("someInt", 0);
title = getArguments().getString("someTitle");
}
// Inflate the view for the fragment based on layout XML
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.fragment_second, container, false);
TextView tvLabel2 = (TextView) view.findViewById(R.id.textView2);
//Alle Objekte hier einfügen (wie textview tvavel2)
final Button button = (Button) view.findViewById(R.id.button);
final TextView textView = (TextView) view.findViewById(R.id.textView);
final TextView textView2 = (TextView) view.findViewById(R.id.textView2);
final EditText editText = (EditText) view.findViewById(R.id.editText);
final EditText editText2 = (EditText) view.findViewById(R.id.editText2);
final EditText editText3 = (EditText) view.findViewById(R.id.editText3);
final ArrayList<PieEntry> entries = new ArrayList<>();
button.setOnClickListener(new View.OnClickListener() {
public void onClick (View view) {
if (editText3.getText().toString().matches("")) {
Toast.makeText(getActivity(), "You did not enter a Valid Item ID", Toast.LENGTH_LONG).show();
return;
}
else if (editText2.getText().toString().matches("")) {
Toast.makeText(getActivity(), "You did not enter a Valid Quantitiy", Toast.LENGTH_LONG).show();
return;
}
else {
String nomen = (editText3.getText().toString());
float number = Float.parseFloat(editText2.getText().toString());
entries.add(new PieEntry(number, nomen));
editText3.setText("");
editText2.setText("");
editText3.requestFocus();
}
}
});
return view;
}
}
Fragment b code:
public class FirstFragment extends Fragment {
private String title;
private int page;
public static FirstFragment newInstance(int page, String title) {
FirstFragment fragmentFirst = new FirstFragment();
Bundle args = new Bundle();
args.putInt("someInt", page);
args.putString("someTitle", title);
fragmentFirst.setArguments(args);
return fragmentFirst;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
page = getArguments().getInt("someInt", 0);
title = getArguments().getString("someTitle");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_first, container, false);
EditText editText = (EditText) view.findViewById(R.id.editText);
final PieChart piechart = (PieChart) view.findViewById(R.id.piechart);
final Button button2 = (Button) view.findViewById(R.id.button2);
new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
}
#Override
public void onPageScrollStateChanged(int position) {
}
};
button2.setOnClickListener(new View.OnClickListener() {
public void onClick (View view) {
getResources().getColor(R.color.violp);
getResources().getColor(R.color.bluep);
getResources().getColor(R.color.redp);
getResources().getColor(R.color.greenp);
getResources().getColor(R.color.yellowp);
getResources().getColor(R.color.orangep);
getResources().getColor(R.color.lightbluep);
getResources().getColor(R.color.purplep);
getResources().getColor(R.color.darkredp);
PieDataSet set = new PieDataSet(entries, "");
set.setColors(new int[]{R.color.bluep, R.color.greenp, R.color.violp, R.color.redp, R.color.yellowp, R.color.orangep, R.color.lightbluep, R.color.purplep, R.color.darkredp}, getActivity());
PieData datax = new PieData(set);
piechart.setData(datax);
Toast.makeText(getActivity(), (R.string.loading),
Toast.LENGTH_SHORT).show();
piechart.setNoDataText(String.valueOf(R.string.nodata));
piechart.notifyDataSetChanged();
piechart.animateX(2000, Easing.EasingOption.EaseInExpo);
piechart.animateY(2000, Easing.EasingOption.EaseInExpo);
}
});
return view;
}
I have tried a number of options so far but I could not get the programm to run.
Any help is apprediated.
Thanks!
In order to transfer data, we need to parcel it or serialize it. Android OS by default promoting Parcelable instead to Serialization. Serialization is a java concept. In your case, you need to create the "PieEntry" class as Parcelable. For that, you need to implement the Parcelable interface in your model.
Check below implementation.
package com.cludprinting.mysample;
import android.os.Parcel;
import android.os.Parcelable;
/**
* Created by nithinjith.pp on 05-01-2017.
* Implement Parcelable in PieEntry.
*
*/
public class PieEntry implements Parcelable {
public static final Parcelable.Creator<PieEntry> CREATOR = new Parcelable.Creator<PieEntry>() {
#Override
public PieEntry createFromParcel(Parcel source) {
return new PieEntry(source);
}
#Override
public PieEntry[] newArray(int size) {
return new PieEntry[size];
}
};
// These are sample instance variables
// Add your own instance variable
private String mName;
private String mDOB;
private int mAge;
public PieEntry(Parcel parcel) {
this.mName = parcel.readString();
this.mDOB = parcel.readString();
this.mAge = parcel.readInt();
}
public int getmAge() {
return mAge;
}
public void setmAge(int mAge) {
this.mAge = mAge;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(this.mName);
dest.writeString(this.mDOB);
dest.writeInt(this.mAge);
}
public String getmDOB() {
return mDOB;
}
public void setmDOB(String mDOB) {
this.mDOB = mDOB;
}
public String getmName() {
return mName;
}
public void setmName(String mName) {
this.mName = mName;
}
}
The instance variable and access methods may change based on your implemenaton.
Related
I'm trying to display the bottom dialog fragment (AddNewHabit.java) when user clicked an item from the RecyclerView, but I kept getting the error that the fragment has not been attached yet. I don't know where or how should I attach it to make bottomSheetDialogFragment.show() work.
Logcat:
2022-09-11 20:52:31.916 21228-21228/com.unicode.android.wodehabit E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.unicode.android.wodehabit, PID: 21228
java.lang.IllegalStateException: Fragment AddNewHabit{fdd5021} (ce46aa77-b5b3-43e6-9564-559dd68d8ad9) has not been attached yet.
at androidx.fragment.app.Fragment.getChildFragmentManager(Fragment.java:1075)
at com.unicode.android.wodehabit.HabitsAdapter.editHabit(HabitsAdapter.java:91)
at com.unicode.android.wodehabit.HabitsAdapter$1.onClick(HabitsAdapter.java:50)
at android.view.View.performClick(View.java:7448)
at android.view.View.performClickInternal(View.java:7425)
at android.view.View.access$3600(View.java:810)
at android.view.View$PerformClick.run(View.java:28305)
at android.os.Handler.handleCallback(Handler.java:938)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7656)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
Here's HabitsFragment:
public class HabitsFragment extends Fragment implements DialogCloseListener{
private List<HabitModel> mHabitList;
private RecyclerView mRecyclerView;
private HabitsAdapter mHabitsAdapter;
private ImageButton mAddTaskBtn;
private Spinner mDropdown;
private DataBaseHandler db;
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
public HabitsFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment HabitsFragment.
*/
// TODO: Rename and change types and number of parameters
public static HabitsFragment newInstance(String param1, String param2) {
HabitsFragment fragment = new HabitsFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_habits, container, false);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
db = new DataBaseHandler(getActivity());
db.openDatabase();
mAddTaskBtn = (ImageButton) view.findViewById(R.id.add_new_habit_btn);
mAddTaskBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
AddNewHabit.newInstance().show(getChildFragmentManager(), AddNewHabit.TAG);
}
});
mRecyclerView = (RecyclerView) view.findViewById(R.id.habit_recyclerview);
mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
mHabitsAdapter = new HabitsAdapter(db, getActivity());
mRecyclerView.setAdapter(mHabitsAdapter);
updateRecyclerView();
}
public void handleDialogClose(DialogInterface dialog){
updateRecyclerView();
}
public void updateRecyclerView(){
mHabitList = db.getAllHabits();
Collections.reverse(mHabitList);
mHabitsAdapter.setHabit(mHabitList);
mHabitsAdapter.notifyDataSetChanged();
}
}
AddNewHabit.java:
public class AddNewHabit extends BottomSheetDialogFragment {
public static final String TAG = "com.unicode.android.wodehabit.action_bottom_dialog";
private EditText cueTxt, habitTxt, descriptionTxt;
private Button cancelBtn, addBtn;
private Spinner dropdown;
private DataBaseHandler db;
public static AddNewHabit newInstance() {
return new AddNewHabit();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setStyle(STYLE_NORMAL, R.style.DialogStyle);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.new_habit, container, false);
//readjust bottom sheet dialog and move upward when we type something
getDialog().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
return view;
}
//Define codes needed to execute functions in dialog fragment
#Override
public void onViewCreated(View view, Bundle saveInstanceState) {
super.onViewCreated(view, saveInstanceState);
cueTxt = (EditText) getView().findViewById(R.id.new_task_cue);
habitTxt = (EditText) getView().findViewById(R.id.new_task_habit);
descriptionTxt = (EditText) getView().findViewById(R.id.new_task_description);
dropdown = (Spinner) getView().findViewById(R.id.new_task_preposition);
cancelBtn = (Button) getView().findViewById(R.id.cancel_habit_button);
addBtn = (Button) getView().findViewById(R.id.add_habit_button);
//Spinner adapter
String[] items = new String[]{"before", "during", "after"};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_spinner_item, items);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
dropdown.setAdapter(adapter);
boolean isUpdate = false;
final Bundle bundle = getArguments();
if (bundle != null) {
isUpdate = true;
String cue = bundle.getString("cue");
cueTxt.setText(cue);
String habit = bundle.getString("habit");
habitTxt.setText(habit);
String description = bundle.getString("description");
descriptionTxt.setText(description);
}
db = new DataBaseHandler(getActivity());
db.openDatabase();
cancelBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
getParentFragmentManager().beginTransaction().remove(AddNewHabit.this).commit();
}
});
//final boolean finalIsUpdate = isUpdate;
boolean finalIsUpdate = isUpdate;
addBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String cue = cueTxt.getText().toString();
String preposition = dropdown.getSelectedItem().toString();
String habit = habitTxt.getText().toString();
String description = descriptionTxt.getText().toString();
String fullHabit = habit + " " + preposition + " " + cue;
if(finalIsUpdate){
db.updateHabit(bundle.getInt("id"), habit, description);
}else{
if (cue.isEmpty() || habit.isEmpty()) {
Toast.makeText(getActivity(), R.string.complete_toast, Toast.LENGTH_LONG).show();
} else {
HabitModel habit1 = new HabitModel();
habit1.setTitle(fullHabit);
habit1.setDescription(description);
db.insertHabit(habit1);
}
}
dismiss();
}
});
}
#Override
public void onDismiss(DialogInterface dialog){
Activity activity = getActivity();
if(activity instanceof DialogCloseListener){
((DialogCloseListener)activity).handleDialogClose(dialog);
}
}
}
Here's HabitsAdapter.java:
public class HabitsAdapter extends RecyclerView.Adapter<HabitsAdapter.ViewHolder> {
private List<HabitModel> mHabitList;
private Activity mActivity;
private DataBaseHandler db;
public HabitsAdapter(DataBaseHandler db, Activity activity){
this.db = db;
this.mActivity = activity;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.habit_item, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
db.openDatabase();
HabitModel item = mHabitList.get(position);
holder.mTitle.setText(item.getTitle());
holder.mDescription.setText(item.getDescription());
int pos = holder.getAdapterPosition();
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
editHabit(pos);
}
});
}
#Override
public int getItemCount() {
return mHabitList.size();
}
public static class ViewHolder extends RecyclerView.ViewHolder{
TextView mTitle, mDescription;
FloatingActionButton mFab;
ViewHolder(View view){
super(view);
mTitle = (TextView) view.findViewById(R.id.habit_title);
mDescription = (TextView) view.findViewById(R.id.habit_description);
mFab = (FloatingActionButton) view.findViewById(R.id.check_off_button);
}
}
public void setHabit(List<HabitModel> habitList){
this.mHabitList = habitList;
notifyDataSetChanged();
}
public Context getContext(){
return mActivity;
}
public void editHabit(int position){
HabitModel habit = mHabitList.get(position);
Bundle bundle = new Bundle();
bundle.putInt("id", habit.getId());
bundle.putString("habit", habit.getTitle());
bundle.putString("description", habit.getDescription());
AddNewHabit fragment = new AddNewHabit();
fragment.setArguments(bundle);
//THE PROBLEM
fragment.show(fragment.getChildFragmentManager(), AddNewHabit.TAG);
}
public void deleteHabit(int position){
HabitModel habit = mHabitList.get(position);
db.deleteHabit(habit.getId());
mHabitList.remove(position);
notifyItemRemoved(position);
}
}
Found the answer from https://stackoverflow.com/a/22971406/15433004
Replaced this code in HabitsAdapter:
AddNewHabit fragment = new AddNewHabit();
fragment.setArguments(bundle);
fragment.show(fragment.getChildFragmentManager(), AddNewHabit.TAG);
To:
FragmentActivity activity = (FragmentActivity)(getContext());
FragmentManager fm = activity.getSupportFragmentManager();
AddNewHabit fragment = new AddNewHabit();
fragment.setArguments(bundle);
fragment.show(fm, AddNewHabit.TAG);
I created a shopping cart app, and it has a menu item. Then it has another activity called "SettingActivity", for this settingActivity will have a TextView to show "Primary language, secondary language and both language".
I got the SharedPreferences data in the SettingActivity. How can I pass those data to the MainAdapter?
Because when I click the secondary language in the SettingActivity, then the menu will change to secondary language or show both languages.
So, how can I get the SettingActivity's SharedPreference data in the MainAdapter?
SettingActivity:
public class SettingActivity extends AppCompatActivity {
LinearLayout languageModeLinearLayout;
TextView languageModeTextView;
SharedPreferences settingPreferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_setting);
languageModeLinearLayout = findViewById(R.id.setting_language_mode_linearLayout);
languageModeTextView = findViewById(R.id.setting_language_mode_textView);
settingPreferences = getSharedPreferences("setting", MODE_PRIVATE);
updateUI();
languageModeLinearLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String[] language = getResources().getStringArray(R.array.setting_language_mode);
AlertDialog.Builder languageMode = new AlertDialog.Builder(v.getContext());
languageMode.setTitle("Select Language Mode");
languageMode.setItems(language, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int position) {
SharedPreferences.Editor editor = settingPreferences.edit();
editor.putInt("language", position);
editor.apply();
updateUI();
}
});
languageMode.create().show();
}
});
}
private String getLanguage(){
String[] language = getResources().getStringArray(R.array.setting_language_mode);
int position;
position = settingPreferences.getInt("language", 0);
return language[position];
}
private void updateUI(){
languageModeTextView.setText(getLanguage());
}
MainAdapter:
public class MainAdapter extends ArrayAdapter<MenuItem> implements Serializable {
private TextView mCartCounterTextView;
public MainAdapter(Context context, List<MenuItem> menuItems) {
super(context, 0, menuItems);
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
View itemView = convertView;
final ViewHolder viewHolder;
if (itemView == null) {
itemView = LayoutInflater.from(getContext()).inflate(R.layout.item_main, parent, false);
viewHolder = new ViewHolder(itemView);
itemView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) itemView.getTag();
}
final MenuItem currentMenuItem = getItem(position);
viewHolder.nameTextView.setText(currentMenuItem.getPrimaryName());
viewHolder.nameTextView.setText(currentMenuItem.getSecondaryName());
viewHolder.addToCartButton.setText(getFormattedPriceTextToButton(currentMenuItem));
viewHolder.addToCartButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Main.getAddedItems().add(currentMenuItem);
Toast.makeText(v.getContext(), "Item had added to cart", Toast.LENGTH_SHORT).show();
mCartCounterTextView.setText(String.valueOf(Main.getAddedItems().size()));
mCartCounterTextView.setVisibility(View.VISIBLE);
}
});
return itemView;
}
private String getFormattedPriceTextToButton(MenuItem currentMenuItem) {
return "+ $" + currentMenuItem.getPrice();
}
private class ViewHolder {
TextView nameTextView;
TextView priceTextView;
Button addToCartButton;
public ViewHolder(View itemView) {
nameTextView = itemView.findViewById(R.id.main_name_textView);
priceTextView = itemView.findViewById(R.id.main_price_textView);
addToCartButton = itemView.findViewById(R.id.main_add_to_cart_button);
}
}
public void setData(TextView cartCounter){
mCartCounterTextView = cartCounter;
}
private void getSharedPreferencesLanguage(){
// SharedPreferences.Editor editor = getContext().getSharedPreferences("setting", MODE_PRIVATE).edit();
SharedPreferences language = getContext().getSharedPreferences("setting", MODE_PRIVATE);
}
MenuItem:
public class MenuItem {
private String mPrimaryName;
private String mSecondaryName;
private double mPrice;
public MenuItem(String primaryName, String secondaryName, double price){
mPrimaryName = primaryName;
mSecondaryName = secondaryName;
mPrice = price;
}
public String getPrimaryName(){
return mPrimaryName;
}
public String getSecondaryName(){
return mSecondaryName;
}
public double getPrice(){
return mPrice;
}
Just pass your context to the function and get the value from sharedpref
public static String getLan(Context cont) {
SharedPreferences settingPreferences=settingPreferences =cont.getSharedPreferences("setting", MODE_PRIVATE);
String[] language = getResources().getStringArray(R.array.setting_language_mode);
int posi =settingPreferences.getInt("language",0);
return language[pos];
}
I think you are doing well on
SharedPreferences language = getContext().getSharedPreferences("setting", MODE_PRIVATE);
But now if you want to get the data (language int in this case) you just have to do the following:
int lang_int = language.getInt("language",0);
I want to pass a string value from my adapter class to my fragment. I tried storing the string in a bundle. To retrieve the value i used Bundle b = getArguments(); b.getString("key") the problem is im getting a null pointer exception. Below is the code that saves the string in a bundle. So my question is how can i pass a string value from adapterA to fragmentB.
Thanks in advance.
Adapter.java
public class ToDoRecyclerViewAdapter extends RecyclerView.Adapter<ToDoRecyclerViewAdapter.ViewHolder> {
private Context context;
private List<Aktivnost_> mValues;
private final OnListFragmentInteractionListener mListener;
public ToDoRecyclerViewAdapter td;
public ToDoRecyclerViewAdapter(List<Aktivnost_ > items, Context context, OnListFragmentInteractionListener listener) {
mValues = items;
mListener = listener;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.fragment_todo, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
holder.mItem = mValues.get(position);
holder.mContentView.setText(mValues.get(position).getNaziv());
holder.mDateView.setText(mValues.get(position).getDatum());
holder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (null != mListener) {
mListener.onListFragmentInteraction(holder.mItem);
Intent i = new Intent(context.getApplicationContext(), PodrobnostiActivity.class);
i.putExtra("task_id", mValues.get(position).getId_());
context.getApplicationContext().startActivity(i);
Toast.makeText(v.getContext(), "task - " + mValues.get(position).getId_(), Toast.LENGTH_SHORT).show();
}
}
});
holder.mView.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(final View v) {
AlertDialog.Builder adb = new AlertDialog.Builder(v.getContext());
CharSequence meni[] = new CharSequence[] {"DOING", "FINISHED"};
adb.setItems(meni, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
if(i == 0) {
Bundle b = new Bundle();
DoingFragment d = new DoingFragment();
mValues.get(i).setStanje("doing");
b.putString("doing", mValues.get(i).getStanje());
d.setArguments(b);
} else {
mValues.get(i).setStanje("koncano");
}
}
});
AlertDialog alertDialog = adb.create();
alertDialog.setCancelable(true);
alertDialog.show();
return true;
}
});
}
#Override
public int getItemCount() {
return mValues.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public final View mView;
public final TextView mContentView;
public final TextView mDateView;
public long id;
public Aktivnost_ mItem;
public ViewHolder(View view) {
super(view);
mView = view;
this.id = id;
mDateView = (TextView) view.findViewById(R.id.Date);
mContentView = (TextView) view.findViewById(R.id.content);
}
#Override
public String toString() {
return super.toString() + " '" + mContentView.getText() + "'";
}
}
}
And i want to get the value i set in bundle in this fragment.
Fragment.java
public class DoingFragment extends Fragment {
DoingFragmentRecyclerViewAdapter mAdapter;
private OnListFragmentInteractionListener mListener;
public DoingFragment() {
}
#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.fragment_doingfragment_list, container, false);
RecyclerView recyclerView = (RecyclerView) view.findViewById(R.id.list_doing);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
recyclerView.addItemDecoration(new DividerItemDecoration(getContext(), LinearLayoutManager.VERTICAL));
mAdapter = new DoingFragmentRecyclerViewAdapter(listAktivnosti(),mListener);
recyclerView.setAdapter(mAdapter);
return view;
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnListFragmentInteractionListener) {
mListener = (OnListFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnListFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnListFragmentInteractionListener {
void onListFragmentInteraction1(Aktivnost_ item);
}
AppDatabase db;
public void openDB() {
db = new AppDatabase(getContext());
db.open();
}
Aktivnost_ ak;
List<Aktivnost_> array;
public List<Aktivnost_> listAktivnosti() {
array = new ArrayList<>();
openDB();
Bundle b = getArguments();
Cursor cursor = db.getAllRows(b.getString("doing"));
while(cursor.moveToNext()) {
ak = new Aktivnost_();
ak.setId_(cursor.getLong(cursor.getColumnIndex("_id")));
ak.setNaziv(cursor.getString(cursor.getColumnIndex("naziv")));
ak.setDatum(cursor.getString(cursor.getColumnIndex("datum")));
ak.setFk_projekt(cursor.getInt(cursor.getColumnIndex("fk_projekt")));
ak.setUdeleženci(cursor.getString(cursor.getColumnIndex("udelezenci")));
ak.setStanje(cursor.getString(cursor.getColumnIndex("stanje")));
array.add(ak);
}
return array;
}
}
From the code, I can see you are only setting the Bundle parameters in Fragment object, but not using that fragment object further.
You need to display that fragment object first, then it will reflect into your target fragment.
Am looking to create a fragment conaining listview by retriveing data from firebase database.This listview gets cards having buttons and seekbar. All I want is to have a global variable listen to these buttons. I tried creating onClicklistener in the fragment itself but wasn't successful.Then I created onClicklistener for these buttons on the Adapter itself which was working. Now when I use the buttonclick to create a Toast, the Toast string is coming up as I expect. But the problem is that I want this Toasted string to store somewhere like global variable so that I could use it in another fragment as well. So I used:
String alpha = ((MyApplication) getContext()).getCartitem();
((MyApplication)getContext()).setCartitem("XYZ");
inside my adapter class's on Click Listener itself but the application crashes showing error log "First cannot be cast to com.fastfrooot.fastfrooot.MyApplication". First being my Activity containing Fragment and MyApplication is the class extending application.
MyApplication.java
package com.fastfrooot.fastfrooot;
import android.app.Application;
import android.widget.Button;
public class MyApplication extends Application {
private boolean[] cartsitem = {
false,
false,
false,
false,
false,
false
};
private String orderitem;
private String pkname;
private boolean oncomp = false;
private Button[] cartbuttons = new Button[20];
private String cartitem = "Alpha";
public boolean[] getcartsitem() {
return cartsitem;
}
public void setcartsitem(boolean[] cartsitem) {
this.cartsitem = cartsitem;
}
public String getorderitem() {
return orderitem;
}
public void setorderitem(String orderitem) {
this.orderitem = orderitem;
}
public String getpkname() {
return pkname;
}
public void setpkname(String pkname) {
this.pkname = pkname;
}
public boolean getoncomp() {
return oncomp;
}
public void setoncomp(boolean oncomp) {
this.oncomp = oncomp;
}
public Button[] getcartbuttons() {
return cartbuttons;
}
public void setCartbuttons(Button[] cartbuttons) {
this.cartbuttons = cartbuttons;
}
public String getCartitem() {
return cartitem;
}
public void setCartitem(String cartitem) {
this.cartitem = cartitem;
}
}
public class CustomListAdapterfir extends ArrayAdapter < Cardfir > {
private static final String TAG = "CustomListAdapter";
private Context mContext;
private int mResource;
private int lastPosition = -1;
private int procount;
String Cartkeitem;
private static class ViewHolder {
TextView title;
ImageView image;
TextView Status;
Button cartbutton;
SeekBar seekbar;
}
public CustomListAdapterfir(Context context, int resource, List < Cardfir > objects) {
super(context, resource, objects);
mContext = context;
mResource = resource;
//sets up the image loader library
setupImageLoader();
}
#NonNull
#Override
public View getView(int position, View convertView, ViewGroup parent) {
//get the persons information
final String title = getItem(position).getTitle();
String imgUrl = getItem(position).getImgURL();
final String Status = getItem(position).getStatus();
Button cartbutton = getItem(position).getCartbutton();
final SeekBar seekBar = getItem(position).getSeekbar();
try {
//create the view result for showing the animation
final View result;
//ViewHolder object
final ViewHolder holder;
if (convertView == null) {
LayoutInflater inflater = LayoutInflater.from(mContext);
convertView = inflater.inflate(mResource, parent, false);
holder = new ViewHolder();
holder.title = (TextView) convertView.findViewById(R.id.cardTitle);
holder.Status = (TextView) convertView.findViewById(R.id.cardstat);
holder.image = (ImageView) convertView.findViewById(R.id.cardImage);
holder.seekbar = (SeekBar) convertView.findViewById(R.id.seekBarf);
holder.cartbutton = (Button) convertView.findViewById(R.id.Addbutton);
result = convertView;
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
result = convertView;
}
lastPosition = position;
holder.title.setText(title);
holder.Status.setText(Status);
holder.cartbutton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
int seekerpos = holder.seekbar.getProgress() + 1;
Cartkeitem = title + " " + String.valueOf(seekerpos);
Toast.makeText(mContext, Cartkeitem, Toast.LENGTH_SHORT).show();
String alpha = ((MyApplication) getContext()).getCartitem();
((MyApplication) getContext()).setCartitem("XYZ");
}
});
holder.seekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
//create the imageloader object
ImageLoader imageLoader = ImageLoader.getInstance();
int defaultImage = mContext.getResources().getIdentifier("#drawable/logo", null, mContext.getPackageName());
DisplayImageOptions options = new DisplayImageOptions.Builder().cacheInMemory(true)
.cacheOnDisc(true).resetViewBeforeLoading(true)
.showImageForEmptyUri(defaultImage)
.showImageOnFail(defaultImage)
.showImageOnLoading(defaultImage).build();
imageLoader.displayImage(imgUrl, holder.image, options);
return convertView;
} catch (IllegalArgumentException e) {
Log.e(TAG, "getView: IllegalArgumentException: " + e.getMessage());
return convertView;
}
}
private void setupImageLoader() {
DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder()
.cacheOnDisc(true).cacheInMemory(true)
.imageScaleType(ImageScaleType.EXACTLY)
.displayer(new FadeInBitmapDisplayer(300)).build();
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(
mContext)
.defaultDisplayImageOptions(defaultOptions)
.memoryCache(new WeakMemoryCache())
.discCacheSize(100 * 1024 * 1024).build();
ImageLoader.getInstance().init(config);
}
}
public class Tab1fragment extends Fragment implements View.OnClickListener {
private static final String TAG = "TAG1 fragment";
private ListView mListView;
DatabaseReference Complete = FirebaseDatabase.getInstance().getReference();
DatabaseReference Products = Complete.child("Products");
ValueEventListener productlistener;
final ArrayList < Cardfir > list = new ArrayList < Cardfir > ();
String productname;
String producttype;
final ArrayList < Button > Cartbuttons = new ArrayList < Button > ();
final ArrayList < SeekBar > Seekbars = new ArrayList < SeekBar > ();
int productnumber = -1;
Button[] Cartsbut = new Button[20];
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.tab1_fragment, container, false);
mListView = (ListView) view.findViewById(R.id.listview);
productlistener = Products.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (final DataSnapshot delphi: dataSnapshot.getChildren()) {
productnumber = productnumber + 1;
productname = delphi.child("Name").getValue().toString();
producttype = delphi.child("Type").getValue().toString();
list.add(new Cardfir("drawable://" + R.drawable.trans, productname, producttype));
}
CustomListAdapterfir adapter = new CustomListAdapterfir(getActivity(), R.layout.card_layout_liveorder, list);
mListView.setAdapter(adapter);
Products.removeEventListener(productlistener);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
return view;
}
#Override
public void onClick(View view) {
Toast.makeText(getContext(), "HI", Toast.LENGTH_SHORT).show();
}
}
I have main activity which contains fragments. One of the fragment is calling dialogFragment for new item entry. This new item is specified by Serializable class.
Just to be more specific:
item.java
public class Item implements Serializable {
private String mTitle;
private String mDescription;
private Boolean mTrue;
//getters and setters
public String getTitle() {
return mTitle;
}
public void setTitle(String mTitle) {
this.mTitle = mTitle;
}
public String getDescription() {
return mDescription;
}
public void setDescription(String mDescription) {
this.mDescription = mDescription;
}
public Boolean isTrue() {
return mTrue;
}
public void setTrue(Boolean mTrue) {
this.mTrue = mTrue;
}
}
DialogNewItem
public class DialogNewItem extends DialogFragment {
//filters state holder
Boolean isTrue = false;
//filters state end
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState){
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
View dialogView = inflater.inflate(R.layout.new_item, null);
final EditText editTitle = (EditText) dialogView.findViewById(R.id.editTitle);
final EditText editDescription = (EditText) dialogView.findViewById(R.id.editDescription)
//filter icons
final ImageView ivIsTrue = (ImageView) dialogView.findViewById(R.id.filterTrue);
//filter icons end
//onClickListener for filter icons
ivIsTrue.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
if (isTrue == false) {
ivIsTrue.setBackgroundResource(R.drawable.border_white);
ivIsTrue.setImageResource(R.drawable.true_white);
isTrue = true;
} else {
ivIsTrue.setBackgroundResource(R.drawable.border_green);
ivIsTrue.setImageResource(R.drawable.true_green);
isTrue = false;
}
}
});
Button btnCancel = (Button) dialogView.findViewById(R.id.btnCancel);
Button btnOK = (Button) dialogView.findViewById(R.id.btnOK);
builder.setView(dialogView);
//cancel button
btnCancel.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
dismiss();
}
});
//give button
btnOK.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//new item
final Item newItem = new Item();
//Set its variables to match the users entries on the form
newItem.setTitle(editTitle.getText().toString());
newItem.setDescription(editDescription.getText().toString());
newItem.setTrue(isTrue);
dismiss();
}
});
return builder.create();
}
}
Now, I want to pass newItem from DialogNewItem (btnOK) to a listView Fragment. In other words I want to make a listView Fragment which will contain all the new items created in DialogNewItem.
I was trying different methods (set/getFragment, ArrayList, different interfaces, etc) but some how non of it works. I have no problem with passing newItem to listView in an activity:
//get the reference to dashboard
Dashboard callingActivity = (Dashboard) getActivity();
//pass new item back to dashboard
callingActivity.createNewItem(newItem);
and then dashboard activity:
public class Dashboard extends AppCompatActivity {
private ItemAdapter mItemAdapter;
public void createNewItem(Item n) {
mItemAdapter.addItem(n);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dashboard);
mItemAdapter = new ItemAdapter();
ListView listItem = (ListView) findViewById(R.id.listView);
listItem.setAdapter(mItemAdapter);
}
//handle clicks on listView
listItem.setOnItemClickListener(new AdapterView.OnItemClickListener(){
#Override
public void onItemClick (AdapterView<?> adapter, View view, int whichItem, long id ){
//creating temporary item which is reference to the clicked item
Item tempItem = mItemAdapter.getItem(whichItem);
//new dialog window
DialogShowItem dialog = new DialogShowItem();
//send reference to the item to be shown
dialog.sendItemSelected(tempItem);
//show the dialog window with the item
dialog.show(getFragmentManager(),"");
}
});
#Override
public View getView(int whichItem, View view, ViewGroup viewGroup){
//has been inflated already
if (view==null){
//creating layout inflater
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
//instantiate view by inflating inflater (listItem layout)
view = inflater.inflate(R.layout.listitem, viewGroup, false);
}
Item tempItem = itemList.get(whichItem);
//grabbing the refrence to all variables
TextView txtTitle = (TextView) view.findViewById(R.id.txtTitle);
TextView txtDescription = (TextView) view.findViewById(R.id.txtDescription);
ImageView ivTrue = (ImageView) view.findViewById(R.id.imgSmTrue);
//setting text variables
txtTitle.setText(tempItem.getTitle());
txtDescription.setText(tempItem.getDescription());
//hide not relevant images
if (!tempItem.isTrue()){
ivTrue.setVisibility(View.INVISIBLE);
} else {ivTrue.setVisibility(View.VISIBLE);}
//category with different image src
return view;
}
and everything works perfectly, but when I want to do the same with Fragment instead of Activity, somehow I cannot make it work.
I would appreciate any help. Thanx
Fragment (with listview):
public class ListItems extends ListFragment {
private ItemAdapter mItemAdapter;
public void createNewItem(Item i) {
mItemAdapter.addItem(i);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstatceState) {
View view = inflater.inflate(R.layout.list_items, container, false);
//Item adapter
mItemAdapter = new ItemAdapter();
final ListView listItems = (ListView) view.findViewById(R.id.listView);
listItems.setAdapter(mItemAdapter);
//floating give button
FloatingActionButton fab = (FloatingActionButton) view.findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
DialogNewItem dialog = new DialogNewItem();
dialog.show(getFragmentManager(), "");
}
});
//handle clicks on itemList
listItems.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int whichItem, long id) {
Item tempItem = mItemAdapter.getItem(whichItem);
DialogShowItem dialog = new DialogShowItem();
dialog.sendItemSelected(tempItem);
dialog.show(getFragmentManager(), "");
}
});
return view;
}
#Override
protected void onPause() {
super.onPause();
mItemAdapter.saveItems();
}
public class ItemAdapter extends BaseAdapter {
List<Item> itemList = new ArrayList<Item>();
private JSONSerializer mSerializer;
public ItemAdapter() {
mSerializer = new JSONSerializer("myProject.json", getActivity().getApplicationContext());
try {
itemList = mSerializer.load();
} catch (Exception e) {
itemList = new ArrayList<Item>();
Log.e("Error loading items: ", "", e);
}
}
public void saveItems() {
try {
mSerializer.save(itemList);
} catch (Exception e) {
Log.e("Error saving items: ", "", e);
}
}
#Override
public int getCount() {
return itemList.size();
}
#Override
public Item getItem(int whichItem) {
return itemList.get(whichItem);
}
#Override
public long getItemId(int whichItem) {
return whichItem;
}
public void addItem(Item n) {
itemList.add(n);
notifyDataSetChanged();
}
#Override
public View getView(int whichItem, View view, ViewGroup viewGroup) {
if (view==null) {
LayoutInflater inflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.list_items, viewGroup, false);
}
Item tempItem = itemList.get(whichItem);
TextView txtTitle = (TextView) view.findViewById(R.id.txtTitle);
TextView txtDescription = (TextView) view.findViewById(R.id.txtDescription);
ImageView ivTrue = (ImageView) view.findViewById(R.id.imgSmTrue);
//setting text variables
txtTitle.setText(tempItem.getTitle());
txtDescription.setText(tempItem.getDescription());
//hide irrelevant images
if (!tempItem.isTrue()){
ivTrue.setVisibility(View.INVISIBLE);
} else {ivTrue.setVisibility(View.VISIBLE);}
return view;
}
}
}
It's a drawer activity so I'm showing it after drawer item click:
private void switchFragment(int position) {
Fragment fragment = null;
String fragmentID = "";
switch (position) {
case 0:
fragmentID = "LISTITEMS";
fragment = new ListItems();
break;
case 1:
fragmentID = "PROFILE";
fragment = new Profile();
break;
default:
break;
}
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.fragmentHolder, fragment, fragmentID).commit();
//close the drawer
mDrawerLayout.closeDrawer(mNavDrawerList);
}
You can make a public method in ListItems fragment class in which you receive an Item class object and add it in adapter. And then inside your DialogNewItem Fragment, On OK Button click, you can search the ListItems using SupportFragmentManager by using its tag and call the public method you wrote.
The following code might help you.
DialogNewItem class
btnOK.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//new item
final Item newItem = new Item();
//Set its variables to match the users entries on the form
newItem.setTitle(editTitle.getText().toString());
newItem.setDescription(editDescription.getText().toString());
newItem.setTrue(isTrue);
FragmentManager manager = getActivity().getSupportFragmentManager();
ListItems fragment = (ListItems)manager.findFragmentByTag("LISTITEMS");
if(fragment != null){
fragment.createNewItem(newItem);
}
dismiss();
}
});
In your ListItems fragment the following code will depict an ItemAdapter as the data member of the ListViewFragment class and below that is the method you can call to add the item in the adapter.
private ItemAdapter mItemAdapter;
public void createNewItem(Item n) {
mItemAdapter.addItem(n);
}