RecyclerView save elements in JSON - android

I have recyclerview (in fragment) and fragment with details information to one of the element. All is good, but when my data was saved. I have bad results in my JSON file. All times when i open element of list he add new element inside JSON file, while he must overwrite oneself.
My Activity
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.start_page_activity);
Log.i("MainActivity", "onCreate");
if(savedInstanceState==null) {
getFragment(new ObjectListFragment());
}
}
public void getFragment(Fragment fragment) {
FragmentManager fm = getSupportFragmentManager();
Fragment mFragment = fm.findFragmentById(R.id.fragment_container);
if (mFragment == null) {
mFragment = fragment;
fm.beginTransaction()
.add(R.id.fragment_container, mFragment)
.commit();
}
if (mFragment != null) {
mFragment = fragment;
fm.beginTransaction().addToBackStack(null)
.replace(R.id.fragment_container, mFragment)
.commit();
}
}
}
My Model:
public class Object {
private static final String JSON_ID = "id";
private static final String JSON_TITLE = "title";
private UUID mId;
private String mTitle;
public Object() {
mId=UUID.randomUUID();
}
public Object(JSONObject json) throws JSONException {
mId = UUID.fromString(json.getString(JSON_ID));
mTitle = json.getString(JSON_TITLE);
}
public JSONObject toJSON()throws JSONException{
JSONObject json = new JSONObject();
json.put(JSON_ID, mId.toString());
json.put(JSON_TITLE, mTitle);
return json;
}
public UUID getId() {
return mId;
}
public String getTitle() {
return mTitle;
}
public void setTitle(String title) {
mTitle = title;
}
#Override
public String toString() {
return mTitle;
}
}
ObjectLab:
public class ObjectLab {
private static final String TAG = "ObjectLab";
private static final String FILENAME = "reminder.json";
private ObjectJSON mSerializer;
private ArrayList<Object> mObjects;
private static ObjectLab sObjectLab;
private Context mContext;
private ObjectLab(Context context){
mContext = context;
mSerializer = new ObjectJSON(mContext, FILENAME);
try {
mObjects = mSerializer.loadReminders();
} catch (Exception e) {
mObjects = new ArrayList<Object>();
Log.e(TAG, "Error loading crimes: ", e);
}
}
public static ObjectLab get(Context c){
if(sObjectLab == null){
sObjectLab = new ObjectLab(c.getApplicationContext());
}
return sObjectLab;
}
public ArrayList<Object> getObjects(){
return mObjects;
}
public Object getReminder(UUID id){
for(Object c : mObjects){
if(c.getId().equals(id))
return c;
}
return null;
}
public void addReminder(Object c){
mObjects.add(0,c);
}
public void deleteReminder(Object c){
mObjects.remove(c);
}
public boolean saveReminders(){
try{
mSerializer.saveReminders(mObjects);
Log.d(TAG, "reminders saved to file");
return true;
}catch (Exception e){
Log.e(TAG, "Error saving crimes: ", e);
return false;
}
}
ObjectJSON:
public class ObjectJSON {
private Context mContext;
private String mFilename;
public ObjectJSON(Context context, String filename) {
mContext = context;
mFilename = filename;
}
public void saveReminders(ArrayList<Object> objects) throws JSONException, IOException {
Log.i("Save","saveReminders");
JSONArray array = new JSONArray();
for (Object f : objects)
array.put(f.toJSON());
Writer writer = null;
try {
OutputStream out = mContext.openFileOutput(mFilename, Context.MODE_APPEND);
writer = new OutputStreamWriter(out);
writer.write(array.toString());
} finally {
if (writer != null)
writer.close();
}
}
public ArrayList<Object> loadReminders() throws IOException, JSONException {
Log.i("Save","loadReminders");
ArrayList<Object> objects = new ArrayList<Object>();
BufferedReader reader = null;
try {
InputStream in = mContext.openFileInput(mFilename);
reader = new BufferedReader(new InputStreamReader(in));
StringBuilder jsonString = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
jsonString.append(line);
}
JSONArray array = (JSONArray) new JSONTokener(jsonString.toString())
.nextValue();
for (int i = 0; i < array.length(); i++) {
objects.add(new Object(array.getJSONObject(i)));
}
} catch (FileNotFoundException e) {
//when 0
} finally {
if (reader != null)
reader.close();
}
return objects;
}
ObjectListFragment:
public class ObjectListFragment extends Fragment {
private RecyclerView mRecyclerView;
private RecyclerView.LayoutManager mLayoutManager;
private RecyclerAdapter mAdapter;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.reminder_activity, container, false);
Log.i("ObjectListFragment", "onCreateView");
final ArrayList<Object> mData = ObjectLab.get(getActivity()).getObjects();
getActivity().setTitle("Object");
mRecyclerView = (RecyclerView)v. findViewById(R.id.my_recycler_view);
//registerForContextMenu(mRecyclerView);
mRecyclerView.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(getActivity());
mRecyclerView.setLayoutManager(mLayoutManager);
mAdapter = new RecyclerAdapter(mData);
mRecyclerView.setAdapter(mAdapter);
mRecyclerView.addOnItemTouchListener(new RecyclerItemClickListener(v.getContext(), new RecyclerItemClickListener.OnItemClickListener() {
#Override
public void onItemClick(View view, int position) {
Log.i("ObjectListFragment", "onItemClick");
Object f = mData.get(position);
FragmentManager fm = getFragmentManager();
Fragment mFragment = fm.findFragmentById(R.id.fragment_container);
Bundle bundle = new Bundle();
bundle.putSerializable(ObjectFragment.EXTRA_REMINDER_ID, f.getId());
if (mFragment != null) {
mFragment = new ObjectFragment();
mFragment.setArguments(bundle);
fm.beginTransaction().addToBackStack(null)
.replace(R.id.fragment_container, mFragment)
.commit();
}
}
}));
return v;
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.menu_main, menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
Log.d("Testing", "ID == " + id);
switch (id) {
case R.id.action_settings: {
Log.d("onOptionsItemSelected", " SETTings");
Object f = new Object();
ObjectLab.get(getActivity()).addReminder(f);
FragmentManager fm = getFragmentManager();
Fragment mFragment = fm.findFragmentById(R.id.fragment_container);
Bundle bundle = new Bundle();
bundle.putSerializable(ObjectFragment.EXTRA_REMINDER_ID, f.getId());
if (mFragment != null) {
mFragment = new ObjectFragment();
mFragment.setArguments(bundle);
fm.beginTransaction().addToBackStack(null)
.replace(R.id.fragment_container, mFragment)
.commit();
}
return true;
}
}
return super.onOptionsItemSelected(item);
}
}
RecyclerAdapter:
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.ViewHolder> {
ArrayList<Object> mData;
public RecyclerAdapter(ArrayList<Object> objects) {
mData = objects;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.reminder_item, parent, false);
return new ViewHolder(v);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.mTitleTextView.setText(mData.get(position).getTitle());
}
#Override
public int getItemCount() {
return mData.size();
}
public static class ViewHolder extends RecyclerView.ViewHolder {
private TextView mTitleTextView;
public ViewHolder(View itemView) {
super(itemView);
mTitleTextView = (TextView) itemView.findViewById(R.id.forget_list_titleTextView);
}
}
RecyclerItemClickListener:
public class RecyclerItemClickListener implements RecyclerView.OnItemTouchListener {
private OnItemClickListener mListener;
public interface OnItemClickListener {
public void onItemClick(View view, int position);
}
GestureDetector mGestureDetector;
public RecyclerItemClickListener(Context context, OnItemClickListener listener) {
mListener = listener;
mGestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
#Override public boolean onSingleTapUp(MotionEvent e) {
return true;
}
});
}
#Override
public boolean onInterceptTouchEvent(RecyclerView view, MotionEvent e) {
View childView = view.findChildViewUnder(e.getX(), e.getY());
if (childView != null && mListener != null && mGestureDetector.onTouchEvent(e)) {
mListener.onItemClick(childView, view.getChildLayoutPosition(childView));
return true;
}
return false;
}
#Override
public void onTouchEvent(RecyclerView view, MotionEvent motionEvent) { }
#Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
and last ObjectFragmet
public class ObjectFragment extends Fragment{
public static final String EXTRA_REMINDER_ID = "id";
private Object mObject;
public static ObjectFragment newInstance(UUID crimeId) {
Log.i("ObjectFragment", "newInstance");
Bundle args = new Bundle();
args.putSerializable(EXTRA_REMINDER_ID, crimeId);
ObjectFragment fragment = new ObjectFragment();
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
UUID uuid = (UUID) getArguments().getSerializable(EXTRA_REMINDER_ID);
Log.i("ObjectFragment", " "+uuid);
mObject = ObjectLab.get(getContext()).getReminder(uuid);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.remind_act, container, false);
EditText editText = (EditText)v.findViewById(R.id.editText1);
editText.setText(mObject.getTitle());
editText.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
mObject.setTitle(charSequence.toString());
}
#Override
public void afterTextChanged(Editable editable) {
}
});
return v;
}
#Override
public void onPause() {
super.onPause();
Log.i("ObjectFragment", "onPause");
ObjectLab.get(getActivity()).saveReminders();
}
Links to the project(Android Studio).
Where my problem is that I do not. With pleasure hear all your comments and advice on the topic as well as that off-topic.
Your help will not forsake unattended.

