Cannot get data from sharedpreference? - android

Here is my doubt I have one activity inside that one fragment need to populate listview in activity from fragment data . But when I press back button from activity listview data is missing my doubt is how to store data permanently I have read about shared preferences here we can store and retrieve data permanently but when I use it i doesn't store the listview value permanently it's still missing the value as am new for android am confused with this so far what I have tried is:
Here is my Fragment:
package first.service.precision.servicefirst;
import android.app.Activity;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
/**
* Created by 4264 on 16-12-2015.
*/
public class NewCompetitors extends Fragment {
CompetitorsData competitorsData;
CompetitorsView competitorsView = new CompetitorsView();
EditText editText_name,editText_website,editText_strength,editText_weakness;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.new_competitors_fragment, container, false);
editText_name = (EditText) rootView.findViewById(R.id.competitors_name);
editText_website = (EditText) rootView.findViewById(R.id.competitors_website);
editText_strength = (EditText) rootView.findViewById(R.id.competitors_strength);
editText_weakness = (EditText) rootView.findViewById(R.id.competitors_weakness);
Button btn_save = (Button) rootView.findViewById(R.id.btn_save);
btn_save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
editTextcompetitor();
sendData(competitorsView);
getActivity().getFragmentManager().popBackStack();
}
});
return rootView;
}
public void editTextcompetitor(){
competitorsView.setCompetitor_name(editText_name.getText().toString());
competitorsView.setCompetitor_website(editText_website.getText().toString());
competitorsView.setCompetitor_strength(editText_strength.getText().toString());
competitorsView.setCompetitor_weakness(editText_weakness.getText().toString());
}
public void sendData(CompetitorsView competitorsView){
competitorsData.dataToCompetitorActivity(competitorsView);
}
#SuppressWarnings("deprecation")
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
competitorsData = (CompetitorsData) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()+ "");
}
}
public interface CompetitorsData{
void dataToCompetitorActivity(CompetitorsView competitorsView);
}
}
Here is my Activity where i populate listview:
package first.service.precision.servicefirst;
import android.app.FragmentTransaction;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
public class Competitors extends Main2Activity implements NewCompetitors.CompetitorsData{
ListView lv;
SharedPreferences sharedPreferences;
List<CompetitorsView> competitorsViews;
CompetitorsListAdapter competitorsListAdapter;
Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_competitors);
LayoutInflater inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View contentView = inflater.inflate(R.layout.activity_competitors, null, false);
mDrawerLayout.addView(contentView, 0);
lv=(ListView)findViewById(R.id.list_competitors);
competitorsViews=new ArrayList<CompetitorsView>();
competitorsListAdapter=new CompetitorsListAdapter(this,R.id.list_competitors,competitorsViews);
lv.setAdapter(competitorsListAdapter);
Button btn_competitors=(Button)findViewById(R.id.btn_new_competitors);
SharedPreferences sharedPreferences= PreferenceManager.getDefaultSharedPreferences(this.getApplicationContext());
SharedPreferences.Editor edit=sharedPreferences.edit();
Gson gson=new Gson();
String yog=sharedPreferences.getString("go","");
Type type=new TypeToken<List<NewCompetitors>>(){}.getType();
List<CompetitorsView>competitorsViews=gson.fromJson(yog,type);
edit.commit();
btn_competitors.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
NewCompetitors fragment = new NewCompetitors();
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.add(R.id.competitors_frame, fragment);
ft.addToBackStack(null);
ft.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_competitors, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onDestroy() {
super.onDestroy();
Gson gson = new Gson();
String jsonCurProduct = gson.toJson(competitorsViews);
SharedPreferences sharedPref = getApplicationContext().getSharedPreferences("yog", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("go", jsonCurProduct);
editor.commit();
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
//ArrayList<CompetitorsView>cc=savedInstanceState.getParcelableArrayList("yog");
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
}
#Override
public void dataToCompetitorActivity(CompetitorsView competitorsView)
{
competitorsViews.add(competitorsView);
competitorsListAdapter.notifyDataSetChanged();
}
#Override
protected void onRestart() {
super.onRestart();
}
}
Here is my customlistadapter:
package first.service.precision.servicefirst;
import android.content.Context;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import java.util.List;
/**
* Created by 4264 on 16-12-2015.
*/
public class CompetitorsListAdapter extends ArrayAdapter<CompetitorsView> {
private List<CompetitorsView> listData;
private LayoutInflater layoutInflater;
public CompetitorsListAdapter(Context context, int resource, List<CompetitorsView> listdata) {
super(context, resource, listdata);
this.listData = listdata;
layoutInflater = LayoutInflater.from(context);
}
#Override
public void add(CompetitorsView object) {
super.add(object);
}
#Override
public int getCount() {
return listData.size();
}
#Override
public CompetitorsView getItem(int position) {
return listData.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
View mview = convertView;
if (mview == null) {
convertView = layoutInflater.inflate(R.layout.list_competitors, null);
// TextView req = (TextView) convertView.findViewById(R.id.txt);
//req.setText("Select Lead Information");
holder = new ViewHolder();
holder.competitors_name = (TextView) convertView.findViewById(R.id.company_grp);
holder.competitors_website = (TextView) convertView.findViewById(R.id.company_name);
holder.competitors_strength = (TextView) convertView.findViewById(R.id.addrsline);
holder.competitors_weakness = (TextView) convertView.findViewById(R.id.stateid);
// add.lv.setVisibility(View.INVISIBLE);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
// add.lv.setVisibility(View.VISIBLE);
holder.competitors_name.setText("Competitors Name: " + listData.get(position).getCompetitor_name());
holder.competitors_website.setText("Website: " + listData.get(position).getCompetitor_website());
holder.competitors_strength.setText("Competitors Strength: " + listData.get(position).getCompetitor_strength());
holder.competitors_weakness.setText("Competitors Weakness:" + listData.get(position).getCompetitor_weakness());
convertView.setBackgroundColor(Color.parseColor("#ffffff"));
return convertView;
}
static class ViewHolder {
public TextView competitors_name;
public TextView competitors_website;
public TextView competitors_strength;
public TextView competitors_weakness;
}
}
it's working but it's not storing the value!

Related

The Search View is not giving any result in my Fragment containing RecyclerView. After I click on the Search icon the screen is just blank

I have a fragment with RecyclerView and Room Database and I want to add a search view. I have successfully added the search icon and also added the code in the Fragment as well as Adapter. But the problem is that when I click on the Search icon, the screen is blank. Also, when I type anything it doesn't give me any result.
If I close the Search View and click on back button, the RecyclerView in Fragment is no more visible. I have checked the solution online and it uses similar code. So, I can't understand what is the mistake in my code. can anyone help me please?
My Fragment Code
'''
package com.nitin.roomrecyclerview;
import androidx.appcompat.widget.SearchView;
import androidx.core.view.MenuItemCompat;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModel;
import androidx.lifecycle.ViewModelProvider;
import androidx.lifecycle.ViewModelProviders;
import android.content.Intent;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.navigation.Navigation;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.provider.ContactsContract;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import java.util.ArrayList;
import java.util.List;
public class FragmentStatus extends Fragment implements MyViewHolder.OnStatusListener, SearchView.OnQueryTextListener, MenuItem.OnActionExpandListener {
private FragmentStatusViewModel mViewModel;
private RecyclerView recyclerView;
private RecyclerView.LayoutManager layoutManager;
private MyAdapter mAdapter;
FloatingActionButton floatingActionButton;
Bundle bundletest;
Bundle bundletest1;
Status status;
private List<Status> statuses = new ArrayList<>();
public static FragmentStatus newInstance() {
return new FragmentStatus();
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// Inflate the menu; this adds items to the action bar if it is present.
inflater.inflate(R.menu.main, menu);
MenuItem menuItem = menu.findItem(R.id.search);
SearchView searchView = (SearchView) menuItem.getActionView();
searchView.setOnQueryTextListener(this);
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
if (newText == null || newText.trim().isEmpty()) {
mAdapter.setfilter(statuses);
return false;
} else {
newText = newText.toLowerCase();
List<Status> newList = new ArrayList<>();
for (Status status : statuses) {
if (status.getTitle().toLowerCase().contains(newText)){
newList.add(status);
}
}
Toast.makeText(getActivity(), "newtext" + newText, Toast.LENGTH_SHORT).show();
mAdapter.setfilter(newList);
return true;
}
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()){
case R.id.deleteallstatus:
FragmentStatusViewModel mViewModel = new ViewModelProvider(this).get(FragmentStatusViewModel.class);
mViewModel.deleteAllStatus();
Toast.makeText(getActivity(), "All Status Deleted", Toast.LENGTH_SHORT).show();
return true;
case R.id.action_settings:
Toast.makeText(getActivity(), "Setting Selected", Toast.LENGTH_SHORT).show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container,
#Nullable Bundle savedInstanceState) {
// setHasOptionsMenu(true);
return inflater.inflate(R.layout.fragment_status_fragment, container, false);
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
recyclerView = (getActivity()).findViewById(R.id.statusRecyclerView);
layoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(layoutManager);
recyclerView.setHasFixedSize(true);
floatingActionButton = getActivity().findViewById(R.id.button_add_status);
floatingActionButton.setOnClickListener(Navigation.createNavigateOnClickListener(R.id.action_fragmentStatus_to_updateFragment, null));
//status = new Status(title,description);
mAdapter = new MyAdapter(statuses, this);
recyclerView.setAdapter(mAdapter);
mViewModel = new ViewModelProvider(this).get(FragmentStatusViewModel.class);
mViewModel.getAllStatus().observe(getViewLifecycleOwner(), new Observer<List<Status>>() {
#Override
public void onChanged(List<Status> statuses) {
mAdapter.setStatuses(statuses);
}
});
if(getArguments() != null && getArguments().containsKey("ID") == true && bundletest != getArguments()){
int id = getArguments().getInt("ID", -1);
if(id == -1){
Toast.makeText(getActivity(), "Status can't be updated", Toast.LENGTH_LONG).show();
}
String title = getArguments().getString("title1");
String description = getArguments().getString("description1");
Status status = new Status(title,description);
mViewModel.update(status);
status.setId(id);
bundletest = getArguments();
Toast.makeText(getActivity(), "Status updated" + id, Toast.LENGTH_LONG).show();
}else if (getArguments() != null && !getArguments().containsKey("ID") && bundletest1 != getArguments()){
String title = getArguments().getString("title");
String description = getArguments().getString("description");
Status status = new Status(title,description);
mViewModel.insert(status);
bundletest1 = getArguments();
Toast.makeText(getActivity(), "Status saved", Toast.LENGTH_LONG).show();
}else {
Toast.makeText(getActivity(), "Statuses displayed!", Toast.LENGTH_SHORT).show();
}
new ItemTouchHelper(new ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT |
ItemTouchHelper.RIGHT) {
#Override
public boolean onMove(#NonNull RecyclerView recyclerView, #NonNull RecyclerView.ViewHolder viewHolder, #NonNull RecyclerView.ViewHolder target) {
return false;
}
#Override
public void onSwiped(#NonNull RecyclerView.ViewHolder viewHolder, int direction) {
mViewModel.delete(mAdapter.getStatusAt(viewHolder.getAdapterPosition()));
Toast.makeText(getActivity(), "Note Deleted", Toast.LENGTH_LONG).show();
}
}).attachToRecyclerView(recyclerView);
}
#Override
public void onStatusClick(Status status) {
Toast.makeText(getActivity(), "the id is " + status.getId(), Toast.LENGTH_SHORT).show();
Bundle bundle = new Bundle();
bundle.putInt("ID", status.getId());
bundle.putString("description", status.getDescription());
bundle.putString("title", status.getTitle());
Navigation.findNavController(getActivity().findViewById(R.id.recyclerLayout)).navigate(R.id.action_fragmentStatus_to_editStatusFragment, bundle);
}
#Override
public boolean onMenuItemActionExpand(MenuItem item) {
return true;
}
#Override
public boolean onMenuItemActionCollapse(MenuItem item) {
mAdapter.setfilter(statuses);
return true;
}
}
'''
My Adapter Code
'''
package com.nitin.roomrecyclerview;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.coordinatorlayout.widget.CoordinatorLayout;
import androidx.navigation.Navigation;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
public class MyAdapter extends RecyclerView.Adapter<MyViewHolder> {
private List<Status> statuses = new ArrayList<>();
private MyViewHolder.OnStatusListener listener;
public MyAdapter(List<Status> statuses, MyViewHolder.OnStatusListener listener) {
this.statuses = statuses;
this.listener = listener;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View view = inflater.inflate(R.layout.status_recyclerview, parent, false);
MyViewHolder myViewHolder = new MyViewHolder(view, listener, statuses);
return myViewHolder;
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, int position) {
Status status = statuses.get(position);
holder.title_template.setText(status.getTitle());
holder.description_template.setText(status.getDescription());
}
#Override
public int getItemCount() {
return statuses.size();
}
public void setStatuses(List<Status> statuses){
this.statuses = statuses;
notifyDataSetChanged();
}
public Status getStatusAt(int position){
return statuses.get(position);
}
public void setfilter(List<Status> newList){
statuses.clear();
statuses.addAll(newList);
notifyDataSetChanged();
}
}
'''
My ViewHolder Code
'''
package com.nitin.roomrecyclerview;
import android.view.View;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
import java.util.List;
public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public TextView title_template;
public TextView description_template;
private List<Status> statuses = new ArrayList<>();
OnStatusListener listener;
//Status status;
public MyViewHolder(#NonNull View itemView, OnStatusListener listener, List<Status> statuses) {
super(itemView);
this.title_template = itemView.findViewById(R.id.title_template);
this.description_template = itemView.findViewById(R.id.description_template);
this.listener = listener;
this.statuses = statuses;
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
listener.onStatusClick(statuses.get(getAdapterPosition()));
}
interface OnStatusListener{
void onStatusClick(Status status);
}
}
'''
My Menu XML Code
'''
<?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/action_settings"
android:orderInCategory="100"
android:title="#string/action_settings"
app:showAsAction="never" />
<item
android:id="#+id/deleteallstatus"
android:orderInCategory="100"
android:title="Delete all status"
app:showAsAction="never" />
<item
android:id="#+id/search"
android:orderInCategory="100"
android:icon="#drawable/ic_search"
app:showAsAction="ifRoom|collapseActionView"
android:title="Search"
app:actionViewClass="androidx.appcompat.widget.SearchView" />
</menu>
'''
As I am using LiveData...the code is as follows
I had to implement Filterable in Adapter...and then the codes as shown below.
In Fragment
'''
package com.nitin.roomrecyclerview;
import androidx.activity.OnBackPressedCallback;
import androidx.appcompat.widget.SearchView;
import androidx.core.view.MenuItemCompat;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModel;
import androidx.lifecycle.ViewModelProvider;
import androidx.lifecycle.ViewModelProviders;
import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.navigation.Navigation;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.provider.ContactsContract;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import java.util.ArrayList;
import java.util.List;
public class FragmentStatus extends Fragment implements MyViewHolder.OnStatusListener {
private FragmentStatusViewModel mViewModel;
private RecyclerView recyclerView;
private RecyclerView.LayoutManager layoutManager;
private MyAdapter mAdapter;
FloatingActionButton floatingActionButton;
Bundle bundletest;
Bundle bundletest1;
private List<Status> statuses = new ArrayList<>();
public static FragmentStatus newInstance() {
return new FragmentStatus();
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// Inflate the menu; this adds items to the action bar if it is present.
inflater.inflate(R.menu.main, menu);
MenuItem menuItem = menu.findItem(R.id.search);
SearchView searchView = (SearchView) menuItem.getActionView();
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
mAdapter.getFilter().filter(newText);
return true;
}
});
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()){
case R.id.deleteallstatus:
FragmentStatusViewModel mViewModel = new ViewModelProvider(this).get(FragmentStatusViewModel.class);
mViewModel.deleteAllStatus();
Toast.makeText(getActivity(), "All Status Deleted", Toast.LENGTH_SHORT).show();
return true;
case R.id.action_settings:
Toast.makeText(getActivity(), "Setting Selected", Toast.LENGTH_SHORT).show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container,
#Nullable Bundle savedInstanceState) {
// setHasOptionsMenu(true);
return inflater.inflate(R.layout.fragment_status_fragment, container, false);
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
recyclerView = (getActivity()).findViewById(R.id.statusRecyclerView);
layoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(layoutManager);
recyclerView.setHasFixedSize(true);
floatingActionButton = getActivity().findViewById(R.id.button_add_status);
floatingActionButton.setOnClickListener(Navigation.createNavigateOnClickListener(R.id.action_fragmentStatus_to_updateFragment, null));
//status = new Status(title,description);
mAdapter = new MyAdapter(getActivity(), statuses, this);
recyclerView.setAdapter(mAdapter);
mViewModel = new ViewModelProvider(this).get(FragmentStatusViewModel.class);
mViewModel.getAllStatus().observe(getViewLifecycleOwner(), new Observer<List<Status>>() {
#Override
public void onChanged(List<Status> statuses) {
mAdapter.setStatuses(statuses);
}
});
if(getArguments() != null && getArguments().containsKey("ID") == true && bundletest != getArguments()){
int id = getArguments().getInt("ID", -1);
if(id == -1){
Toast.makeText(getActivity(), "Status can't be updated", Toast.LENGTH_LONG).show();
}
String title = getArguments().getString("title1");
String description = getArguments().getString("description1");
Status status = new Status(title,description);
mViewModel.update(status);
status.setId(id);
bundletest = getArguments();
Toast.makeText(getActivity(), "Status updated" + id, Toast.LENGTH_LONG).show();
}else if (getArguments() != null && !getArguments().containsKey("ID") && bundletest1 != getArguments()){
String title = getArguments().getString("title");
String description = getArguments().getString("description");
Status status = new Status(title,description);
mViewModel.insert(status);
bundletest1 = getArguments();
Toast.makeText(getActivity(), "Status saved", Toast.LENGTH_LONG).show();
}else {
Toast.makeText(getActivity(), "Statuses displayed!", Toast.LENGTH_SHORT).show();
}
new ItemTouchHelper(new ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT |
ItemTouchHelper.RIGHT) {
#Override
public boolean onMove(#NonNull RecyclerView recyclerView, #NonNull RecyclerView.ViewHolder viewHolder, #NonNull RecyclerView.ViewHolder target) {
return false;
}
#Override
public void onSwiped(#NonNull RecyclerView.ViewHolder viewHolder, int direction) {
mViewModel.delete(mAdapter.getStatusAt(viewHolder.getAdapterPosition()));
Toast.makeText(getActivity(), "Note Deleted", Toast.LENGTH_LONG).show();
}
}).attachToRecyclerView(recyclerView);
}
#Override
public void onStatusClick(Status status) {
Toast.makeText(getActivity(), "the id is " + status.getId(), Toast.LENGTH_SHORT).show();
Bundle bundle = new Bundle();
bundle.putInt("ID", status.getId());
bundle.putString("description", status.getDescription());
bundle.putString("title", status.getTitle());
Navigation.findNavController(getActivity().findViewById(R.id.recyclerLayout)).navigate(R.id.action_fragmentStatus_to_editStatusFragment, bundle);
}
}
'''
Adapter Code
'''
package com.nitin.roomrecyclerview;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.TextView;
import android.widget.Toast;
import androidx.activity.OnBackPressedCallback;
import androidx.annotation.NonNull;
import androidx.coordinatorlayout.widget.CoordinatorLayout;
import androidx.navigation.Navigation;
import androidx.recyclerview.widget.RecyclerView;
import com.nitin.roomrecyclerview.ui.home.HomeFragment;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Locale;
public class MyAdapter extends RecyclerView.Adapter<MyViewHolder> implements Filterable {
private static final String TAG = "TEST_1";
private List<Status> statuses;
private MyViewHolder.OnStatusListener listener;
ArrayList<Status> arrayList = new ArrayList<>();
Context context;
public MyAdapter(Context context, List<Status> statuses, MyViewHolder.OnStatusListener listener) {
this.statuses = statuses;
this.listener = listener;
this.context = context;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View view = inflater.inflate(R.layout.status_recyclerview, parent, false);
MyViewHolder myViewHolder = new MyViewHolder(view, listener, statuses);
return myViewHolder;
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, int position) {
Status status = statuses.get(position);
holder.title_template.setText(status.getTitle());
holder.description_template.setText(status.getDescription());
}
#Override
public int getItemCount() {
return statuses.size();
}
public void setStatuses(List<Status> newstatuses) {
this.statuses = newstatuses;
arrayList.addAll(statuses);
notifyDataSetChanged();
}
public Status getStatusAt(int position) {
return statuses.get(position);
}
#Override
public Filter getFilter() {
return new Filter() {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
constraint = constraint.toString().toLowerCase().trim();
statuses.clear();
if (constraint.length() == 0) {
statuses.addAll(arrayList);
} else {
for (Status item : arrayList) {
if (item.getTitle().toLowerCase(Locale.getDefault()).contains(constraint)
|| item.getDescription().toLowerCase(Locale.getDefault()).contains(constraint)) {
statuses.add(item);
}
}
}
FilterResults results = new FilterResults();
results.values = statuses;
results.count = statuses.size();
return results;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
if(results.count == 0){
Toast.makeText(context, "No Results found", Toast.LENGTH_LONG).show();
notifyDataSetChanged();
}else {
notifyDataSetChanged();
}
}
};
}
}
'''

call a method in a fragment, from a class that extends from RecyclerView.Adapter

I have a class that extends from a RecyclerView.Adapter, in that class I have two buttons, one to update and one to delete, the problem is that I want to use those buttons to call a method that is in another class that extends Fragments but not I know how to make the instance to my method, I also want to pass a parameter.
This is my class that extends from a RecyclerView.Adapter:
package com.example.enriq.examen_tareas_segundo_plano_enrique_espinosa.adapter;
import android.app.Activity;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.TextView;
import android.widget.Toast;
import com.example.enriq.examen_tareas_segundo_plano_enrique_espinosa.R;
import com.example.enriq.examen_tareas_segundo_plano_enrique_espinosa.tareasFragmento;
import java.util.ArrayList;
/**
* Created Enrique Espinosa.
*/
public class TareasAdapter extends RecyclerView.Adapter<TareasAdapter.UsuarioHolder>{
private Activity activity;
private ArrayList<Tareas> tareas;
public TareasAdapter(Activity activity, ArrayList<Tareas> tareas) {
this.activity = activity;
this.tareas = tareas;
}
public class UsuarioHolder extends RecyclerView.ViewHolder {
public TextView txtId;
public TextView txtNombreUsuario;
public TextView txtNota;
public TextView txtEstudiante;
public int pasId;
Button btnEliminar = (Button)itemView.findViewById(R.id.btnEliminar);
Button btnActualizar = (Button)itemView.findViewById(R.id.btnActualizar);
public UsuarioHolder(View itemView) {
super(itemView);
txtId = (TextView) itemView.findViewById(R.id.txt_id);
txtNombreUsuario = (TextView) itemView.findViewById(R.id.txt_nombre_usuario);
txtNota = (TextView) itemView.findViewById(R.id.txt_nota);
txtEstudiante = (TextView) itemView.findViewById(R.id.txtEstudiante);
}
}
#Override
public UsuarioHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = activity.getLayoutInflater().inflate(R.layout.plantilla_usuariosegundo, parent, false);
UsuarioHolder holder = new UsuarioHolder(view);
return holder;
}
#Override
public void onBindViewHolder(final UsuarioHolder holder, int position) {
holder.txtId.setText(tareas.get(position).getId());
holder.txtNombreUsuario.setText("Tarea: "+ tareas.get(position).getNombreTarea());
holder.txtNota.setText("Nota: "+ tareas.get(position).getNota());
holder.txtEstudiante.setText("Estudiante: "+ tareas.get(position).getEstudiante());
}
#Override
public int getItemCount() {
return tareas.size();
}
}
And this is my class that extends form a Fragment:
package com.example.enriq.examen_tareas_segundo_plano_enrique_espinosa;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.Volley;
import com.example.enriq.examen_tareas_segundo_plano_enrique_espinosa.adapter.Tareas;
import com.example.enriq.examen_tareas_segundo_plano_enrique_espinosa.adapter.TareasAdapter;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Enriq on 26/04/2018.
*/
public class tareasFragmento extends Fragment {
private String url = "http://192.168.1.128:8080/WebServiceExamenFinal/webapi/tareas";
private ArrayList<Tareas> estudiantes = new ArrayList<>();
//Si no funciona esto se puede borrar
AlertDialog alertDialog;
private List<Tareas> tareasList;
private TareasAdapter tareasAdapter;
private int assiId;
public tareasFragmento() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_tareas, container, false);
RecyclerView recyclerView = (RecyclerView) view.findViewById(R.id.recycler_list);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new GridLayoutManager(getContext(), 2,
GridLayoutManager.VERTICAL, false));
final TareasAdapter adapter = new TareasAdapter(getActivity(), estudiantes);
recyclerView.setAdapter(adapter);
RequestQueue queue = Volley.newRequestQueue(getContext());
final ProgressDialog dialog = new ProgressDialog(getContext());
dialog.setMessage("Por favor espere...");
dialog.show();
try {
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
deserializarJSONArray(response);
adapter.notifyDataSetChanged();
if (dialog.isShowing()) dialog.dismiss();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getActivity(),
"Error al realizar la peticiĆ³n\n" + error.getMessage(),
Toast.LENGTH_LONG).show();
if (dialog.isShowing()) dialog.dismiss();
}
});
queue.add(jsonArrayRequest);
}catch (Exception e) {
Toast.makeText(getActivity(),"El error es: "+e,Toast.LENGTH_LONG).show();
}
return view;
}
public void deserializarJSONArray(JSONArray jsonArray) {
for (int i = 0; i < jsonArray.length(); i++) {
try {
JSONObject item = jsonArray.getJSONObject(i);
Tareas tareas = new Tareas();
tareas.setId(item.getString("id"));
tareas.setNombreTarea(item.getString("nombreUsuario"));
tareas.setEstudiante(item.getString("estudiante"));
tareas.setNota(item.getString("nota"));
estudiantes.add(tareas);
} catch (JSONException e) {
Toast.makeText(getActivity(), "Error al procesar la respuesta de la peticiĆ³n: " + e,
Toast.LENGTH_SHORT).show();
}
}
}
public void delete(int id){
Toast.makeText(getActivity(),"Este es el id recibido: "+id,Toast.LENGTH_LONG).show();
}
public int getAssiId(){
Toast.makeText(getActivity(),"Estas en el get de tareas fragmento",Toast.LENGTH_LONG).show();
return assiId;
}
}
I tried doing something similar to this:
tareasFragmento tarea = new tareasFragmento();
tarea.eliminar(id);
But it returns this error:
Attemp to invoque a virtual method 'android.content.res.Resources
android.content.Context.getResources()' a null object refrences
I've updated your adapter.
public class TareasAdapter extends RecyclerView.Adapter<TareasAdapter.UsuarioHolder> {
private Activity activity;
private ArrayList<Tareas> tareas;
private OnClickButton callback;
public TareasAdapter(Activity activity, ArrayList<Tareas> tareas) {
this.activity = activity;
this.tareas = tareas;
}
public void setCallback(OnClickButton callback) {
this.callback = callback;
}
public class UsuarioHolder extends RecyclerView.ViewHolder {
public TextView txtId;
public TextView txtNombreUsuario;
public TextView txtNota;
public TextView txtEstudiante;
public int pasId;
Button btnEliminar;
Button btnActualizar;
public UsuarioHolder(View itemView) {
super(itemView);
txtId = (TextView) itemView.findViewById(R.id.txt_id);
txtNombreUsuario = (TextView) itemView.findViewById(R.id.txt_nombre_usuario);
txtNota = (TextView) itemView.findViewById(R.id.txt_nota);
txtEstudiante = (TextView) itemView.findViewById(R.id.txtEstudiante);
btnEliminar = (Button) itemView.findViewById(R.id.btnEliminar);
btnActualizar = (Button) itemView.findViewById(R.id.btnActualizar);
}
}
#Override
public UsuarioHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = activity.getLayoutInflater().inflate(R.layout.plantilla_usuariosegundo, parent, false);
UsuarioHolder holder = new UsuarioHolder(view);
holder.btnActualizar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
callback.onClickUpdate();
}
});
holder.btnEliminar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
callback.onClickDelete();
}
});
return holder;
}
#Override
public void onBindViewHolder(final UsuarioHolder holder, int position) {
holder.txtId.setText(tareas.get(position).getId());
holder.txtNombreUsuario.setText("Tarea: " + tareas.get(position).getNombreTarea());
holder.txtNota.setText("Nota: " + tareas.get(position).getNota());
holder.txtEstudiante.setText("Estudiante: " + tareas.get(position).getEstudiante());
}
#Override
public int getItemCount() {
return tareas.size();
}
public interface OnClickButton {
void onClickUpdate();
void onClickDelete();
}
}
EDIT:
Now make the fragment that uses this adapter implement the interface OnClickButton. you'll then be able to manipulate the click events in the activity which is the right place to manipulate/communicate with fragments.
Finally after initializing the adapter call:
adapter.setCallback(this);

