I'm trying to get favourite items in favourite list from main list.When i click on favourite icon in mainlist, favouritelist get updating but when i remove any favourite from favouritelist and trying to add more favourites from mainlist i get error index out of bound exception
MainActivity
import android.content.Context;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.Toast;
import java.util.Arrays;
import java.util.List;
public class MainActivity extends AppCompatActivity implements RecyclerViewClickListener{
RecyclerView simpleListView;
static Context ctx;
String diseaseList[];
SharedPreference sharedPreference;
DiseaseAdapter da;
List<String> newDiseaseList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ctx=this;
sharedPreference = new SharedPreference();
diseaseList= new String[]{"Abscess",
"Allergies",
"Amnesia",
"Anemia",
"Andropause",
"Angina",
"Weight Loss"};
Arrays.sort(diseaseList);
newDiseaseList = Arrays.asList(diseaseList);
simpleListView= (RecyclerView)findViewById(R.id.simpleListView);
LinearLayoutManager lm=new LinearLayoutManager(MainActivity.this);
simpleListView.setLayoutManager(lm);
/* DividerItemDecoration di=new DividerItemDecoration(MainActivity.this,lm.getOrientation());
simpleListView.addItemDecoration(di);*/
da=new DiseaseAdapter(newDiseaseList,ctx,this);
simpleListView.setAdapter(da);
simpleListView.setHasFixedSize(true);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_favorites:
Intent i=new Intent(this,Favourite.class);
this.startActivity(i);
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onResume() {
super.onResume();
da.notifyDataSetChanged();
}
#Override
public void recyclerViewListClicked(View view, int position) {
ImageView button = (ImageView) view.findViewById(R.id.imgbtn_favorite);
String tag = button.getTag().toString();
if (tag.equalsIgnoreCase("grey")) {
sharedPreference.addFavorite(ctx, newDiseaseList.get(position));
Toast.makeText(ctx,
"add to favourites",
Toast.LENGTH_SHORT).show();
button.setTag("red");
button.setImageResource(R.drawable.star_colour);
} else {
sharedPreference.removeFavorite(ctx, newDiseaseList.get(position));
button.setTag("grey");
button.setImageResource(R.drawable.ic_action_name);
Toast.makeText(ctx,
"removed from favourites",
Toast.LENGTH_SHORT).show();
}
}
}
Favourite.java
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;
import java.util.Collections;
import java.util.List;
public class Favourite extends AppCompatActivity implements RecyclerViewClickListener {
RecyclerView favoriteList;
SharedPreference sharedPreference;
List<String> favorites;
DiseaseAdapter diseaseAdapter;
static Context ctx;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_favourite);
ctx=this;
sharedPreference = new SharedPreference();
favorites = sharedPreference.getFavorites(ctx);
Collections.sort(favorites);
favoriteList = (RecyclerView)findViewById(R.id.favListView);
LinearLayoutManager lm=new LinearLayoutManager(ctx);
favoriteList.setLayoutManager(lm);
favoriteList.setHasFixedSize(true);
if (favorites == null) {
showAlert(getResources().getString(R.string.no_favorites_items),
getResources().getString(R.string.no_favorites_msg));
} else {
if (favorites.size() == 0) {
showAlert(
getResources().getString(R.string.no_favorites_items),
getResources().getString(R.string.no_favorites_msg));
}
if (favorites != null) {
diseaseAdapter = new DiseaseAdapter(favorites,ctx,this);
favoriteList.setAdapter(diseaseAdapter);
}
}
}
public void showAlert(String title, String message) {
if (ctx != null) {
AlertDialog alertDialog = new AlertDialog.Builder(ctx)
.create();
alertDialog.setTitle(title);
alertDialog.setMessage(message);
alertDialog.setCancelable(false);
// setting OK Button
alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
// activity.finish();
getFragmentManager().popBackStackImmediate();
}
});
alertDialog.show();
}
}
#Override
public void recyclerViewListClicked(View view, int position) {
ImageView button = (ImageView) view
.findViewById(R.id.imgbtn_favorite);
String tag = button.getTag().toString();
if (tag.equalsIgnoreCase("grey")) {
sharedPreference.addFavorite(ctx,
favorites.get(position));
Toast.makeText(
ctx,
ctx.getResources().getString(
R.string.add_favr),
Toast.LENGTH_SHORT).show();
button.setTag("red");
button.setImageResource(R.drawable.star_colour);
} else {
sharedPreference.removeFavorite(ctx,
favorites.get(position));
button.setTag("grey");
button.setImageResource(R.drawable.ic_action_name);
/* diseaseAdapter.remove(favorites
.get(position));*/
diseaseAdapter.remove(position);
Toast.makeText(
ctx,
ctx.getResources().getString(
R.string.remove_favr),
Toast.LENGTH_SHORT).show();
}
}
}
Adapter
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.support.v7.widget.RecyclerView;
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;
import java.util.List;
/**
* Created by admin on 12/4/2017.
*/
public class DiseaseAdapter extends RecyclerView.Adapter<DiseaseAdapter.DiseaseAdapterViewHolder> {
List <String> data;
Context ctx;
private static RecyclerViewClickListener itemListener;
SharedPreference sharedPreference;
DiseaseAdapter(List <String> data, Context ctx, RecyclerViewClickListener itemListener){
this.data=data;
this.ctx=ctx;
sharedPreference = new SharedPreference();
this.itemListener = itemListener;
notifyDataSetChanged();
}
#Override
public DiseaseAdapterViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater=LayoutInflater.from(parent.getContext());
View view= inflater.inflate(R.layout.activity_listview,parent,false);
return new DiseaseAdapterViewHolder(view);
}
#Override
public void onBindViewHolder(DiseaseAdapterViewHolder holder, int position) {
final String title=data.get(position);
holder.textView1.setText(title);
if (checkFavoriteItem(title)) {
holder.imageButton.setImageResource(R.drawable.star_colour);
holder.imageButton.setTag("red");
} else {
holder.imageButton.setImageResource(R.drawable.ic_action_name);
holder.imageButton.setTag("grey");
}
}
#Override
public int getItemCount() {
return data.size();
}
class DiseaseAdapterViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
TextView textView1;
ImageView imageButton;
public DiseaseAdapterViewHolder(View itemView) {
super(itemView);
textView1=(TextView) itemView.findViewById(R.id.textView);
imageButton=(ImageView)itemView.findViewById(R.id.imgbtn_favorite);
imageButton.setOnClickListener(this);
}
#Override
public void onClick(View v) {
notifyDataSetChanged();
itemListener.recyclerViewListClicked(v, this.getLayoutPosition());
}
}
/*Checks whether a particular product exists in SharedPreferences*/
public boolean checkFavoriteItem(String checkProduct) {
boolean check = false;
List<String> favorites = sharedPreference.getFavorites(ctx);
if (favorites != null) {
for (String product : favorites) {
if (product.equals(checkProduct)) {
check = true;
break;
}
}
}
return check;
}
public void add(String product) {
data.add(product);
notifyDataSetChanged();
}
public void remove(int position) {
data.remove(position);
notifyItemRemoved(position);
notifyItemRangeChanged(position, data.size());
notifyDataSetChanged();
}
}
SharedPreference
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import com.google.gson.Gson;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class SharedPreference {
public static final String PREFS_NAME = "PRODUCT_APP";
public static final String FAVORITES = "Product_Favorite";
public SharedPreference() {
super();
}
// This four methods are used for maintaining favorites.
public void saveFavorites(Context context, List<String> favorites) {
SharedPreferences settings;
Editor editor;
settings = context.getSharedPreferences(PREFS_NAME,
Context.MODE_PRIVATE);
editor = settings.edit();
Gson gson = new Gson();
String jsonFavorites = gson.toJson(favorites);
editor.putString(FAVORITES, jsonFavorites);
editor.commit();
}
public void addFavorite(Context context, String product) {
List<String> favorites = getFavorites(context);
if (favorites == null)
favorites = new ArrayList<String>();
favorites.add(product);
saveFavorites(context, favorites);
}
public void removeFavorite(Context context, String product) {
List<String> favorites = getFavorites(context);
if (favorites != null) {
favorites.remove(product);
saveFavorites(context, favorites);
}
}
public ArrayList<String> getFavorites(Context context) {
SharedPreferences settings;
List<String> favorites ;
settings = context.getSharedPreferences(PREFS_NAME,
Context.MODE_PRIVATE);
if (settings.contains(FAVORITES)) {
String jsonFavorites = settings.getString(FAVORITES, null);
Gson gson = new Gson();
String [] favoriteItems = (gson.fromJson(jsonFavorites,String [].class));
favorites = Arrays.asList(favoriteItems);
favorites = new ArrayList<String>(favorites);
} else
return null;
return (ArrayList<String>) favorites;
}
}
This is an error that i'm getting
FATAL EXCEPTION: main
Process: com.example.admin.fav, PID: 10974
java.lang.IndexOutOfBoundsException: Invalid index 3, size is 3
at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:255)
at java.util.ArrayList.get(ArrayList.java:308)
at com.example.admin.fav.Favourite.recyclerViewListClicked(Favourite.java:145)
at com.example.admin.fav.DiseaseAdapter$DiseaseAdapterViewHolder.onClick(DiseaseAdapter.java:90)
at android.view.View.performClick(View.java:5207)
at android.view.View$PerformClick.run(View.java:21168)
at android.os.Handler.handleCallback(Handler.java:746)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5443)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:728)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
Problem in your listener. You are using same adapter class for both MainActivity recylerview & Favourite activity recylerview. After you go back from favourite activity to Mainactivity still your listener read from Favourite activity. Thats the issue.
Solution
Create Static field to hold listener value here am created in SharedPreference Class:
public class SharedPreference {
public static final String PREFS_NAME = "PRODUCT_APP";
public static final String FAVORITES = "Product_Favorite";
/*Added*/
private static RecyclerViewClickListener listener;
public RecyclerViewClickListener getListener() {
return listener;
}
public void setListener(RecyclerViewClickListener listener) {
SharedPreference.listener = listener;
}
/*Added*/
...
}
Add this code to MainActivity & Favourite Activity 'OnCreate' method
sharedPreference.setListener(this);
public class MainActivity extends AppCompatActivity implements RecyclerViewClickListener{
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sharedPreference.setListener(this);
....
}
public class Favourite extends AppCompatActivity implements RecyclerViewClickListener{
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_favourite);
sharedPreference.setListener(this);
....
}
Change Adapter 'OnClick method' to
#Override
public void onClick(View v) {
notifyDataSetChanged();
itemListener = sharedPreference.getListener();
itemListener.recyclerViewListClicked(v, this.getLayoutPosition());
}
And Finally change in MainActivity 'resume' method
#Override
protected void onResume() {
super.onResume();
sharedPreference.setListener(this);
da.notifyDataSetChanged();
}
Hope it helps.!
In your DiseaseAdapterViewHolder change the onclick methode to,
#Override
public void onClick(View v) {
itemListener.recyclerViewListClicked(v, this.getLayoutPosition());
notifyDataSetChanged();
}
Related
I'm a beginner in Java and I'm trying to create a listener in my DialogFragment to notice my fragment that some book was removed. When the user removes a book, I want to call the removeBook method in BookFragment and update the recyclerview.
Here is my BookDialogFragment.java:
package com.compose.dietapp.ui.books;
import android.app.Dialog;
import android.content.DialogInterface;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.DialogFragment;
import java.util.Objects;
public class BookDialogFragment extends DialogFragment {
private final String nameToDelete;
private final int position;
private static String MESSAGE_TO_DIALOG_FRAGMENT;
public BookDialogFragment(String nameToDelete, int position) {
this.nameToDelete = nameToDelete;
this.position = position;
}
public static BookDialogFragment newInstance(String title, String nameToDelete, int position) {
BookDialogFragment frag = new BookDialogFragment(nameToDelete, position);
if (Objects.equals(nameToDelete, "none")) {
MESSAGE_TO_DIALOG_FRAGMENT = "Book removed!";
} else {
MESSAGE_TO_DIALOG_FRAGMENT = "Are you sure you want to remove the book '"
+ nameToDelete
+ "'?";
}
Bundle args = new Bundle();
args.putString("title", title);
frag.setArguments(args);
return frag;
}
#NonNull
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
assert getArguments() != null;
String title = getArguments().getString("title");
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(getActivity());
alertDialogBuilder.setTitle(title);
alertDialogBuilder.setMessage(MESSAGE_TO_DIALOG_FRAGMENT);
if (Objects.equals(MESSAGE_TO_DIALOG_FRAGMENT, "Book removed!")) {
alertDialogBuilder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (dialog != null) {
dialog.dismiss();
}
}
});
} else {
alertDialogBuilder.setPositiveButton("Remove", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// here I want to callback my fragment
BookFragment deleteBook = new BookFragment();
deleteBook.removeBook(nameToDelete, position);
Bundle result = new Bundle();
result.putBoolean("value", true);
getParentFragmentManager().setFragmentResult("removed", result);
}
});
alertDialogBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (dialog != null) {
dialog.dismiss();
}
}
});
}
return alertDialogBuilder.create();
}
#Override
public void onStart() {
super.onStart();
((AlertDialog) Objects.requireNonNull(getDialog())).getButton(AlertDialog.BUTTON_NEGATIVE)
.setTextColor(Color.rgb(128, 128, 128));
}
}
And here is my BookFragment.java:
package com.compose.dietapp.ui.books;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.compose.dietapp.R;
import com.compose.dietapp.database.DatabaseAccess;
import com.compose.dietapp.databinding.FragmentBookBinding;
import java.util.ArrayList;
public class BookFragment extends Fragment{
#SuppressLint("StaticFieldLeak")
private static Activity activity;
private RecyclerView recyclerView;
private final ArrayList<Book> itensBook = new ArrayList<Book>();
private BookAdapter bookAdapter;
public View onCreateView(#NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
activity = this.getActivity();
View v = inflater.inflate(R.layout.fragment_book, container, false);
recyclerView = (RecyclerView) v.findViewById(R.id.book_recycler);
instanciateBooks();
return v;
}
private void instanciateBooks() {
ArrayList<ArrayList<String>> bookDatabaseValues = getDatabaseData();
if (recyclerView != null && bookDatabaseValues != null) {
createItemBook(bookDatabaseValues);
createRecyclerViewBook();
}
}
public void removeBook(String nameToDelete, int position) {
getChildFragmentManager().setFragmentResultListener("removed",
this, new FragmentResultListener() {
#Override
public void onFragmentResult(#NonNull String requestKey, #NonNull Bundle bundle) {
String result = bundle.getString("value");
Log.i("result", result);
}
});
}
private void createRecyclerViewBook() {
recyclerView.setHasFixedSize(true);
bookAdapter = new BookAdapter(activity, itensBook);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(activity,
LinearLayoutManager.VERTICAL, false);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(bookAdapter);
}
private void createItemBook(ArrayList<ArrayList<String>> bookDatabaseValues) {
for (int i = 0; i < bookDatabaseValues.size(); i++) {
itensBook.add(new Book(
String.valueOf(bookDatabaseValues.get(i).get(0)),
String.valueOf(bookDatabaseValues.get(i).get(1)),
String.valueOf(bookDatabaseValues.get(i).get(2)),
String.valueOf(bookDatabaseValues.get(i).get(3)),
String.valueOf(bookDatabaseValues.get(i).get(4))
));
}
}
public static ArrayList<ArrayList<String>> getDatabaseData() {
if (activity != null) {
return getArrayListsFromDatabase();
}
return null;
}
private static ArrayList<ArrayList<String>> getArrayListsFromDatabase() {
DatabaseAccess databaseAccess = openDatabase();
ArrayList<ArrayList<String>> books = databaseAccess.getBook();
closeDatabase(databaseAccess);
return books;
}
private static void closeDatabase(DatabaseAccess databaseAccess) {
databaseAccess.close();
}
#NonNull
private static DatabaseAccess openDatabase() {
DatabaseAccess databaseAccess = DatabaseAccess.getInstance(activity);
databaseAccess.open();
return databaseAccess;
}
}
Here is my BookAdapter.java:
package com.compose.dietapp.ui.books;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentManager;
import androidx.recyclerview.widget.RecyclerView;
import com.compose.dietapp.R;
import java.io.InputStream;
import java.util.ArrayList;
public class BookAdapter extends RecyclerView.Adapter<BookViewHolder> {
public static FragmentManager supportFragment;
private final Context context;
private final ArrayList<Book> itens;
public BookAdapter(Context context, ArrayList<Book> itens) {
this.context = context;
this.itens = itens;
}
#NonNull
#Override
public BookViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.item_recycler_book, parent, false);
BookViewHolder viewHolder = new BookViewHolder(view);
supportFragment = ((AppCompatActivity)context).getSupportFragmentManager();
return viewHolder;
}
#Override
public void onBindViewHolder(#NonNull BookViewHolder bookViewHolder, int position) {
Book book = itens.get(position);
bookViewHolder.nome.setText(book.getName());
bookViewHolder.bookType.setText(book.getBookType());
imageInstanciate(bookViewHolder);
}
private void imageInstanciate(#NonNull BookViewHolder bookViewHolder) {
new DownloadImageFromInternet((ImageView) bookViewHolder.bookImage)
.execute("https://pbs.twimg.com/profile_images/630285593268752384/iD1MkFQ0.png");
}
private class DownloadImageFromInternet extends AsyncTask<String, Void, Bitmap> {
ImageView imageView;
public DownloadImageFromInternet(ImageView imageView) {
this.imageView = imageView;
}
protected Bitmap doInBackground(String... urls) {
String imageURL = urls[0];
Bitmap bimage = null;
try {
InputStream in = new java.net.URL(imageURL).openStream();
bimage = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error Message", e.getMessage());
e.printStackTrace();
}
return bimage;
}
protected void onPostExecute(Bitmap result) {
imageView.setImageBitmap(result);
}
}
#Override
public int getItemCount() {
return itens.size();
}
}
Here is my BookViewHolder.java:
package com.compose.dietapp.ui.books;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.fragment.app.FragmentManager;
import androidx.recyclerview.widget.RecyclerView;
import com.compose.dietapp.R;
public class BookViewHolder extends RecyclerView.ViewHolder {
TextView nome;
TextView bookType;
ImageView bookImage;
public BookViewHolder(#NonNull View itemView) {
super(itemView);
nome = itemView.findViewById(R.id.nome);
bookType = itemView.findViewById(R.id.email);
bookImage = itemView.findViewById(R.id.book_image);
itemView.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View view) {
int position = getLayoutPosition();
return true;
}
});
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String nomeDelete = nome.getText().toString();
int position = getLayoutPosition();
FragmentManager fm = BookAdapter.supportFragment;
BookDialogFragment bookDialogFragment =
BookDialogFragment.newInstance("Atenção:", nomeDelete, position);
bookDialogFragment.show(fm, "fragment_alert");
}
});
}
}
I've seen other similar solutions, but I didn't get to implement them in my code. Can anyone help me?
Going through your code, it doesn't seem like you're using Navigation Component. So let's do it this way.
Your BookDialogFragment is a child fragment to BookFragment. So basically, you should set a result in your dialog when remove button is clicked. Then set up a result listener code in you parent fragment (BookFragment), so as to get immediate result to act upon.
First part, set a result when remove is clicked
NonNull
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
...
if (Objects.equals(MESSAGE_TO_DIALOG_FRAGMENT, "Book removed!")) {
...
} else {
alertDialogBuilder.setPositiveButton("Remove", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// here I want to callback my fragment
BookFragment deleteBook = new BookFragment();
deleteBook.removeBook(nameToDelete, position);
Bundle result = new Bundle();
result.putBoolean("value", true);
getParentFragmentManager().setFragmentResult("removed", result);
}
});
alertDialogBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
...
}
}
}
Then, listen for and act on the result in you BookFragment, wherever you want to, with these lines.
getChildFragmentManager().setFragmentResultListener("removed", this, new FragmentResultListener() {
#Override
public void onFragmentResult(#NonNull String requestKey, #NonNull Bundle bundle) {
// We use a Boolean here, but any type that can be put in a Bundle is supported
Boolean result = bundle.getString("value");
// Do something with the result
}
});
PS: You can use constant variables where you have "removed" and "value" for accuracy.
Hope this helps :)
I want to get total price in Activity from Price and Quantity in Adapter, it's mean like qty * price = total_price.
Here is my Adapter for handling the list of Items Activity:
package com.example.aulaherbalfinal.Adapter;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.example.aulaherbalfinal.Model.DataModel;
import com.example.aulaherbalfinal.R;
import java.text.NumberFormat;
import java.util.List;
import java.util.Locale;
public class AdapterDataPembelian extends RecyclerView.Adapter<AdapterDataPembelian.HolderDataPembelian>{
private Context ctx;
private List<DataModel> listDataPembelian;
private int count;
public AdapterDataPembelian(Context ctx, List<DataModel> listDataPembelian) {
this.ctx = ctx;
this.listDataPembelian = listDataPembelian;
}
#NonNull
#Override
public HolderDataPembelian onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View layout = LayoutInflater.from(parent.getContext()).inflate(R.layout.card_item_pembelian, parent, false);
HolderDataPembelian holder = new HolderDataPembelian(layout);
return holder;
}
#Override
public void onBindViewHolder(#NonNull HolderDataPembelian holder, int position) {
DataModel dm = listDataPembelian.get(position);
holder.tvId.setText(String.valueOf(dm.getId()));
holder.tvBarang.setText(dm.getBarang());
holder.tvStok.setText("Stok : "+String.valueOf(dm.getStok()));
holder.tvHarga.setText(formatRupiah(Double.parseDouble(String.valueOf(dm.getHarga()))));
holder.jmlBarang.setText(String.valueOf(dm.getQuantity()));
//holder.totalHarga.setText(String.valueOf(dm.getTotalHarga()));
Intent intent = new Intent("custom-message");
holder.btnRemove.setOnClickListener(v -> {
minusCartItem(holder,listDataPembelian.get(position));
});
holder.btnAdd.setOnClickListener(v -> {
plusCartItem(holder,listDataPembelian.get(position));
});
}
private void plusCartItem(HolderDataPembelian holder, DataModel dataModel) {
dataModel.setQuantity(dataModel.getQuantity()+1);
//dataModel.setTotalHarga(Integer.parseInt(String.valueOf(dataModel.getQuantity()*Double.parseDouble(String.valueOf(dataModel.getHarga())))));
holder.jmlBarang.setText(new StringBuilder().append(dataModel.getQuantity()));
}
private void minusCartItem(HolderDataPembelian holder, DataModel dataModel) {
if (dataModel.getQuantity() > 0){
dataModel.setQuantity(dataModel.getQuantity()-1);
//dataModel.setTotalHarga(Integer.parseInt(String.valueOf(dataModel.getQuantity()*Double.parseDouble(String.valueOf(dataModel.getHarga())))));
holder.jmlBarang.setText(new StringBuilder().append(dataModel.getQuantity()));
} else {
holder.jmlBarang.setText("0");
}
}
#Override
public int getItemCount() {
return listDataPembelian.size();
}
public class HolderDataPembelian extends RecyclerView.ViewHolder {
TextView tvId, tvBarang, tvStok, tvHarga;
Button btnAdd, btnRemove;
TextView jmlBarang, totalHarga;
public HolderDataPembelian(#NonNull View itemView) {
super(itemView);
tvId = itemView.findViewById(R.id.tv_id);
tvBarang = itemView.findViewById(R.id.tv_barang);
tvStok = itemView.findViewById(R.id.tv_stok);
tvHarga = itemView.findViewById(R.id.tv_harga);
btnAdd = itemView.findViewById(R.id.btn_add);
btnRemove = itemView.findViewById(R.id.btn_remove);
jmlBarang = itemView.findViewById(R.id.jml_barang);
totalHarga = itemView.findViewById(R.id.total_harga);
}
}
private String formatRupiah(Double number){
Locale localeID = new Locale("IND", "ID");
NumberFormat numberFormat = NumberFormat.getCurrencyInstance(localeID);
String formatRupiah = numberFormat.format(number);
String[] split = formatRupiah.split(",");
int length = split[0].length();
return split[0].substring(0,2)+". "+split[0].substring(2,length);
}
public int getTotalPrice(){
int totalPrice = 0;
for (int i=0 i<listDataPembelian.size(); i++){
}
}
}
And here is my Activity
package com.example.aulaherbalfinal.Activity;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.cardview.widget.CardView;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.example.aulaherbalfinal.API.APIRequestData;
import com.example.aulaherbalfinal.API.RetroServer;
import com.example.aulaherbalfinal.Adapter.AdapterDataPembelian;
import com.example.aulaherbalfinal.Model.DataModel;
import com.example.aulaherbalfinal.Model.ResponseModel;
import com.example.aulaherbalfinal.R;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import java.util.ArrayList;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class PembelianActivity extends AppCompatActivity {
private RecyclerView rvData;
private RecyclerView.Adapter adData;
private RecyclerView.LayoutManager lmData;
private List<DataModel> listDataPembelian = new ArrayList<>();
private SwipeRefreshLayout srlData;
private ProgressBar pbData;
private TextView totalHarga;
private EditText jmlBarang;
#SuppressLint("ClickableViewAccessibility")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pembelian);
rvData = findViewById(R.id.rv_data);
lmData = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
rvData.setLayoutManager(lmData);
srlData = findViewById(R.id.srl_data);
pbData = findViewById(R.id.pb_data);
totalHarga = findViewById(R.id.total_harga);
jmlBarang = findViewById(R.id.jml_barang);
totalHarga = findViewById(R.id.total_harga);
//retrieveData();
CardView cvTotal = findViewById(R.id.cv_total);
rvData.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_MOVE){
cvTotal.setVisibility(View.INVISIBLE);
}
if (event.getAction() == MotionEvent.ACTION_UP){
cvTotal.setVisibility(View.VISIBLE);
}
return false;
}
});
BottomNavigationView bottom_navigation = findViewById(R.id.bottom_navigation);
bottom_navigation.setItemIconTintList(null);
bottom_navigation.setSelectedItemId(R.id.navigation_pembelian);
ImageView profile =findViewById(R.id.profile);
profile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(PembelianActivity.this, ProfileActivity.class);
startActivity(intent);
finish();
}
});
bottom_navigation.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch ( (item.getItemId())){
case R.id.navigation_stok:
startActivity(new Intent(getApplicationContext(), MainActivity.class));
overridePendingTransition(0, 0);
return true;
case R.id.navigation_pembelian:
return true;
case R.id.navigation_penjualan:
startActivity(new Intent(getApplicationContext(), PenjualanActivity.class));
overridePendingTransition(0, 0);
return true;
}
return false;
}
});
srlData.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
srlData.setRefreshing(true);
retrieveData();
srlData.setRefreshing(false);
}
});
}
#Override
protected void onResume() {
super.onResume();
retrieveData();
}
public void retrieveData(){
pbData.setVisibility(View.VISIBLE);
APIRequestData ardData = RetroServer.konekRetrofit().create(APIRequestData.class);
Call<ResponseModel> tampildata = ardData.ardRetrieveData();
tampildata.enqueue(new Callback<ResponseModel>() {
#Override
public void onResponse(Call<ResponseModel> call, Response<ResponseModel> response) {
int kode = response.body().getKode();
String pesan = response.body().getPesan();
//Toast.makeText(MainActivity.this, "Kode : "+kode+" | Pesan : "+pesan, Toast.LENGTH_SHORT).show();
listDataPembelian = response.body().getData();
adData = new AdapterDataPembelian(PembelianActivity.this, listDataPembelian);
rvData.setAdapter(adData);
adData.notifyDataSetChanged();
pbData.setVisibility(View.INVISIBLE);
}
#Override
public void onFailure(Call<ResponseModel> call, Throwable t) {
Toast.makeText(PembelianActivity.this, "Gagal Menghubungi Server", Toast.LENGTH_SHORT).show();
pbData.setVisibility(View.INVISIBLE);
}
});
}
}
Here is my app
I would do something like this:
Create an Interface for your activity to implement:
public interface CallbackIF {
double tally(double amount, int quantity)
}
public class PembelianActivity extends AppCompatActivity implements CallbackIF {
#Override
public double tally(double amount, int quantity) {
return amount * quantity;
}
}
Then when you initialize your recyclerview adapter pass in the interface like so:
adData = new AdapterDataPembelian(PembelianActivity.this, listDataPembelian, PembelianActivity.this);
And change your constructor for the data adapter to be
private CallbackIF callback;
public AdapterDataPembelian(Context ctx, List<DataModel> listDataPembelian, CallbackIF callback) {
this.ctx = ctx;
this.listDataPembelian = listDataPembelian;
this.callback = callback;
}
Then in your onClicklistener for your list / wherever you want to trigger a tally just call
double value = callback.tally(amount, quantity);
If you have any questions please ask
I try to passing data from cardview when clicked to DetailFragment, in this case I try to use interface in my adapter, but I get an error a null object reference in mOnItemClickListener.onClick(i).
I try to passing data from cardview when clicked to DetailFragment, in this case I try to use interface in my adapter.
I want to passing data to DetailMoviesFragment Class.
this is my CardviewMovieAdapter Class
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import java.util.ArrayList;
public class CardviewMovieAdapter extends RecyclerView.Adapter<CardviewMovieAdapter.CardViewViewHolder> {
private ArrayList<Movie> listMovie;
Context context;
OnItemClickListener mOnItemClickListener;
public void setListMovie(ArrayList<Movie> listMovie) {
this.listMovie = listMovie;
}
public ArrayList<Movie> getListMovie() {
return listMovie;
}
public interface OnItemClickListener {
void onClick(int position);
}
public void setOnItemClickListener(final OnItemClickListener mItemClickListener) {
this.mOnItemClickListener = mItemClickListener;
}
public CardviewMovieAdapter(ArrayList<Movie> listMovie, Context context) {
this.listMovie = listMovie;
this.context = context;
}
#NonNull
#Override
public CardviewMovieAdapter.CardViewViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.list_movie, viewGroup,false);
return new CardViewViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull final CardviewMovieAdapter.CardViewViewHolder cardViewViewHolder, final int i) {
final Movie movie = listMovie.get(i);
Glide.with(cardViewViewHolder.itemView.getContext())
.load(movie.getImageMovie())
.apply(new RequestOptions().override(350, 550))
.into(cardViewViewHolder.imgPhoto);
cardViewViewHolder.tvTitle.setText(movie.getTitleMovie());
cardViewViewHolder.tvDesc.setText(movie.getDescription());
cardViewViewHolder.btnDetail.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(cardViewViewHolder.itemView.getContext(), "Detail "+
listMovie.get(cardViewViewHolder.getAdapterPosition()).getTitleMovie(), Toast.LENGTH_SHORT).show();
}
});
cardViewViewHolder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(cardViewViewHolder.itemView.getContext(), "Kamu Memilih "+movie.getTitleMovie(), Toast.LENGTH_SHORT).show();
mOnItemClickListener.onClick(i);
}
});
// cardViewViewHolder.itemView.setOnClickListener(new View.OnClickListener() {
// #Override
// public void onClick(View v) {
// Toast.makeText(cardViewViewHolder.itemView.getContext(), "Kamu Memilih "+movie.getTitleMovie(), Toast.LENGTH_SHORT).show();
// }
// });
}
#Override
public int getItemCount() {
return listMovie.size();
}
public class CardViewViewHolder extends RecyclerView.ViewHolder {
ImageView imgPhoto;
TextView tvTitle, tvDesc;
Button btnDetail;
public CardViewViewHolder(#NonNull View itemView) {
super(itemView);
imgPhoto = itemView.findViewById(R.id.img_item_photo);
tvTitle = itemView.findViewById(R.id.tv_title);
tvDesc = itemView.findViewById(R.id.tv_desc);
btnDetail = itemView.findViewById(R.id.btn_detail);
}
}
}
This is my MoviesFragment Class
import android.content.Intent;
import android.content.res.TypedArray;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.widget.CardView;
import android.support.v7.widget.LinearLayoutManager;
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.Button;
import android.widget.ListView;
import java.util.ArrayList;
/**
* A simple {#link Fragment} subclass.
*/
public class MoviesFragment extends Fragment implements View.OnClickListener{
private RecyclerView rvMovie;
private String[] dataMovieTitle;
private String[] dataDescription;
private TypedArray dataPhoto;
private ArrayList<Movie> movies;
Button btnDetail;
private CardviewMovieAdapter adapter;
View view;
final static String KEY = "KEY";
public MoviesFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
view = inflater.inflate(R.layout.fragment_movies, container, false);
//adapter = new CardviewMovieAdapter(movies,getContext());
rvMovie = view.findViewById(R.id.rv_movies);
prepare();
addItem();
showRecyclerCardView();
adapter = new CardviewMovieAdapter(movies, getContext());
adapter.setOnItemClickListener(new CardviewMovieAdapter.OnItemClickListener() {
#Override
public void onClick(int position) {
final Movie movie = movies.get(position);
DetailMoviesFragment detailMoviesFragment = new DetailMoviesFragment();
// Bundle mBundle = new Bundle();
// mBundle.putString(detailMoviesFragment.EXTRA_TITLE, movie.getTitleMovie());
// mBundle.putString(detailMoviesFragment.EXTRA_DESCRIPTION, movie.getDescription());
// mBundle.putInt(detailMoviesFragment.EXTRA_PHOTO, movie.getImageMovie());
// detailMoviesFragment.setArguments(mBundle);
MoviesFragment.newInstance(movie.getTitleMovie(), movie.getDescription(), movie.getImageMovie());
FragmentManager mFragmentManager = getFragmentManager();
if (mFragmentManager!= null) {
FragmentTransaction mFragmentTransaction = mFragmentManager.beginTransaction();
mFragmentTransaction.replace(R.id.containterFragment, detailMoviesFragment, DetailMoviesFragment.class.getSimpleName());
mFragmentTransaction.addToBackStack(null);
mFragmentTransaction.commit();
}
}
});
return view;
}
public static MoviesFragment newInstance(String title, String desc, int image) {
MoviesFragment moviesFragment = new MoviesFragment();
Bundle args = new Bundle();
args.putInt("image", image);
args.putString("title", title);
args.putString("desc", desc);
moviesFragment.setArguments(args);
return moviesFragment;
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
private void showRecyclerCardView(){
rvMovie.setLayoutManager(new LinearLayoutManager(getActivity()));
CardviewMovieAdapter adapter = new CardviewMovieAdapter(movies,getActivity());
rvMovie.setAdapter(adapter);
}
private void prepare() {
dataMovieTitle = getResources().getStringArray(R.array.data_movie_name);
dataDescription = getResources().getStringArray(R.array.data_desc_movie);
dataPhoto = getResources().obtainTypedArray(R.array.data_photo_movie);
}
private void addItem(){
movies = new ArrayList<>();
for (int i=0; i < dataMovieTitle.length; i++){
Movie movie = new Movie();
movie.setImageMovie(dataPhoto.getResourceId(i, -1));
movie.setTitleMovie(dataMovieTitle[i]);
movie.setDescription(dataDescription[i]);
movies.add(movie);
}
}
#Override
public void onClick(View v) {
if(v.getId() == R.id.card_view){
}
}
}
and this is DetailMoviesActivity Class
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import com.squareup.picasso.Picasso;
public class DetailMovieActivity extends AppCompatActivity {
Movie movie;
TextView tvTitle, tvDesc;
ImageView ivMovie;
Button btnDetail;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail_movie);
initView();
}
private void initView() {
movie = (Movie) getIntent().getSerializableExtra("informasi");
String judul = movie.getTitleMovie();
String desc = movie.getDescription();
int img = movie.getImageMovie();
tvTitle.setText(judul);
tvDesc.setText(desc);
Picasso.get().load(img).into(ivMovie);
}
}
You can try with delete the setOnItemClickListener and call intent from cardViewViewHolder.itemView.setOnClickListener
I am developing attendance system and i have a listview with students name i want to programatically check or uncheck the radio buttons in the listview when the scanned qr matchs the student name I tried to do it in the ontextchengeListner method of txtresult but the text is changing many time even in reading a single qr
This are my java classes
CustomAdapter.java
package com.attendance.olana.qr_scanner;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CompoundButton;
import android.widget.RadioButton;
import android.widget.TextView;
import java.util.ArrayList;
/**
* Created by olana on 23/03/2018.
*/
public class CustomAdapter extends BaseAdapter {
Context context;
String[] questionsList;
public static String message;
LayoutInflater inflter;
public static TextView question ;
public static RadioButton yes,no ;
public static ArrayList<String> selectedAnswers;
public CustomAdapter(Context applicationContext, String[] questionsList) {
this.context = context;
this.questionsList = questionsList;
// initialize arraylist and add static string for all the questions
selectedAnswers = new ArrayList<>();
for (int i = 0; i < questionsList.length; i++) {
selectedAnswers.add("Not Attempted");
}
inflter = (LayoutInflater.from(applicationContext));
}
#Override
public int getCount() {
return questionsList.length;
}
#Override
public Object getItem(int i) {
return null;
}
#Override
public long getItemId(int i) {
return 0;
}
#Override
public View getView(final int i, View view, ViewGroup viewGroup) {
view = inflter.inflate(R.layout.main, null);
// get the reference of TextView and Button's
question = (TextView) view.findViewById(R.id.question);
yes = (RadioButton) view.findViewById(R.id.yes);
no = (RadioButton) view.findViewById(R.id.no);
// perform setOnCheckedChangeListener event on yes button
yes.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// set Yes values in ArrayList if RadioButton is checked
if (isChecked)
selectedAnswers.set(i, "Present");
}
});
// perform setOnCheckedChangeListener event on no button
no.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// set No values in ArrayList if RadioButton is checked
if (isChecked)
selectedAnswers.set(i, "Absent");
}
});
// set the value in TextView
question.setText(questionsList[i]);
return view;
}
}
list.java
package com.attendance.olana.qr_scanner;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.Toast;
/**
* Created by olana on 23/03/2018.
*/
public class list extends AppCompatActivity {
ListView simpleList;
public static String[] questions;
Button submit,scan;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list);
scan =(Button)findViewById(R.id.scan);
// get the string array from string.xml file
questions = getResources().getStringArray(R.array.student);
// get the reference of ListView and Button
simpleList = (ListView) findViewById(R.id.simpleListView);
submit = (Button) findViewById(R.id.submit);
// set the adapter to fill the data in the ListView
CustomAdapter customAdapter = new CustomAdapter(getApplicationContext(), questions);
simpleList.setAdapter(customAdapter);
scan.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i;
i = new Intent(list.this,MainActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivity(i);
}
});
// perform setOnClickListerner event on Button
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String message = "";
// get the value of selected answers from custom adapter
for (int i = 0; i < CustomAdapter.selectedAnswers.size(); i++) {
message = message + "\n" + (i + 1) + " " + CustomAdapter.selectedAnswers.get(i);
}
// display the message on screen with the help of Toast.
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show();
}
});
}
}
MainActivity.java
package com.attendance.olana.qr_scanner;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Vibrator;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.util.SparseArray;
import android.view.Menu;
import android.view.MenuItem;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.vision.CameraSource;
import com.google.android.gms.vision.Detector;
import com.google.android.gms.vision.barcode.Barcode;
import com.google.android.gms.vision.barcode.BarcodeDetector;
import java.io.IOException;
import java.util.jar.Manifest;
public class MainActivity extends AppCompatActivity {
BarcodeDetector barcodeDetector;
SurfaceView camerapreview;
CameraSource cameraSource;
TextView txtresult;
String message;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button finish = (Button) findViewById(R.id.finish);
//Button scan = (Button) findViewById(R.id.scan);
finish.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show();
}
});
camerapreview = (SurfaceView) findViewById(R.id.camerapreview);
txtresult = (TextView) findViewById(R.id.txtresult);
barcodeDetector = new BarcodeDetector.Builder(this)
.setBarcodeFormats(Barcode.QR_CODE)
.build();
cameraSource = new CameraSource
.Builder(this, barcodeDetector)
.setRequestedPreviewSize(640, 480)
.build();
//add event
camerapreview.getHolder().addCallback(new SurfaceHolder.Callback() {
#Override
public void surfaceCreated(SurfaceHolder holder) {
try {
cameraSource.start(camerapreview.getHolder());
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
cameraSource.stop();
}
});
barcodeDetector.setProcessor(new Detector.Processor<Barcode>() {
#Override
public void release() {
try {
cameraSource.start(camerapreview.getHolder());
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void receiveDetections(Detector.Detections<Barcode> detections) {
final SparseArray<Barcode> qrcodes = detections.getDetectedItems();
if (qrcodes.size() != 0) {
txtresult.post(new Runnable() {
#Override
public void run() {
//create vibration
Vibrator vibrator = (Vibrator) getApplicationContext().getSystemService(Context.VIBRATOR_SERVICE);
vibrator.vibrate(100);
txtresult.setText(qrcodes.valueAt(0).displayValue);
//barcodeDetector.release();
}
});
}
}
});
}
}
Please tell me where i can implement these the programatically checking or unchecking the radio button when the name in the listview matchs the scanned qr please help me
I've got this error, but I don't know how to resolve this error.
Error: Fragments should be static such that they can be re-instantiated by the system, and anonymous classes are not static [ValidFragment]
Please help me if you know how to solve
This is the MainActivity.java
import android.annotation.TargetApi;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.res.ColorStateList;
import android.content.res.Configuration;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.design.widget.Snackbar;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v4.view.GravityCompat;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GoogleApiAvailability;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private DrawerLayout mDrawerLayout;
private String keyPref = "test";
private SharedPreferences pref;
private static SharedPreferences.Editor editor;
private static ViewPager view;
private FoodListFragment makanan = new FoodListFragment() {
#Override
public void doRefresh() {
updateData();
}
};
private FoodListFragment minuman = new FoodListFragment() {
#Override
public void doRefresh() {
updateData();
}
};
private FoodListFragment snack = new FoodListFragment() {
#Override
public void doRefresh() {
updateData();
}
};
private Adapter adapter = new Adapter(getSupportFragmentManager());
private static final int PLAY_SERVICES_RESOLUTION_REQUEST = 4343;
private BroadcastReceiver mRegistrationBroadcastReceiver;
private static ProgressDialog loading;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pref = getApplicationContext().getSharedPreferences(keyPref, MODE_PRIVATE);
editor = pref.edit();
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
final ActionBar ab = getSupportActionBar();
ab.setHomeAsUpIndicator(R.drawable.ic_menu);
ab.setDisplayHomeAsUpEnabled(true);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
if (navigationView != null) {
setupDrawerContent(navigationView);
}
ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
if (viewPager != null) {
setupViewPager(viewPager);
}
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setBackgroundTintList(ColorStateList.valueOf(Color.rgb(183,28,28)));
fab.setOnClickListener(new View.OnClickListener() {
#TargetApi(Build.VERSION_CODES.LOLLIPOP)
#Override
public void onClick(View view) {
Intent intent = new Intent(getApplicationContext(), CartActivity.class);
MainActivity.this.startActivity(intent);
}
});
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
DBHelper db = new DBHelper(this);
mRegistrationBroadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
//mRegistrationProgressBar.setVisibility(ProgressBar.GONE);
SharedPreferences sharedPreferences =
PreferenceManager.getDefaultSharedPreferences(context);
boolean sentToken = sharedPreferences
.getBoolean(QuickstartPreferences.SENT_TOKEN_TO_SERVER, false);
}
};
loading = new ProgressDialog(this);
loading.setMessage("Loading");
loading.setTitle("Menu");
updateData();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
return true;
}
#Override
protected void onPause() {
super.onPause();
LocalBroadcastManager.getInstance(this).unregisterReceiver(mRegistrationBroadcastReceiver);
}
#Override
protected void onResume() {
super.onResume();
LocalBroadcastManager.getInstance(this).registerReceiver(mRegistrationBroadcastReceiver,
new IntentFilter(QuickstartPreferences.REGISTRATION_COMPLETE));
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
mDrawerLayout.openDrawer(GravityCompat.START);
return true;
}
return super.onOptionsItemSelected(item);
}
public void updateData() {
ServerHelper server = new ServerHelper() {
#Override
public void onStart() {
loading.show();
}
#Override
public void onFinish() {
loading.dismiss();
}
#Override
public void onSuccess(int statusCode, String response) {
try {
editor.putString("response", response);
editor.commit();
makanan.clearFood();
minuman.clearFood();
snack.clearFood();
JSONArray foods = new JSONArray(response);
for (int i = 0; i <= foods.length()-1; i++) {
JSONObject object = foods.getJSONObject(i);
JSONObject subs = object.getJSONObject("SubCategory");
FoodCategory addFood = new FoodCategory(subs.getString("name"), subs.getString("photo"));
if (subs.getString("categories_id").contains("1")) {
makanan.addFood(addFood);
} else if (subs.getString("categories_id").contains("2")) {
minuman.addFood(addFood);
} else if (subs.getString("categories_id").contains("3")) {
snack.addFood(addFood);
}
}
makanan.doneRefresh();
minuman.doneRefresh();
snack.doneRefresh();
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(view.getContext(),"Terjadi masalah koneksi, silahkan coba kembali", Toast.LENGTH_LONG).show();
}
loading.dismiss();
}
#Override
public void onFailure(int statusCode, String response) {
if (view != null) {
Snackbar.make(view, "Terjadi Masalah Koneksi", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
} else {
Toast.makeText(MainActivity.this,"Terjadi Masalah Koneksi", Toast.LENGTH_LONG).show();
}
makanan.doneRefresh();
minuman.doneRefresh();
snack.doneRefresh();
loading.dismiss();
}
};
server.getAllSubs();
}
private void setupViewPager(ViewPager viewPager) {
makanan.setRetainInstance(true);
minuman.setRetainInstance(true);
snack.setRetainInstance(true);
adapter.addFragment(makanan, "Makanan");
adapter.addFragment(minuman, "Minuman");
adapter.addFragment(snack, "Snack");
viewPager.setAdapter(adapter);
updateData();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
}
private void setupDrawerContent(final NavigationView navigationView) {
View header = navigationView.getHeaderView(0);
TextView username = (TextView) header.findViewById(R.id.main_username);
DBHelper db = new DBHelper(this);
username.setText(db.getUsers().getName());
navigationView.setNavigationItemSelectedListener(
new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.nav_home: {
menuItem.setChecked(true);
break;
}
case R.id.nav_order: {
navigationView.getMenu().getItem(0).setChecked(true);
Intent order = new Intent(MainActivity.this, OrderActivity.class);
startActivity(order);
break;
}
case R.id.nav_cart: {
navigationView.getMenu().getItem(0).setChecked(true);
Intent cart = new Intent(MainActivity.this, CartActivity.class);
startActivity(cart);
break;
}
case R.id.nav_logout: {
AlertDialog.Builder dialog = new AlertDialog.Builder(MainActivity.this);
dialog.setMessage("Anda yakin ingin logout akun anda ?");
dialog.setNegativeButton("Batal",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
}
});
dialog.setPositiveButton("Keluar",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
DBHelper logout = new DBHelper(MainActivity.this);
logout.clearSPConfig();
LocalBroadcastManager.getInstance(MainActivity.this).unregisterReceiver(mRegistrationBroadcastReceiver);
Intent goLogin = new Intent(MainActivity.this, LoginMainActivity.class);
startActivity(goLogin);
}
});
AlertDialog alertDialog = dialog.create();
alertDialog.show();
}
}
mDrawerLayout.closeDrawers();
return true;
}
});
}
public static class Adapter extends FragmentPagerAdapter {
private final List<Fragment> mFragments = new ArrayList<>();
private final List<String> mFragmentTitles = new ArrayList<>();
public Adapter(FragmentManager fm) {
super(fm);
}
public void addFragment(Fragment fragment, String title) {
mFragments.add(fragment);
mFragmentTitles.add(title);
}
#Override
public Fragment getItem(int position) {
return mFragments.get(position);
}
#Override
public int getCount() {
return mFragments.size();
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitles.get(position);
}
}
}
and this is the fragment class FoodListFragment.java
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.annotation.UiThread;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.InflateException;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
public abstract class FoodListFragment extends Fragment {
private ArrayList<FoodCategory> foodList = new ArrayList<FoodCategory>();
private RecyclerView rv;
private RecyclerViewAdapter adapter;
private SwipeRefreshLayout swipeLayout;
private View view;
FoodListFragment() {
}
public void addFoods(ArrayList<FoodCategory> food) {
foodList = food;
if (adapter != null) {
adapter.notifyDataSetChanged();
}
}
public void addFood(FoodCategory food) {
foodList.add(food);
if (adapter != null) {
adapter.notifyDataSetChanged();
}
}
public void clearFood() {
foodList.clear();
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// final RecyclerView rv = (RecyclerView) inflater.inflate(R.layout.fragment_food_list, container, false);
view = inflater.inflate(R.layout.fragment_food_list, null);
swipeLayout = (SwipeRefreshLayout) view.findViewById(R.id.swipe_container);
swipeLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
doRefresh();
}
});
swipeLayout.setColorSchemeColors(Color.RED, Color.GRAY);
RecyclerView rv = (RecyclerView) view.findViewById(R.id.recyclerview);
setupRecyclerView(rv);
return view;
}
private void setupRecyclerView(final RecyclerView recyclerView) {
//recyclerView.setLayoutManager(new LinearLayoutManager(recyclerView.getContext()));
recyclerView.setLayoutManager(new GridLayoutManager(recyclerView.getContext(), 2));
recyclerView.setHasFixedSize(true);
setRetainInstance(true);
adapter = new RecyclerViewAdapter(getActivity(),foodList);
recyclerView.setAdapter(adapter);
}
public void doneRefresh(){
if (swipeLayout != null) {
swipeLayout.setRefreshing(false);
}
}
public abstract void doRefresh();
}
You are declaring your Fragment as abstract class. Abstract class can't be instantiated. It can be used only as a base class. The way you are trying to use it (anonymous class) is not possible in Android framework. A Fragment class must be a subclass of Fragment (or an existing subclass of it) and concrete.
Remove abstract keyword
public class FoodListFragment extends Fragment {
Things your are trying to achieve with
public abstract void doRefresh();
should be done using an interface.