When opening the OutputStream for writing into the file, you're using the Context.MODE_APPEND flag, which is causing the write operation to append and not overwrite as you intended, change it to:
OutputStream out = mContext.openFileOutput(mFilename, 0);
Also, there was no need to mention the RecyclerView at all, since it has nothing to do with the problem at hand.

Related

how to change value every time when passing it through bundle from container activity to fragment

This is my MediaTab.java Activity and it has fragment TabImage.
public class MediaTab extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener,
TabImage.OnFragmentInteractionListener,
TabPdf.OnFragmentInteractionListener {
Toolbar toolbar;
HashMap<String, String> groupName;
private ArrayList<String> groupNameArray;
Spinner group;
UserService userService;
SharedPreferences.Editor sharedPref;
String groupIdString;
private String TAG = MediaTab.class.getSimpleName();
ViewPager viewPager;
TabImage obj;
#SuppressLint("CommitPrefEdits")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_media_tab);
toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
sharedPref = getSharedPreferences(getPackageName(), Context.MODE_PRIVATE).edit();
groupNameArray = new ArrayList<>();
userService = ApiUtils.getUserService();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle("Media");
group = findViewById(R.id.groupspinner);
groupName = new HashMap<>();
viewPager = findViewById(R.id.viewpager);
TabLayout tabLayout = findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
getCategories();
group.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
groupIdString = groupName.get(groupNameArray.get(position));
Log.d(TAG, "onItemClick:valueID " + groupIdString);
Bundle bundle = new Bundle();
bundle.putString("params", groupIdString);
obj = new TabImage();
obj.setArguments(bundle);
setupViewPager(viewPager);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(obj, "MEDIA");
adapter.addFragment(new TabPdf(), "FILE");
viewPager.setAdapter(adapter);
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
return false;
}
#Override
public void onFragmentInteraction(Uri uri) {
}
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
private void getCategories() {
Call<CreatePostList> userServicePost = userService.getschema(App.getToken());
userServicePost.enqueue(new Callback<CreatePostList>() {
#Override
public void onResponse(Call<CreatePostList> call, Response<CreatePostList> response) {
if (response.isSuccessful()) {
CreatePostList createPostList = response.body();
List<Group> groups;
groups = createPostList.getGroups();
for (int j = 0; j < groups.size(); j++) {
groupName.put(groups.get(j).getName(), groups.get(j).getId());
}
Set<String> strings1 = groupName.keySet();
ArrayList<String> arrayList1 = new ArrayList<>();
arrayList1.addAll(strings1);
groupNameArray = arrayList1;
SpinnerMediaAdapter customAdapter2 = new SpinnerMediaAdapter(getApplicationContext(), R.layout.spinnertems_layout, R.id.spinnertems_text, groupNameArray);
group.setAdapter(customAdapter2);
// if(groupNameArray.size() > 0) {
// groupIdString = groupName.get(groupNameArray.get(0));
// Log.d(TAG, "onResponse: .... setting at load " + groupIdString);
// Bundle bundle = new Bundle();
// bundle.putString("params", groupIdString);
// TabImage myObj = new TabImage();
// myObj.setArguments(bundle);
// }
// setupViewPager(viewPager);
}
}
#Override
public void onFailure(Call<CreatePostList> call, Throwable t) {
Toast.makeText(MediaTab.this, "Something went wrong", Toast.LENGTH_SHORT).show();
}
});
}
This is my fragment "TabImage" where i am getting bundle.
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_tab_image, container, false);
if (getArguments() != null) {
myDataFromActivity = getArguments().getString("params");
Log.d(TAG, "onCreate: tab activity " + myDataFromActivity);
}
mRecyclerView = view.findViewById(R.id.tabimgrv);
mRecyclerView.setFitsSystemWindows(true);
mRecyclerView.setHasFixedSize(true);
progressBar = view.findViewById(R.id.myprog);
userService = ApiUtils.getUserService();
activity = (MediaTab) getActivity();
GridLayoutManager manager = new GridLayoutManager(this.getActivity(), 2, GridLayoutManager.VERTICAL, false);
mRecyclerView.setLayoutManager(manager);
getPostList(currentPage);
mRecyclerView.addOnScrollListener(new PaginationMediaScrolling(manager) {
#Override
protected void loadMoreItems() {
Log.d("TabImage :", "loadMoreItems() called");
if (!isLastPage()) {
{
isLoading = true;
currentPage = currentPage + 1;
loadNextpage(currentPage);
}
}
}
#Override
public int getTotalPageCount() {
return TOTAL_PAGES;
}
#Override
public boolean isLastPage() {
return isLastPage;
}
#Override
public boolean isLoading() {
return isLoading;
}
});
return view;
}
private void getPostList(int currentPage) {
// progressBar.setVisibility(View.VISIBLE);
Call<GetImage> userServicePost = userService.getMediaImage(App.getToken(), myDataFromActivity, currentPage);
userServicePost.enqueue(new Callback<GetImage>() {
#Override
public void onResponse(Call<GetImage> call, Response<GetImage> response) {
// progressBar.setVisibility(View.GONE);
if (response.isSuccessful()) {
GetImage getImagemodel = response.body();
TOTAL_PAGES = totalPages(response);
Media media = getImagemodel.getMedia();
List<ResultMedia> resultMediaList = media.getResults();
mAdapter = new TabImageAdapter(getContext(), resultMediaList);
mRecyclerView.setAdapter(mAdapter);
if (currentPage <= TOTAL_PAGES) mAdapter.addLoadingFooter();
else isLastPage = true;
isLoading = false;
} else {
Toast.makeText(context, "Could not complete the request! Please try again.", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(Call<GetImage> call, Throwable t) {
}
});
}
how to change "myDataFromActivity" every time when i select value from spinner. and how to pass this changed value through bundle
Because groupid is dynamic value which will change every time

How to pass an Object from one fragment to other fragment

I want to pass my total entity (Incidencia) who is created in One fragment and pass it to another fragment who will show a list of each entity added before. Both fragments are inside of one Activity. Im using recyclerview to list the entities and this entity implements parcelable.
This is the main activity who contain both fragments
public class MainActivity extends ActionBarActivity implements IngresoIncidenciaTroncalFragment.OnButtonClickedListener{
DrawerLayout mDrawerLayout;
NavigationView mNavigationView;
FragmentManager mFragmentManager;
FragmentTransaction mFragmentTransaction;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Toolbar mitoolbar = (Toolbar) findViewById(R.id.toolbar);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
mNavigationView = (NavigationView) findViewById(R.id.shitstuff) ;
setSupportActionBar(mitoolbar);
mNavigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
mDrawerLayout.closeDrawers();
if (menuItem.getItemId() == R.id.nav_item_ingresoIncidencia) {
FragmentTransaction fragmentTransaction = mFragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.containerView,new IngresoIncidenciaTroncalFragment()).commit();
mitoolbar.setTitle("Ingreso Incidencia Troncal");
}
else if (menuItem.getItemId() == R.id.nav_item_listarIncidencia) {
FragmentTransaction fragmentTransaction = mFragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.containerView,new ListaIncidenciasTroncalFragment()).commit();
mitoolbar.setTitle("Lista Incidencias Troncal");
}
return false;
}
});
android.support.v7.widget.Toolbar toolbar = (android.support.v7.widget.Toolbar) findViewById(R.id.toolbar);
ActionBarDrawerToggle mDrawerToggle = new ActionBarDrawerToggle(this,mDrawerLayout, toolbar,R.string.app_name,
R.string.app_name);
mDrawerLayout.setDrawerListener(mDrawerToggle);
mDrawerToggle.syncState();
}
//THIS IS THE METHOD WHO DOESNT WORK
//WHAT CONTAINER DO I HAVE TO WRITE? THE ACTIVITY CONTAINER? OR FRAGMENT ONE OR TWO CONTAINERS?
#Override
public void onButtonClicked(Incidencia incidencia){
IngresoIncidenciaTroncalFragment fragment = new IngresoIncidenciaTroncalFragment();
Bundle args = new Bundle();
args.putParcelable("incident", incidencia);
fragment.setArguments(args);
getSupportFragmentManager().beginTransaction().replace(R.id.containerView, fragment).commit();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item){
int id = item.getItemId();
return super.onOptionsItemSelected(item);
}
}
This is the fragment who will add the entity
public class IngresoIncidenciaTroncalFragment extends Fragment implements
FechaDialog.DatePickerDialogFragmentEvents,HoraDialog.TimePickerDialogFragmentEvents ,FechaLlegadaDialog.DateLlegadaPickerDialogFragmentEvents{
private TextView mDateDisplay;
private TextView mTimeDisplay;
private Button botonAgregaIncidencia;
Context context;
private OnButtonClickedListener mListener;
private Spinner spinnerFallas;
public interface OnButtonClickedListener {
void onButtonClicked(Incidencia incidencia);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
/**
*Inflate ingresoincidenciastroncal and setup Views.
*/
final View x = inflater.inflate(R.layout.ingresoincidenciastroncal,null);
context = x.getContext();
mHoraLLegadaEstacion=(TextView)x.findViewById(R.id.tvHoraLLegadaEstacion);
mObservaciones=(TextView)x.findViewById(R.id.tvObservaciones);
mFechaSolucion=(TextView)x.findViewById(R.id.tvFechaSolucion);
mHoraSolucion=(TextView)x.findViewById(R.id.tvHoraSolucion);
//ADD ENTITY BUTTON
botonAgregaIncidencia=(Button) x.findViewById(R.id.btnAgregarIncidencia);
botonAgregaIncidencia.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//CREATING NEW ENTITY(Incidencia)
Incidencia incidencia = new Incidencia();
incidencia.setFechaRegistro(mDateDisplay.toString());
incidencia.setHoraSolucion(mTimeDisplay.toString());
incidencia.setTipoFalla(spinnerFallas.getPrompt().toString());
//NEW ENTITY AS PAREMETER
mListener.onButtonClicked(incidencia);
}
});
return x;
}
}
This is the fragment who will show the list of entities
public class ListaIncidenciasTroncalFragment extends Fragment {
Context context;
GestureDetector detector;
private RecyclerView rvListaIncidencias;
private ListaIncidenciasTroncalAdapter mlistaIncidenciasTroncalAdapter;
public ListaIncidenciasTroncalFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View x = inflater.inflate(R.layout.listaincidenciastroncalfragment,null);
context = x.getContext();
detector = new GestureDetector(getActivity(), new RecyclerViewOnGestureListener());
rvListaIncidencias=(RecyclerView)x.findViewById(R.id.rv_listaIncidenciasTroncal);
rvListaIncidencias.setLayoutManager(new LinearLayoutManager(getContext()));
mlistaIncidenciasTroncalAdapter = new ListaIncidenciasTroncalAdapter();
rvListaIncidencias.setAdapter(mlistaIncidenciasTroncalAdapter);
//HERE I SUPPOSE TO GET OBJECT CREATED FROM FRAGMENTONE
Bundle args = getArguments();
Incidencia incidencia = args.getParcelable("incident");
mlistaIncidenciasTroncalAdapter.add(incidencia);
return x;
}
}
This is the recyclerview adapter
public class ListaIncidenciasTroncalAdapter extends RecyclerView.Adapter<ListaIncidenciasTroncalAdapter.ListaIncidenciasTroncalAdapterViewHolder>
{
private List<Incidencia> mLstIncidencia = new ArrayList<>();
//private OnItemClickListener listener;
public void add(Incidencia incidencia){
mLstIncidencia.add(incidencia);
notifyItemInserted(mLstIncidencia.size()-1);
}
#Override
public ListaIncidenciasTroncalAdapter.ListaIncidenciasTroncalAdapterViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.listaincidencias_item,parent,false);
ListaIncidenciasTroncalAdapterViewHolder mlistaIncidenciasTroncalAdapterViewHolder = new ListaIncidenciasTroncalAdapterViewHolder(view);
return mlistaIncidenciasTroncalAdapterViewHolder;
}
#Override
public void onBindViewHolder(ListaIncidenciasTroncalAdapter.ListaIncidenciasTroncalAdapterViewHolder holder, final int position) {
final Incidencia incidencia= mLstIncidencia.get(position);
holder.tv_FechaRegistro.setText("Registro: "+incidencia.getFechaRegistro()+" - "+incidencia.getHoraRegistro());
holder.tv_Falla.setText(incidencia.getTipoFalla());
holder.tv_Estacion.setText(incidencia.getNomEstacion());
holder.tv_FechaSolucion.setText("Solucion: "+incidencia.getFechaSolucion()+" - "+incidencia.getHoraSolucion());
}
#Override
public int getItemCount() {
return mLstIncidencia.size();
}
static class ListaIncidenciasTroncalAdapterViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
//private OnItemClickListener listener;
TextView tv_FechaRegistro, tv_Falla, tv_Estacion,tv_FechaSolucion;
LinearLayout linearLayout;
public DetalleIncidencia detalleincidencia;
public ListaIncidenciasTroncalAdapterViewHolder(View itemView) {
super(itemView);
tv_FechaRegistro= (TextView) itemView.findViewById(R.id.tvRegistro);
tv_Falla= (TextView) itemView.findViewById(R.id.tvFalla);
tv_Estacion= (TextView) itemView.findViewById(R.id.tvEstacion);
tv_FechaSolucion= (TextView) itemView.findViewById(R.id.tvSolucion);
final Context context = itemView.getContext();
//detalleincidencia=(DetalleIncidencia) itemView.findViewById(R.id.)
linearLayout=(LinearLayout) itemView.findViewById(R.id.linearItem);
}
#Override
public void onClick(View v) {
int pos = getAdapterPosition();
}
}}
And Finally this is the Entity (Incidencia)
public class Incidencia implements Parcelable {
private Integer id_incidencia;
private String FechaRegistroIncidencia;
private String NomRegistro;
private String FechaRegistro;;
private String HoraRegistro;
private int CodEstacion;
private String NomEstacion;
private int CodEquipo;
private String NomEquipo;
private String TipoFalla;
private int AtoramientoMoneda;
private int AtoramientoBillete;
private String HoraLlegadaEstacion;
private String Estado;
private String Observaciones;
private String FechaSolucion;
private String HoraSolucion;
public Integer getId_incidencia() {
return id_incidencia;
}
public void setId_incidencia(Integer id_incidencia) {
this.id_incidencia = id_incidencia;
}
public String getFechaRegistroIncidencia() {
return FechaRegistroIncidencia;
}
public void setFechaRegistroIncidencia(String fechaRegistroIncidencia) {
FechaRegistroIncidencia = fechaRegistroIncidencia;
}
public String getNomRegistro() {
return NomRegistro;
}
public void setNomRegistro(String nomRegistro) {
NomRegistro = nomRegistro;
}
public String getFechaRegistro() {
return FechaRegistro;
}
public void setFechaRegistro(String fechaRegistro) {
FechaRegistro = fechaRegistro;
}
public String getHoraRegistro() {
return HoraRegistro;
}
public void setHoraRegistro(String horaRegistro) {
HoraRegistro = horaRegistro;
}
public Integer getCodEstacion() {
return CodEstacion;
}
public void setCodEstacion(Integer codEstacion) {
CodEstacion = codEstacion;
}
public String getNomEstacion() {
return NomEstacion;
}
public void setNomEstacion(String nomEstacion) {
NomEstacion = nomEstacion;
}
public Integer getCodEquipo() {
return CodEquipo;
}
public void setCodEquipo(Integer codEquipo) {
CodEquipo = codEquipo;
}
public String getNomEquipo() {
return NomEquipo;
}
public void setNomEquipo(String nomEquipo) {
NomEquipo = nomEquipo;
}
public String getTipoFalla() {
return TipoFalla;
}
public void setTipoFalla(String tipoFalla) {
TipoFalla = tipoFalla;
}
public Integer getAtoramientoMoneda() {
return AtoramientoMoneda;
}
public void setAtoramientoMoneda(Integer atoramientoMoneda) {
AtoramientoMoneda = atoramientoMoneda;
}
public Integer getAtoramientoBillete() {
return AtoramientoBillete;
}
public void setAtoramientoBillete(Integer atoramientoBillete) {
AtoramientoBillete = atoramientoBillete;
}
public String getHoraLlegadaEstacion() {
return HoraLlegadaEstacion;
}
public void setHoraLlegadaEstacion(String horaLlegadaEstacion) {
HoraLlegadaEstacion = horaLlegadaEstacion;
}
public String getEstado() {
return Estado;
}
public void setEstado(String estado) {
Estado = estado;
}
public String getObservaciones() {
return Observaciones;
}
public void setObservaciones(String observaciones) {
Observaciones = observaciones;
}
public String getFechaSolucion() {
return FechaSolucion;
}
public void setFechaSolucion(String fechaSolucion) {
FechaSolucion = fechaSolucion;
}
public String getHoraSolucion() {
return HoraSolucion;
}
public void setHoraSolucion(String horaSolucion) {
HoraSolucion = horaSolucion;
}
public Incidencia(){}
protected Incidencia(Parcel in){
this.id_incidencia=in.readInt();;
this.FechaRegistroIncidencia=in.readString();
this.NomRegistro=in.readString();
this.FechaRegistro=in.readString();
this.HoraRegistro=in.readString();
this.CodEstacion=in.readInt();
this.NomEstacion=in.readString();
this.CodEquipo=in.readInt();
this.NomEquipo=in.readString();
this.TipoFalla=in.readString();
this.AtoramientoMoneda=in.readInt();
this.AtoramientoBillete=in.readInt();
this.HoraLlegadaEstacion=in.readString();
this.Estado=in.readString();
this.Observaciones=in.readString();
this.FechaSolucion=in.readString();
this.HoraSolucion=in.readString();
}
public static final Parcelable.Creator<Incidencia> CREATOR = new Parcelable.Creator<Incidencia>() {
#Override
public Incidencia createFromParcel(Parcel source) {
return new Incidencia(source);
}
#Override
public Incidencia[] newArray(int size) {
return new Incidencia[size];
}
};
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(this.FechaRegistro);
dest.writeString(this.HoraRegistro);
dest.writeString(this.TipoFalla);
dest.writeString(this.FechaSolucion);
dest.writeString(this.HoraSolucion);
dest.writeString(this.NomEstacion);
}
}
You put the parcelable here
IngresoIncidenciaTroncalFragment fragment = new IngresoIncidenciaTroncalFragment();
Bundle args = new Bundle();
args.putParcelable("incident", incidencia);
But within IngresoIncidenciaTroncalFragment, you never got them.
Also, be sure to check the nullability of the arguments.
Bundle args = getArguments();
if (args != null) {
Incidencia incidencia = args.getParcelable("incident");
} else {
Log.w("GetIncidencia", "Arguments expected, but missing");
}
Also, you are missing many fields from writeToParcel that are being read into Incidencia(Parcel in), the first of which do not match, and the rest are out of order.
If you want to pass data between Fragments, see
How to implement OnFragmentInteractionListener
Communicating with Other Fragments
If both fragments in one Activity you just can use FragmentManager#findFragmentByTag(String) or FragmentManager#findFragmentById(int id) to get other fragment instance and just call some public method on that fragment to set entity.
Note that you should use either some tag or some container id when adding this fragments in order to be able to get them.
Try the update the Fragment like this
public class IngresoIncidenciaTroncalFragment extends Fragment implements
FechaDialog.DatePickerDialogFragmentEvents,HoraDialog.TimePickerDialogFragmentEvents ,FechaLlegadaDialog.DateLlegadaPickerDialogFragmentEvents{
private TextView mDateDisplay;
private TextView mTimeDisplay;
private Button botonAgregaIncidencia;
Context context;
private OnButtonClickedListener mListener;
private Spinner spinnerFallas;
public interface OnButtonClickedListener {
void onButtonClicked(Incidencia incidencia);
}
#Override
public void onAttach(Context context) {
if (context instanceOf OnButtonClickedListener) {
mListener = (OnButtonClickedListener) context;
}
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
/**
*Inflate ingresoincidenciastroncal and setup Views.
*/
final View x = inflater.inflate(R.layout.ingresoincidenciastroncal,null);
context = x.getContext();
mHoraLLegadaEstacion=(TextView)x.findViewById(R.id.tvHoraLLegadaEstacion);
mObservaciones=(TextView)x.findViewById(R.id.tvObservaciones);
mFechaSolucion=(TextView)x.findViewById(R.id.tvFechaSolucion);
mHoraSolucion=(TextView)x.findViewById(R.id.tvHoraSolucion);
//ADD ENTITY BUTTON
botonAgregaIncidencia=(Button) x.findViewById(R.id.btnAgregarIncidencia);
botonAgregaIncidencia.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//CREATING NEW ENTITY(Incidencia)
Incidencia incidencia = new Incidencia();
incidencia.setFechaRegistro(mDateDisplay.toString());
incidencia.setHoraSolucion(mTimeDisplay.toString());
incidencia.setTipoFalla(spinnerFallas.getPrompt().toString());
//NEW ENTITY AS PAREMETER
if (mListener != null) {
mListener.onButtonClicked(incidencia);
}
}
});
return x;
}
}