NullException on my dynamic slider

I would like to ask how will I be able to handle the NullException every time that I reach the last object in my int[] array.
Here is my InformationTab
package com.example.aldrinjohn.milktracktest;
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
/**
* Created by Aldrin John on 3/20/2017.
*/
public class InformationTab extends Fragment{
ViewPager viewPager;
CustomSwipeAdapter adapter;
Button btnTrivia,btnBenefitB,btnBenefitM,btnPump,btnStoring,btnInfo;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.informationtab, container, false);
viewPager = (ViewPager)rootView.findViewById(R.id.view_pager);
btnTrivia = (Button)rootView.findViewById(R.id.trivia);
btnTrivia.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
GlobalVariables.buttonClick = "trivia";
adapter = new CustomSwipeAdapter(getActivity());
viewPager.setAdapter(adapter);
}
});
btnBenefitB = (Button)rootView.findViewById(R.id.benefit_babies);
btnBenefitB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
GlobalVariables.buttonClick = "benefitb";
adapter = new CustomSwipeAdapter(getActivity());
viewPager.setAdapter(adapter);
}
});
btnBenefitM = (Button)rootView.findViewById(R.id.benefit_mother);
btnBenefitM.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
GlobalVariables.buttonClick = "benefitm";
adapter = new CustomSwipeAdapter(getActivity());
viewPager.setAdapter(adapter);
}
});
btnPump = (Button)rootView.findViewById(R.id.pump);
btnPump.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
GlobalVariables.buttonClick = "pump";
adapter = new CustomSwipeAdapter(getActivity());
viewPager.setAdapter(adapter);
}
});
btnStoring = (Button)rootView.findViewById(R.id.storing);
btnStoring.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
GlobalVariables.buttonClick = "storing";
adapter = new CustomSwipeAdapter(getActivity());
viewPager.setAdapter(adapter);
}
});
btnInfo = (Button)rootView.findViewById(R.id.tips);
btnInfo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
GlobalVariables.buttonClick = "tips";
adapter = new CustomSwipeAdapter(getActivity());
viewPager.setAdapter(adapter);
}
});
return rootView;
}
}
and this is my
package com.example.aldrinjohn.milktracktest;
import android.content.Context;
import android.provider.ContactsContract;
import android.support.v4.view.PagerAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import com.google.android.gms.ads.formats.NativeAd;
import com.google.android.gms.tagmanager.Container;
/**
* Created by Aldrin John on 3/26/2017.
*/
public class CustomSwipeAdapter extends PagerAdapter{
private int[] trivia = {R.drawable.c1,R.drawable.c2,R.drawable.c3,R.drawable.c4, R.drawable.c5,R.drawable.c6};
private int[] benefitBaby = {R.drawable.c7,R.drawable.c8,R.drawable.c9};
private int[] benefitMother = {R.drawable.c91,R.drawable.c92};
private int[] info = {R.drawable.a1,R.drawable.a2,R.drawable.a3,R.drawable.a4,R.drawable.a5,R.drawable.a6,R.drawable.a7,
R.drawable.a8,R.drawable.a9,R.drawable.a91,R.drawable.a92};
private int[] storing = {R.drawable.b1,R.drawable.b2,R.drawable.b3,R.drawable.b4};
private int[] pump = {R.drawable.a21,R.drawable.a22,R.drawable.a23,R.drawable.a24,R.drawable.a25,R.drawable.a31,R.drawable.a32,
R.drawable.a33,R.drawable.a34,R.drawable.a35,R.drawable.pic1,R.drawable.pic2,R.drawable.pic3,R.drawable.pic4,R.drawable.pic5};
private Context ctx;
private LayoutInflater layoutInflater;
public CustomSwipeAdapter(Context ctx)
{
this.ctx = ctx;
}
#Override
public int getCount() {
return pump.length;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return (view==(LinearLayout)object);
}
#Override
public Object instantiateItem(ViewGroup container, int position){
layoutInflater = (LayoutInflater)ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View item_view = layoutInflater.inflate(R.layout.swipe_layout,container,false);
ImageView imgTrivia = (ImageView)item_view.findViewById(R.id.image_view);
if(GlobalVariables.buttonClick.equals("trivia"))
{
imgTrivia.setImageResource(trivia[position]);
}
else if (GlobalVariables.buttonClick.equals("benefitb"))
{
imgTrivia.setImageResource(benefitBaby[position]);
}
else if (GlobalVariables.buttonClick.equals("benefitm"))
{
imgTrivia.setImageResource(benefitMother[position]);
}
else if (GlobalVariables.buttonClick.equals("storing"))
{
imgTrivia.setImageResource(storing[position]);
}
else if (GlobalVariables.buttonClick.equals("tips"))
{
imgTrivia.setImageResource(info[position]);
}
else if (GlobalVariables.buttonClick.equals("pump"))
{
imgTrivia.setImageResource(pump[position]);
}
container.addView(item_view);
return item_view;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object){
container.removeView((LinearLayout)object);
}
}
SOLVED! I just used a global variable class that contains the number of slides that is clicked. and return it to getCount function.