Using searchview in actionbar in fragments

I am displaying a userlist and I am using serachview in my actionbar to search. When I am using the searchView in activity, it works fine but when I use it for fragment, searchview doesn't work. It does not search in the listview.
Below is my code.
UserListFragment.java
public class UsersListFragment extends Fragment {
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
Activity activity;
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private static final String TAG = "UsersListFragment";
private OnFragmentInteractionListener mListener;
private ListView listView;
private List<UserData> users;
private CustomAdapter adapter;
SharedPreferences.Editor preferenceEditor;
Timer myTimer;
View view;
ActionBar actionBar;
private static final String PREFRENCES_NAME = "setPreferences";
private ProgressDialog progressBar;
String partnerKeyValue;
/**
* 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 UsersListFragment.
*/
// TODO: Rename and change types and number of parameters
public static UsersListFragment newInstance(String param1, String param2) {
UsersListFragment fragment = new UsersListFragment();
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);
progressBar = new ProgressDialog(getActivity());
progressBar.setCancelable(false);
progressBar.setMessage("Loading...");
progressBar.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressBar.setProgress(0);
Log.i(TAG, "UsersListFragment onCreate");
users = new ArrayList<>();
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
SharedPreferences preferenceSettings = getActivity().getSharedPreferences(PREFRENCES_NAME,Context.MODE_PRIVATE);
preferenceEditor = preferenceSettings.edit();
preferenceEditor.putString("refresh","userlistview");
preferenceEditor.commit();
FirebaseUtil uts = new FirebaseUtil(getContext());
uts.startListeningNotification(Global.getInstance().ownerId, new CallBack() {
#Override
public void onCallback(Map<String, Object> response, String Success) {
Log.i(TAG, Success);
setHasOptionsMenu(true);
String partnerKey = (String) response.get("key");
if (partnerKey != null) {
Map<String, Object> typeCheck = (Map<String, Object>) response.get("value");
String type = (String) typeCheck.get("type");
if (type.equals("chat")) {
String key1 = Global.getInstance().ownerId;
String key2 = partnerKey;
partnerKeyValue = partnerKey;
if (key2 != null) {
String currentPartner = Global.getInstance().partnerId;
if (currentPartner.length() > 0) {
if (currentPartner.equals(partnerKey)) {
} else {
Global.getInstance().unreadMessageUsers.add(partnerKey);
}
Global.getInstance().unreadMessageUsers.add(partnerKey);
} else {
}
}
}
}
}
});
}
#Override
public void onStart() {
super.onStart();
Log.i(TAG, "UsersListFragment onStart");
}
#Override
public void onResume() {
super.onResume();
Log.i(TAG, "UsersListFragment onResume");
}
#Override
public void onPause() {
super.onPause();
Log.i(TAG, "UsersListFragment onStart");
}
#Override
public void onStop() {
super.onStop();
Log.i(TAG, "UsersListFragment onStop");
}
#Override
public void onDestroyView() {
super.onDestroyView();
}
#Override
public void onDestroy() {
super.onDestroy();
FirebaseUtil util = new FirebaseUtil(getContext());
util.updateUserStatus(Global.getInstance().ownerId, "4");
Log.i(TAG, "UsersListFragment onDestroy");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
actionBar = ((AppCompatActivity) getActivity()).getSupportActionBar();
if(actionBar!=null) {
actionBar.setDisplayUseLogoEnabled(true);
actionBar.setDisplayShowHomeEnabled(true);
actionBar.setDisplayHomeAsUpEnabled(false);
actionBar.setLogo(R.drawable.ic_logo);
ColorDrawable colorDrawable = new ColorDrawable(Color.parseColor("#006EAD"));
actionBar.setBackgroundDrawable(colorDrawable);
}
Toast.makeText(getActivity(), String.valueOf( Global.getInstance().unreadMessageUsers.size()) , Toast.LENGTH_SHORT).show();
int vd = users.size();
view = inflater.inflate(R.layout.fragment_userslist, container, false);
listView = (ListView) view.findViewById(R.id.userdisplay);
adapter = new CustomAdapter(getActivity(),R.layout.program_list, users );
listView.setAdapter(adapter);
if (users.size()==0){
usersList();
}else {
adapter.notifyDataSetChanged();
}
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
UserData data = users.get(position);
Global.getInstance().someData = data.getId();
Global.getInstance().partnerId = data.getId();
int i = 0;
for (Iterator<String> iter = Global.getInstance().unreadMessageUsers.iterator(); iter.hasNext(); ) {
String element = iter.next();
if (element.equals(data.getId().toString())) {
iter.remove();
}
}
data.setUnreadMessageCount(0);
users.remove(position);
users.add(position, data);
Toast.makeText(getActivity().getApplicationContext(),String.valueOf(Global.getInstance().unreadMessageUsers.size()),Toast.LENGTH_LONG).show();
Fragment fragmentOne = new ChatFragment();
android.support.v4.app.FragmentTransaction ft = getActivity().getSupportFragmentManager().beginTransaction();
Bundle args = new Bundle();
args.putString(ChatFragment.DATA_RECEIVE, data.getName());
fragmentOne .setArguments(args);
ft.addToBackStack(null);
ft.replace(R.id.framecontainerMain, fragmentOne).commit();
}
});
// Inflate the layout for this fragment
return view;
}
public void usersList () {
SharedPreferences preferenceSettings = getActivity().getSharedPreferences(PREFRENCES_NAME,Context.MODE_PRIVATE);
preferenceEditor = preferenceSettings.edit();
//get the data from userlist api
final String URL = "url";
String token = preferenceSettings.getString("authToken","");
final String userId = preferenceSettings.getString("userId","");
HashMap<String, String> params = new HashMap<String, String>();
params.put("user_id",userId);
params.put("auth_token",token);
progressBar.show();
JsonObjectRequest myRequest = new JsonObjectRequest(Request.Method.POST, URL,new JSONObject(params),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.i(TAG, "onResponse:" +response);
String success = null;
try {
success = response.getString("success");
} catch (JSONException e) {
e.printStackTrace();
}
if(success == "true") {
JSONArray Array = null;
try {
//get the users
} else {
users.add(data);
}
}
Log.i(TAG, "arraylist");
adapter.notifyDataSetChanged();
onlineUsers();
myTimer = new Timer();
myTimer.schedule(new TimerTask() {
#Override
public void run() {
TimerMethod();
}
}, 0, 5000);
progressBar.dismiss();
} catch (JSONException e) {
e.printStackTrace();
}
JSONObject Obj;
} else {
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progressBar.dismiss();
VolleyLog.e("Error: ", error.getMessage());
Log.i(TAG, "onErrorResponse:" +error.networkResponse);
}
});
ApplicationController.getInstance().addToRequestQueue(myRequest);
myRequest.setRetryPolicy(new DefaultRetryPolicy(
5000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
}
public void sortingArray(){
if (users.size()>0) {
synchronized (this) {
if (Global.getInstance().unreadMessageUsers.size() > 0) {
System.out.println("\nExample 3 - Count all with Map");
Map<String, Integer> map = new HashMap<String, Integer>();
for (String temp : Global.getInstance().unreadMessageUsers) {
Integer count = map.get(temp);
map.put(temp, (count == null) ? 1 : count + 1);
}
System.out.println("\nSorted Map");
Map<String, Integer> unreadCount = new TreeMap<String, Integer>(map);
for (String key : unreadCount.keySet()) {
int count_unread = unreadCount.get(key);
int i = 0;
for (UserData obj : users) {
UserData user = obj;
if (user.getId().equals(key)) {
user.setUnreadMessageCount(count_unread);
users.remove(i);
users.add(i, user);
break;
}
i++;
}
}
}
synchronized (this) {
if (Global.getInstance().userStatus.size() > 0) {
try {
for (Object dict : Global.getInstance().userStatus) {
Map<String, Object> val = (Map<String, Object>) dict;
String key = val.keySet().iterator().next();
val.get(key).toString().trim();
int statusValue;
if (val.get(key).toString().equals("")) {
statusValue = 4;
} else {
statusValue = Integer.valueOf(val.get(key).toString());
}
int i = 0;
for (UserData obj : users) {
UserData user = obj;
if (user.getId().equals(key)) {
user.setOnlineStatus(statusValue);
users.remove(i);
users.add(i, user);
break;
}
i++;
}
}
}catch (ConcurrentModificationException e){
e.printStackTrace();
}
}
}
Log.i(TAG, users.get(0).getName());
if (users.size() > 0) {
Collections.sort(users, new Comparator<UserData>() {
#Override
public int compare(UserData o1, UserData o2) {
if (o1.getOnlineStatus() > o2.getOnlineStatus()) {
return 1;
} else if (o1.getOnlineStatus() < o2.getOnlineStatus()) {
return -1;
} else {
return 0;
}
}
});
}
if (users.size() > 0) {
Collections.sort(users, new Comparator<UserData>() {
#Override
public int compare(UserData o1, UserData o2) {
if (o1.getUnreadMessageCount() > o2.getUnreadMessageCount()) {
return -1;
} else if (o1.getUnreadMessageCount() < o2.getUnreadMessageCount()) {
return 1;
} else {
return 0;
}
}
});
Global.getInstance().userStatus.clear();
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getActivity().getApplicationContext(), "any mesage", Toast.LENGTH_LONG).show();
adapter.notifyDataSetChanged();
}
});
}
}
}
}
public void TimerMethod() {
synchronized(this) {
SharedPreferences preferenceSettings = getActivity().getSharedPreferences("setPreferences", Context.MODE_PRIVATE);
String checkView = preferenceSettings.getString("refresh", "");
if (checkView.equals("userlistview")) {
if (Global.getInstance().userStatus.size() > 0) {
sortingArray();
}
} else {
preferenceEditor = preferenceSettings.edit();
preferenceEditor.putString("refresh", "userlistview");
preferenceEditor.commit();
if (Global.getInstance().unreadMessageUsers.size() > 0){
sortingArray();
}
}
}
}
public void onlineUsers (){
String value;
for (UserData data : users) {
value = data.getId();
FirebaseUtil online = new FirebaseUtil(getContext());
online.onlineUsers(value, new CallBack() {
#Override
public void onCallback(Map<String, Object> response, String Success) {
if (response == null) {
} else {
Global.getInstance().userStatus.add(response);
}
}
});
}
}
#Override
public void onCreateOptionsMenu(Menu menu,MenuInflater inflater) {
inflater.inflate(R.menu.menu_userlist,menu);
MenuItem item = menu.findItem(R.id.menuSearch);
SearchView searchView = (SearchView)item.getActionView();
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
adapter.getFilter().filter(newText);
return false;
}
});
super.onCreateOptionsMenu(menu,inflater);
}
private void logoutUser(){
Intent I = new Intent(getActivity(), LoginActivity.class);
startActivity(I);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menuSearch :
return true;
case R.id.menuLogout :
logoutUser();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
String val = "'";
mListener.onFragmentInteraction(val);
}
}
public void initlizeval(Context context) {
mListener = (OnFragmentInteractionListener) context;
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
myTimer.cancel();
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(String val);
}
}
menu_userlist.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item android:id="#+id/menuSearch"
android:title="#string/search"
android:icon="#drawable/ic_search"
app:actionViewClass="android.widget.SearchView"
app:showAsAction="always">
</item>
<item android:id="#+id/menuLogout"
android:title="#string/logout"
android:icon="#drawable/ic_logout"
android:tint="#android:color/white"
app:showAsAction="always">
</item>
</menu>
CustomAdapter.java
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.List;
public class CustomAdapter extends ArrayAdapter<UserData> {
private Activity activity;
private List<UserData> messages;
public CustomAdapter(Activity context, int resource, List<UserData> objects) {
super(context, resource, objects);
this.activity = context;
this.messages = objects;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
packagename.CustomAdapter.ViewHolder holder;
LayoutInflater inflater = (LayoutInflater) activity.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
int layoutResource = 0; // determined by view type
UserData data = getItem(position);
int viewType = getItemViewType(position);
layoutResource = R.layout.program_list;
if (convertView != null) {
holder = (com.your.package.CustomAdapter.ViewHolder) convertView.getTag();
} else {
convertView = inflater.inflate(layoutResource, parent, false);
holder = new com.your.package.CustomAdapter.ViewHolder(convertView);
convertView.setTag(holder);
}
//set message content
holder.msg.setText(data.getName());
holder.id = data.geId();
holder.roleMsg.setText(data.getRole());
return convertView;
}
#Override
public int getViewTypeCount() {
// return the total number of view types. this value should never change
// at runtime
return 2;
}
#Override
public int getItemViewType(int position) {
// return a value between 0 and (getViewTypeCount - 1)
return position % 2;
}
private class ViewHolder {
private TextView msg;
private String id;
private TextView roleMsg;
public ViewHolder(View v) {
msg = (TextView) v.findViewById(R.id.textView1);
roleMsg = (TextView) v.findViewById(R.id.textView2);
}
}
}
HomeActivity.java
public class HomeActivity extends AppCompatActivity implements UsersListFragment.OnFragmentInteractionListener {
private UsersListFragment mItemsFragment;
private ChatFragment mFragmentOne;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
VideoFragment fragmentTwo ;
LinearLayout layout1 = (LinearLayout) findViewById(R.id.framecontainer);
layout1.setVisibility(View.VISIBLE);
LinearLayout layout2 = (LinearLayout) findViewById(R.id.framecontainerTab);
layout2.setVisibility(View.VISIBLE);
mItemsFragment = new UsersListFragment();
mItemsFragment.initlizeval(this);
android.support.v4.app.FragmentTransaction fts = getSupportFragmentManager().beginTransaction();
fts.add(R.id.framecontainer, mItemsFragment).commit();
//Instantiate some stuff here like view components
Fragment fragmentOne = new ChatFragment();
android.support.v4.app.FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.add(R.id.framecontainerTab, fragmentOne).commit();
}else{
LinearLayout layout1 = (LinearLayout) findViewById(R.id.framecontainer);
layout1.setVisibility(View.GONE);
LinearLayout layout2 = (LinearLayout) findViewById(R.id.framecontainerTab);
layout2.setVisibility(View.GONE);
layout2.removeAllViews();
mItemsFragment = new UsersListFragment();
mItemsFragment.initlizeval(this);
setFragment(mItemsFragment);
}
}
public void setFragment(Fragment frag)
{
android.support.v4.app.FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
}
public void attemptLogin1() {
String test = "one";
String tested = "fail";
}
#Override
public void onFragmentInteraction(String uri) {
LinearLayout layout1 = (LinearLayout) findViewById(R.id.framecontainer);
layout1.setVisibility(View.GONE);
LinearLayout layout2 = (LinearLayout)findViewById(R.id.framecontainerTab);
layout2.setVisibility(View.GONE);
findViewById(R.id.framecontainerVideo);
Toast.makeText(getApplicationContext(), "bullet", Toast.LENGTH_SHORT).show();
}
#Override
protected void onPause() {
super.onPause();
}
#Override
protected void onResume() {
super.onResume();
}
#Override
public void onBackPressed() {
super.onBackPressed();
Fragment fragmentOne = new ChatFragment();
LinearLayout layout1 = (LinearLayout) findViewById(R.id.framecontainer);
layout1.setVisibility(View.VISIBLE);
LinearLayout layout2 = (LinearLayout) findViewById(R.id.framecontainerTab);
layout2.setVisibility(View.VISIBLE);
}
#Override
protected void onStart() {
super.onStart();
getDelegate().onStart();
}
}
I have written setHasOptionsMenu(true); in onCreate of UserFragment.java
The logout functionality works fine but the search isn't working.
I have tried various options given on Stackoverflow as well as from other resource, but nothing worked. :(
Any help is appreciated.
Thanks in advance.
Create Constructor in your fragment. Pass Context object inside fragment constructor.which allows your activity as global access.
Remove this line and it will work
case R.id.menuSearch:
return true;

Un-filtering the result is not working in Recyclerview

I have a recyclerview with some data and I have a searchview, and filter is working just fine. But un-filtering not working. I can't get the whole data in the recyclerview after un-filter. No data is showing. I have to re-open the activity to get data. I tried to used two data sets. But i have no idea where to use them.
My Fragment.
public class YourDealerListFragment extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private static final String STATE_DEALER_LIST = "state_dealer_list";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private VollySingleton vollySingleton;
private RequestQueue requestQueue;
private RecyclerView recyclerView;
private DealerListAdapter dlAdapter;
private HashMap<String, String> hashMap;
private ArrayList<SuggestGetSet> dealerList = new ArrayList<>();
private ArrayList<SuggestGetSet> filteredDealerList = new ArrayList<>();
private String repNo;
private StaggeredGridLayoutManager staggeredGridLayoutManager;
private GridMenuFragment mGridMenuFragment;
private Toolbar toolbar;
private ItemSorter itemSorter;
private Button sortButton;
private SearchView searchView;
private ProgressView progressView;
public static List<String> disChannel;
public YourDealerListFragment() {
// 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 YourDealerListFragment.
*/
// TODO: Rename and change types and number of parameters
public static YourDealerListFragment newInstance(String param1, String param2) {
YourDealerListFragment fragment = new YourDealerListFragment();
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);
}
vollySingleton = VollySingleton.getsInstance();
requestQueue = vollySingleton.getmRequestQueue();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_your_dealer_list, container, false);
recyclerView = (RecyclerView) view.findViewById(R.id.dealerListRecyclerView);
progressView = (ProgressView) view.findViewById(R.id.pViewew);
itemSorter = new ItemSorter();
dlAdapter = new DealerListAdapter();
disChannel = new ArrayList<String>();
repNo = UserLogIn.getRepNo();
if (savedInstanceState != null) {
dealerList = savedInstanceState.getParcelableArrayList(STATE_DEALER_LIST);
dlAdapter.setDealertList(dealerList);
} else {
getJsonRequest();
}
final FrameLayout frameLayout = (FrameLayout) view.findViewById(R.id.frame_layout);
frameLayout.getBackground().setAlpha(0);
final FloatingActionsMenu fabMenu = (FloatingActionsMenu) view.findViewById(R.id.fab_menu);
final FloatingActionButton fabName = (FloatingActionButton) view.findViewById(R.id.fab_name);
final FloatingActionButton fabCollection = (FloatingActionButton) view.findViewById(R.id.fab_collection);
fabName.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onSortByName();
fabMenu.collapse();
}
});
fabMenu.setOnFloatingActionsMenuUpdateListener(new FloatingActionsMenu.OnFloatingActionsMenuUpdateListener() {
#Override
public void onMenuExpanded() {
frameLayout.getBackground().setAlpha(240);
frameLayout.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
fabMenu.collapse();
return true;
}
});
}
#Override
public void onMenuCollapsed() {
frameLayout.getBackground().setAlpha(0);
frameLayout.setOnTouchListener(null);
}
});
searchView = (SearchView) view.findViewById(R.id.dealerNameSearchView);
searchView.setOnQueryTextListener(listener);
//custom context menu
mGridMenuFragment = GridMenuFragment.newInstance(R.drawable.background);
setupGridMenu();
mGridMenuFragment.setOnClickMenuListener(new GridMenuFragment.OnClickMenuListener() {
#Override
public void onClickMenu(GridMenu gridMenu, int position) {
switch (position) {
case 0:
Intent intent = new Intent(getActivity(), SelectItem.class);
getActivity().finish();
startActivity(intent);
getActivity();
break;
}
}
});
//dealers' recycler view item click
recyclerView.addOnItemTouchListener(new NavigationDrawerFragment.RecycleTouchListner(getActivity(), recyclerView, new NavigationDrawerFragment.ClickListener() {
#Override
public void onClick(View view, int position) {
FragmentTransaction tx = getActivity().getSupportFragmentManager().beginTransaction();
tx.replace(R.id.main_frame, mGridMenuFragment);
tx.addToBackStack(null);
tx.commit();
}
}));
return view;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
setHasOptionsMenu(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
staggeredGridLayoutManager = new StaggeredGridLayoutManager(3, StaggeredGridLayoutManager.VERTICAL);
recyclerView.setLayoutManager(staggeredGridLayoutManager);
final ArrayList<SuggestGetSet> filteredModelList = new ArrayList<>();
for (SuggestGetSet movie : filteredModelList) {
filteredModelList.add(movie);
}
dlAdapter = new DealerListAdapter(filteredModelList, getActivity());
recyclerView.setAdapter(dlAdapter);
}
//search dealer from search view
SearchView.OnQueryTextListener listener = new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String s) {
return false;
}
#Override
public boolean onQueryTextChange(String s) {
final ArrayList<SuggestGetSet> filteredModelList = filter(dealerList, s);
dlAdapter.animateTo(filteredModelList);
recyclerView.scrollToPosition(0);
return true;
}
};
private ArrayList<SuggestGetSet> filter(ArrayList<SuggestGetSet> models, String query) {
query = query.toLowerCase();
final ArrayList<SuggestGetSet> filteredModelList = new ArrayList<>();
for (SuggestGetSet model : models) {
final String text = model.getName().toLowerCase();
if (text.contains(query)) {
filteredModelList.add(model);
}
}
return filteredModelList;
}
//custom context menu data
private void setupGridMenu() {
List<GridMenu> menus = new ArrayList<>();
menus.add(new GridMenu("Order", R.drawable.nnn));
menus.add(new GridMenu("Banking", R.drawable.n));
menus.add(new GridMenu("Credit Note", R.drawable.nn));
menus.add(new GridMenu("Cheques", R.drawable.nnnn));
menus.add(new GridMenu("Invoice Dispatch", R.drawable.nnnnn));
menus.add(new GridMenu("Goods Return", R.drawable.nnnnnn));
mGridMenuFragment.setupMenu(menus);
}
private void getJsonRequest() {
progressView.start();
final SQLiteHandler sqLiteHandler = new SQLiteHandler(getActivity().getApplicationContext());
Cursor cr = sqLiteHandler.getData(sqLiteHandler);
cr.moveToFirst();
do {
repNo = cr.getString(0);
} while (cr.moveToNext());
cr.close();
CustomJsonObjectRequest request = new CustomJsonObjectRequest(Request.Method.POST, AppConfig.URL_JSON_DEALER_LIST, hashMap, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
progressView.stop();
try {
JSONObject jsonObject = new JSONObject(String.valueOf(response));
if (jsonObject.names().get(0).equals("feed")) {
dealerList = parseJsonResponse(response);
dlAdapter.setDealertList(dealerList);
JSONArray arrayAchSum = response.getJSONArray("feedd");
for (int i = 0; i < arrayAchSum.length(); i++) {
JSONObject obj3 = arrayAchSum.getJSONObject(i);
String a = obj3.getString("dis_channel");
disChannel.add(a);
}
} else {
Toast.makeText(getActivity(), "No Dealers Available", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
/*dealerList = parseJsonResponse(response);
dlAdapter.setDealertList(dealerList);*/
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) {
protected Map<String, String> getParams() throws AuthFailureError {
hashMap = new HashMap<String, String>();
hashMap.put("repNo", repNo);
return hashMap;
}
};
requestQueue.add(request);
request.setRetryPolicy(new DefaultRetryPolicy(15 * 1000, 0,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
}
private ArrayList<SuggestGetSet> parseJsonResponse(JSONObject response) {
ArrayList<SuggestGetSet> groupList = new ArrayList<>();
if (response != null || response.length() > 0) {
try {
JSONArray arrayDelaers = response.getJSONArray(KEY_FEED_NAME);
for (int i = 0; i < arrayDelaers.length(); i++) {
JSONObject currentObject = arrayDelaers.getJSONObject(i);
String rep = currentObject.getString(KEY_REP_ID);
String name = currentObject.getString(KEY_REP_NAME);
String dealerId = currentObject.getString(KEY_DEALER_ID);
SuggestGetSet delaers = new SuggestGetSet();
delaers.setId(rep);
delaers.setName(name);
delaers.setDealerId(dealerId);
groupList.add(delaers);
}
//Toast.makeText(getApplicationContext(), productList.toString(), Toast.LENGTH_LONG).show();
} catch (JSONException e) {
e.printStackTrace();
}
}
return groupList;
}
public void onSortByName() {
itemSorter.sortItemByName(dealerList);
dlAdapter.notifyDataSetChanged();
}
public static interface ClickListener {
public void onClick(View view, int position);
//public void onLongClick(View view, int position);
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putParcelableArrayList(STATE_DEALER_LIST, dealerList);
}
}
My Adapter class.
public class DealerListAdapter extends RecyclerView.Adapter<DealerListAdapter.ViewHolderDealerList> {
private LayoutInflater layoutInflater;
public Context mcontext;
private List<SuggestGetSet> dealerArrayList;
private List<SuggestGetSet> originalDealerArrayList;
Typeface type;
private static String selectedRepId, selectedDealerId, selectedDealerName;
public DealerListAdapter() {
}
public DealerListAdapter(Context context) {
layoutInflater = LayoutInflater.from(context);
type = Typeface.createFromAsset(context.getAssets(), "helvr.ttf");
}
public static String getDealerName() {
return selectedDealerName;
}
public static String getDealerID() {
return selectedDealerId;
}
public static String getRepID() {
return selectedRepId;
}
public DealerListAdapter(ArrayList<SuggestGetSet> dList, Context context) {
this.mcontext = context;
layoutInflater = LayoutInflater.from(context);
dealerArrayList = new ArrayList<>(dList);
originalDealerArrayList = new ArrayList<>(dList);
type = Typeface.createFromAsset(context.getAssets(), "helvr.ttf");
}
public void setDealertList(ArrayList<SuggestGetSet> dealerAList) {
this.dealerArrayList = dealerAList;
originalDealerArrayList = new ArrayList<>(dealerAList);
notifyItemRangeChanged(0, dealerArrayList.size());
}
#Override
public ViewHolderDealerList onCreateViewHolder(ViewGroup parent, int viewType) {
View view = layoutInflater.inflate(R.layout.custom_dealer_list_layout, parent, false);
ViewHolderDealerList viewHolderDealerList = new ViewHolderDealerList(view);
return viewHolderDealerList;
}
#Override
public void onBindViewHolder(ViewHolderDealerList holder, int position) {
final SuggestGetSet model = dealerArrayList.get(position);
holder.bind(model);
final int pos = position;
holder.dealerName.setText(dealerArrayList.get(position).getName());
holder.dealerName.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
selectedDealerId = dealerArrayList.get(pos).getDealerId();
selectedRepId = dealerArrayList.get(pos).getId();
selectedDealerName = dealerArrayList.get(pos).getName();
Toast.makeText(layoutInflater.getContext(), dealerArrayList.get(pos).getName() + " / " + dealerArrayList.get(pos).getDealerId() + " / " + dealerArrayList.get(pos).getId(), Toast.LENGTH_LONG).show();
}
});
}
#Override
public int getItemCount() {
return dealerArrayList.size();
}
public void setModels(ArrayList<SuggestGetSet> models) {
dealerArrayList = new ArrayList<>(models);
}
static class ViewHolderDealerList extends RecyclerView.ViewHolder {
private TextView dealerName, dealerId;
public ViewHolderDealerList(View itemView) {
super(itemView);
dealerName = (TextView) itemView.findViewById(R.id.yourDelaerName);
//dealerId = (TextView) itemView.findViewById(R.id.txtDelaerCollection);
}
public void bind(SuggestGetSet model) {
dealerName.setText(model.getName());
}
}
//search animations
public SuggestGetSet removeItem(int position) {
final SuggestGetSet model = dealerArrayList.remove(position);
notifyItemRemoved(position);
return model;
}
public void addItem(int position, SuggestGetSet model) {
dealerArrayList.add(position, model);
notifyItemInserted(position);
}
public void moveItem(int fromPosition, int toPosition) {
final SuggestGetSet model = dealerArrayList.remove(fromPosition);
dealerArrayList.add(toPosition, model);
notifyItemMoved(fromPosition, toPosition);
}
public void animateTo(ArrayList<SuggestGetSet> models) {
applyAndAnimateRemovals(models);
applyAndAnimateAdditions(models);
applyAndAnimateMovedItems(models);
}
private void applyAndAnimateMovedItems(ArrayList<SuggestGetSet> models) {
for (int toPosition = dealerArrayList.size() - 1; toPosition >= 0; toPosition--) {
final SuggestGetSet model = dealerArrayList.get(toPosition);
final int fromPosition = models.indexOf(model);
if (fromPosition >= 0 && fromPosition != toPosition) {
moveItem(fromPosition, toPosition);
}
}
notifyDataSetChanged();
}
private void applyAndAnimateAdditions(ArrayList<SuggestGetSet> models) {
for (int i = 0, count = dealerArrayList.size(); i < count; i++) {
final SuggestGetSet model = dealerArrayList.get(i);
if (!models.contains(model)) {
addItem(i, model);
}
}
notifyDataSetChanged();
}
private void applyAndAnimateRemovals(ArrayList<SuggestGetSet> models) {
for (int i = dealerArrayList.size() - 1; i >= 0; i--) {
final SuggestGetSet model = dealerArrayList.get(i);
if (!models.contains(model)) {
removeItem(i);
}
}
notifyDataSetChanged();
}
}
Just Modify your function and Add check for null or "" .
it will work fine
private ArrayList<SuggestGetSet> filter(ArrayList<SuggestGetSet> models, String query) {
if(TextUtils.isEmpty(query)){
return models;
}
query = query.toLowerCase();
final ArrayList<SuggestGetSet> filteredModelList = new ArrayList<>();
for (SuggestGetSet model : models) {
final String text = model.getName().toLowerCase();
if (text.contains(query)) {
filteredModelList.add(model);
}
}
return filteredModelList;
}

set text value from fragment.newInstance String

I am trying to set a string to a textview but everytime i click the button Quiz the activity is just refreshing instead going to fragment activity.
This summarize the situation.
I have dynamic viewPager inside activity called Quiz_Container
Use only one fragment(Module_Topics_Content_Quiz) in public Fragment getItem(int position) or FragmentStatePagerAdapter.
I want to change text of a textview in the fragment from activity everytime i swipe.
I am passing the string using newInstance with parameter from activity to fragment
The string came from quizQuestion.get(position)
I'm getting the right value with the Log.d but when setting it to textview the activity is just refreshing.
this is my code.
Quiz_Container.java
public class Quiz_Container extends AppCompatActivity implements Module_Topics_Content_Quiz.OnFragmentInteractionListener {
android.support.v7.app.ActionBar actionBar;
ViewPager quizPager;
private int topicID;
private int moduleID;
private int subModuleID;
private ArrayList<Integer> quizID;
private ArrayList<String> quizQuestion;
private ArrayList<String> choiceA;
private ArrayList<String> choiceB;
private ArrayList<String> choiceC;
private ArrayList<String> choiceD;
private ArrayList<String> quizAnswer;
private FragmentManager fragmentManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz__container);
actionBar = getSupportActionBar();
actionBar.setTitle("Quiz");
actionBar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#f1ad1e")));
Bundle extras = getIntent().getExtras();
topicID = extras.getInt("topicID");
moduleID = extras.getInt("moduleID");
subModuleID = extras.getInt("subModuleID");
Log.d("quizTopicID", "" + topicID);
Log.d("quizModuleID", "" + moduleID);
Log.d("quizSubModuleID", "" + subModuleID);
new quizTask().execute();
}
#Override
public void onFragmentInteraction(Uri uri) {
}
public boolean isOnline() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
return true;
} else {
return false;
}
} // Check Internet Connection
class quizTask extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
}
#Override
protected String doInBackground(String... params) {
BufferedReader reader = null;
try {
URL quizURL = new URL("http://192.168.1.110/science/index.php/users/get_quiz_items/" + topicID + "/" + moduleID + "/" + subModuleID + "" );
HttpURLConnection con = (HttpURLConnection)quizURL.openConnection();
StringBuilder sb = new StringBuilder();
reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String quizResponse;
while ((quizResponse = reader.readLine()) != null) {
return quizResponse;
}
return sb.toString();
} catch (IOException e) {
e.printStackTrace();
return null;
} finally {
if(reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
}
}
#Override
protected void onPostExecute(String quizResponses) {
Log.d("quizResponse", "" + quizResponses);
try {
JSONObject quizObject = new JSONObject(quizResponses);
boolean result = quizObject.getBoolean("success");
if (result) {
JSONArray quizArray = quizObject.getJSONArray("data");
quizID = new ArrayList<>();
quizQuestion = new ArrayList<>();
choiceA = new ArrayList<>();
choiceB = new ArrayList<>();
choiceC = new ArrayList<>();
choiceD = new ArrayList<>();
quizAnswer = new ArrayList<>();
for (int i = 0; i < quizArray.length(); i ++) {
JSONObject dataQuiz = quizArray.getJSONObject(i);
quizID.add(dataQuiz.getInt("id"));
quizQuestion.add(dataQuiz.getString("question"));
choiceA.add(dataQuiz.getString("a"));
choiceB.add(dataQuiz.getString("b"));
choiceC.add(dataQuiz.getString("c"));
choiceD.add(dataQuiz.getString("d"));
quizAnswer.add(dataQuiz.getString("answer"));
}
Log.d("quizSize", "" + quizID.size());
quizPager = (ViewPager) findViewById(R.id.quizPager);
fragmentManager = Quiz_Container.this.getSupportFragmentManager();
quizPager.setAdapter(new quizAdapter(getSupportFragmentManager()));
quizPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
}
else {
Toast.makeText(getApplication(), "no quiz yet", Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
} // end of quizTask
class quizAdapter extends FragmentStatePagerAdapter {
public quizAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
Fragment fragment = null;
for (int i = 0; i < quizID.size; i++) {
if (i == position) {
fragment = Module_Topics_Content_Quiz.newInstance(quizQuestion.get(position));
Log.d("testQuestion", "" + quizQuestion.get(position)); // this code is working
}
}
return fragment;
}
#Override
public int getCount() {
return quizID.size();
}
}
}
Module_Topics_Content_Quiz.java
public class Module_Topics_Content_Quiz extends Fragment {
TextView textQuizQuestion;
private String qQuestion;
public Module_Topics_Content_Quiz() {
// Required empty public constructor
}
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
public void onFragmentInteraction(Uri uri);
}
public static Module_Topics_Content_Quiz newInstance(String question) {
Module_Topics_Content_Quiz fragment = new Module_Topics_Content_Quiz();
Bundle args = new Bundle();
args.putString("question", question);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
qQuestion = getArguments().getString("question");
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_module__topics__content__quiz, container, false);
textQuizQuestion = (TextView) getActivity().findViewById(R.id.textQuestion);
Log.d("question", "" + qQuestion); // this is working
// textQuizQuestion.setText(qQuestion); // error if enable
return rootView;
}
}
Please help. Thank you.
In your fragment, try inflating the TextView using the View returned rather than using getActivity()
You need to inflate the Fragment's view and call findViewById() on the View it returns.
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_module__topics__content__quiz, container, false);
// inflate the View inside Fragment using the View returned
textQuizQuestion = (TextView) rootView.findViewById(R.id.textQuestion);
Log.d("question", "" + qQuestion); // this is working
textQuizQuestion.setText(qQuestion);
return rootView;
}
You can also use getView() from within the Fragment to get the root view.
If you wanna call from the enclosing Activity, use
getFragmentManager().findFragmentById(R.id.your_fragment_id).getView().findViewById(R.id.your_view);

Categories

Resources