Save, Share & Favourite Imageview in recyclerview

this codes contains a share button, download button, and a favourate button.
till now its working properly with favourate button, if i remove onClick method from ViewHolder.
I want to implement share/save button onClick share/download the Image in the ImageView in recyclerview.
Please ignore gramatical mistakes
This is my cardFragment Class.
import android.content.ContentResolver;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
public class CardFragment extends Fragment {
ArrayList<WonderModel> listitems = new ArrayList<>();
RecyclerView MyRecyclerView;
String Wonders[] = {"Chichen Itza","Christ the Redeemer","Great Wall of China","Machu Picchu","Petra","Taj Mahal","Colosseum"};
int Images[] = {R.drawable.chichen_itza,R.drawable.christ_the_redeemer,R.drawable.great_wall_of_china,R.drawable.machu_picchu,R.drawable.petra,R.drawable.taj_mahal,R.drawable.colosseum};
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
initializeList();
getActivity().setTitle("7 Wonders of the Modern World");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_card, container, false);
MyRecyclerView = (RecyclerView) view.findViewById(R.id.cardView);
MyRecyclerView.setHasFixedSize(true);
LinearLayoutManager MyLayoutManager = new LinearLayoutManager(getActivity());
MyLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
if (listitems.size() > 0 & MyRecyclerView != null) {
MyRecyclerView.setAdapter(new MyAdapter(listitems));
}
MyRecyclerView.setLayoutManager(MyLayoutManager);
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
public class MyAdapter extends RecyclerView.Adapter<MyViewHolder> {
private ArrayList<WonderModel> list;
public MyAdapter(ArrayList<WonderModel> Data) {
list = Data;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent,int viewType) {
// create a new view
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.recycle_items, parent, false);
MyViewHolder holder = new MyViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(final MyViewHolder holder, int position) {
holder.titleTextView.setText(list.get(position).getCardName());
holder.coverImageView.setImageResource(list.get(position).getImageResourceId());
holder.coverImageView.setTag(list.get(position).getImageResourceId());
holder.likeImageView.setTag(R.drawable.ic_like);
}
#Override
public int getItemCount() {
return list.size();
}
}
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView titleTextView;
public ImageView coverImageView;
public ImageView likeImageView;
public ImageView shareImageView;
public MyViewHolder(View v) {
super(v);
titleTextView = (TextView) v.findViewById(R.id.titleTextView);
coverImageView = (ImageView) v.findViewById(R.id.coverImageView);
likeImageView = (ImageView) v.findViewById(R.id.likeImageView);
shareImageView = (ImageView) v.findViewById(R.id.shareImageView);
likeImageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int id = (int)likeImageView.getTag();
if( id == R.drawable.ic_like){
likeImageView.setTag(R.drawable.ic_liked);
likeImageView.setImageResource(R.drawable.ic_liked);
Toast.makeText(getActivity(),titleTextView.getText()+" added to favourites",Toast.LENGTH_SHORT).show();
}else{
likeImageView.setTag(R.drawable.ic_like);
likeImageView.setImageResource(R.drawable.ic_like);
Toast.makeText(getActivity(),titleTextView.getText()+" removed from favourites",Toast.LENGTH_SHORT).show();
}
}
});
shareImageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Uri imageUri = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE +
"://" + getResources().getResourcePackageName(coverImageView.getId())
+ '/' + "drawable" + '/' + getResources().getResourceEntryName((int)coverImageView.getTag()));
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_STREAM,imageUri);
shareIntent.setType("image/jpeg");
startActivity(Intent.createChooser(shareIntent, getResources().getText(R.string.send_to)));
}
});
}
}
public void initializeList() {
listitems.clear();
for(int i =0;i<7;i++){
WonderModel item = new WonderModel();
item.setCardName(Wonders[i]);
item.setImageResourceId(Images[i]);
item.setIsfav(0);
item.setIsturned(0);
listitems.add(item);
}
}
}
Here is MainActivity.Java
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v7.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FragmentManager fm = getSupportFragmentManager();
Fragment fragment = fm.findFragmentById(R.id.fragmentContainer);
if (fragment == null) {
fragment = new CardFragment();
;
fm.beginTransaction()
.add(R.id.fragmentContainer, fragment)
.commit();
}
}
}
Create your ViewHolder Constructor Like this
public MyViewHolder(View v,Activity activity) {
super(v);
this.activity = activity
/////Remaining code
Now you able to get the activity context in your viewholder class.
Hope it will helps you!!

How to retain the values of radio buttons from listview in android on orientation change

I have different layouts for landscape and portrait mode. When I select the values from radio buttons in radio group and change the orientation , new layout is displayed and all values are vanished. Please Help.
package com.hp.opiniondesknew;
import android.content.Context;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.os.ParcelableCompat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
/**
* Created by HP on 15-12-2016.
*/
public class FragmentFeedback extends Fragment {
private ArrayList<Questions> questionsArrayList;
HashMap<Questions, String> mapAns=new HashMap<Questions, String>();
private MyAdapter myAdapter;
private ListView listFeedbackQuestions;
private Button btSubmitFeedback;
private String selectedAns;
ArrayList<String> rbAnswersArray = new ArrayList<>();
int yesCount=0,noCount=0;
Questions questionPojo;
public FragmentFeedback() {
// setRetainInstance(true);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view=inflater.inflate(R.layout.feedback_layout,container,false);
listFeedbackQuestions= (ListView)view.findViewById(R.id.opinion_desk_feedback_lv_questions);
btSubmitFeedback=(Button)view.findViewById(R.id.opinion_desk_feedback_bt_submit);
questionsArrayList= new ArrayList<Questions>();
addlistview();
initializeBtnSubmit(btSubmitFeedback);
return view;
}
private void initializeBtnSubmit( Button btSubmitFeedback) {
btSubmitFeedback.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//---------
try
{
for(Map.Entry m:mapAns.entrySet()){
// System.out.println(m.getKey"()+" "+m.getValue());
Log.e("key value",m.getKey()+""+m.getValue());
}
if(mapAns.size()==0 || mapAns.size()< questionsArrayList.size())
{
Toast.makeText(getContext(),"Ans all q",Toast.LENGTH_SHORT).show();
}
else
{
int countYes = Collections.frequency(mapAns.values(), "yes");
{
Log.e("yescount",countYes+"");
}
int countNo = Collections.frequency(mapAns.values(), "no");
{
Log.e("noCount",countNo+"");
Log.e("mapsize",mapAns.size()+"");
}
if(countYes>countNo)
{
Fragment someFragment = new FragmentTestimonial();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.replace(R.id.content_frame, someFragment ); // give your fragment container id in first parameter
// transaction.addToBackStack(null); // if written, this transaction will be added to backstack
transaction.commit();
Log.e("noCount",countNo+"");
Log.e("yescount",countYes+"");
// Log.e("yes is greater",rbAnswersArray.size()+"");
}
else
{
Fragment someFragment = new FragmentSuggestions();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.replace(R.id.content_frame, someFragment ); // give your fragment container id in first parameter
// transaction.addToBackStack(null); // if written, this transaction will be added to backstack
transaction.commit();
Log.e("noCount",countNo+"");
Log.e("yescount",countYes+"");
}
mapAns.clear();
}
}catch (Exception e){e.printStackTrace();}
//-----
}
});
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
getActivity().setTitle("Feedback");
}
public void addlistview()
{
try
{
for (int i=0;i<5;i++) {
Questions questions = new Questions();
// questions.setQuestion(i+"");
questions.setQuestion("Did you like the performance of the service?");
questions.setQuestionNo(i);
questionsArrayList.add(questions);
myAdapter = new MyAdapter(getContext(), questionsArrayList);
listFeedbackQuestions.setAdapter(myAdapter);
if(selectedState != null) {
listFeedbackQuestions.onRestoreInstanceState(selectedState);
}
// Log.e("pojo",questions.toString());
}
}
catch (Exception e){e.printStackTrace();}
}
public class MyAdapter extends BaseAdapter {
Context context;
ArrayList<Questions> questionsArrayList;
LayoutInflater inflator;
public MyAdapter(Context context, ArrayList<Questions> questionsArrayList) {
this.context = context;
this.questionsArrayList = questionsArrayList;
inflator= LayoutInflater.from(context);
}
#Override
public int getCount() {
return questionsArrayList.size();
}
#Override
public Object getItem(int position) {
return questionsArrayList.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// Questions questionsPojo= new Questions();
Holder holder= new Holder();
if(convertView==null)
{
convertView=inflator.inflate(R.layout.feedback_question_row,parent,false);
holder.tvQuestion=(TextView) convertView.findViewById(R.id.opinion_desk_feedback_tv_question);
holder.rGroupButtons=(RadioGroup)convertView.findViewById(R.id.opinion_desk_rg_yes_no);
holder.rbYes=(RadioButton) convertView.findViewById(R.id.opinion_desk_feedback_rb_yes);
holder.rbNo=(RadioButton)convertView.findViewById(R.id.opinion_desk_feedback_rb_no);
convertView.setTag(holder);
}
else
{
holder=(Holder)convertView.getTag();
}
questionPojo=questionsArrayList.get(position);
holder.tvQuestion.setText(questionsArrayList.get(position).getQuestion());
final Holder finalHolder = holder;
holder.rGroupButtons.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
if (finalHolder.rbYes.isChecked())
{
Log.e("no",position+"");
finalHolder.selectedAnswer="yes";
questionsArrayList.get(position).setAnswer(finalHolder.selectedAnswer);
selectedAns= questionsArrayList.get(position).getAnswer();
rbAnswersArray.add(selectedAns);
yesCount++;
}
else
{
Log.e("no",position+"");
finalHolder.selectedAnswer="no";
questionsArrayList.get(position).setAnswer(finalHolder.selectedAnswer);
selectedAns=questionsArrayList.get(position).getAnswer();
noCount++;
}
mapAns.put(questionsArrayList.get(position),selectedAns);
rbAnswersArray.add(selectedAns);
//
}
});
return convertView;
}
}
public class Holder
{
TextView tvQuestion;
RadioGroup rGroupButtons;
RadioButton rbYes,rbNo, rbSelectedAnswer;
String selectedAnswer, ansNo;
}
#Override
public void onDestroyOptionsMenu() {
super.onDestroyOptionsMenu();
}
// #Override
// public void onSaveInstanceState(Bundle outState) {
// super.onSaveInstanceState(outState);
// }
}
I am using listview and custom adapter for the listview. I am launching the fragment feedback from navigation activity. OnSavedInstanceState is not working, applictaion is crashing in onRestore method.I might be doing something wrong.
You have to use Bundle savedInstanceState to retrive your values.
You can save them in the onSaveInstanceState method.
Here a link to the documentation https://developer.android.com/guide/components/activities/activity-lifecycle.html

Categories

Resources