I am trying to add a second AutoCompleteTextView (that gets objects from a Web API) in a fragment, but it never retrieves anything.
Currently testing on an Emulator, on API level 24. I have previously tried the code for this AutoCompleteTextView in another activity and it worked as intended there.
Fragment Code
package com.advatek.timewin.fragments;
import android.app.AlertDialog;
import android.content.Context;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v7.widget.AppCompatAutoCompleteTextView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
import com.advatek.timewin.MainActivity;
import com.advatek.timewin.R;
import com.advatek.timewin.helper.APICall;
import com.advatek.timewin.helper.APIHelper;
import com.advatek.timewin.helper.AutoSuggestAdapter;
import com.advatek.timewin.helper.JSONHelper;
import com.advatek.timewin.helper.JobSuggestAdapter;
import com.advatek.timewin.models.Employee;
import com.advatek.timewin.models.Function;
import com.advatek.timewin.models.PayPeriod;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import org.json.JSONArray;
import org.json.JSONException;
import java.util.ArrayList;
import java.util.List;
/**
* A simple {#link Fragment} subclass.
* Activities that contain this fragment must implement the
* {#link Clock.OnFragmentInteractionListener} interface
* to handle interaction events.
* Use the {#link Clock#newInstance} factory method to
* create an instance of this fragment.
*/
public class Clock extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private Context context;
Handler handler;
Handler jobHandler;
AppCompatAutoCompleteTextView txtEmpSearch;
AppCompatAutoCompleteTextView txtJobSearch;
AutoSuggestAdapter autoAdapter;
JobSuggestAdapter jobAdapter;
private static final int TRIGGER_AUTO_COMPLETE = 100;
private static final long AUTO_COMPLETE_DELAY = 300;
private static List<Function> functionList;
PayPeriod period;
private TextView txtPayWeek;
Spinner spnJobs;
Button btnSignIn;
private OnFragmentInteractionListener mListener;
public Clock() {
// Required empty public constructor
}
public AppCompatAutoCompleteTextView getTextView(){
return txtEmpSearch;
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment Clock.
*/
// TODO: Rename and change types and number of parameters
public static Clock newInstance(String param1, String param2) {
Clock fragment = new Clock();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
context = getContext();
period = new PayPeriod();
functionList = new ArrayList<>();
try{
WeekTask wTask = new WeekTask();
wTask.execute().get();
// JobTask task = new JobTask();
// task.execute();
txtJobSearch = (AppCompatAutoCompleteTextView)getView().findViewById(R.id.txtEmpLookup);
jobAdapter = new JobSuggestAdapter(context, R.layout.support_simple_spinner_dropdown_item);
txtJobSearch.setThreshold(2);
txtJobSearch.setAdapter(jobAdapter);
// Fires when an Employee is selected
txtJobSearch.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, final View view, int position, long id) {
InputMethodManager in = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
in.hideSoftInputFromWindow(view.getApplicationWindowToken(), 0);
Function job = (Function) parent.getItemAtPosition(position);
((MainActivity)getActivity()).setJob(job);
}
});
txtJobSearch.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
jobHandler.removeMessages(TRIGGER_AUTO_COMPLETE);
jobHandler.sendEmptyMessageDelayed(TRIGGER_AUTO_COMPLETE, AUTO_COMPLETE_DELAY);
}
#Override
public void afterTextChanged(Editable s) {
if(txtJobSearch.getText().toString().equals("")){
}
}
});
jobHandler = new Handler(new Handler.Callback() {
#Override
public boolean handleMessage(Message msg) {
if (msg.what == TRIGGER_AUTO_COMPLETE) {
if (!TextUtils.isEmpty(txtJobSearch.getText())) {
getJobs(txtJobSearch.getText().toString());
}
}
return false;
}
});
}
catch (Exception ex){
AlertDialog.Builder dialog = new AlertDialog.Builder(context);
dialog.setTitle("Error");
dialog.setMessage(ex.getMessage());
dialog.show();
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_clock, container, false);
txtEmpSearch = view.findViewById(R.id.txtEmpLookup);
txtJobSearch = view.findViewById(R.id.txtJobSearch);
btnSignIn = view.findViewById(R.id.btnSignIn);
return inflater.inflate(R.layout.fragment_clock, container, false);
}
/**
* Gets the Current Pay Period and Sets up the AutoCompleteTextView
*/
private class WeekTask extends AsyncTask<PayPeriod, Void, PayPeriod>{
#Override
protected PayPeriod doInBackground(PayPeriod... payPeriods) {
return new APIHelper().getCurrentPayWeek(JSONHelper.getDateAsInt());
}
#Override
protected void onPostExecute(PayPeriod payPeriod) {
period = payPeriod;
txtPayWeek = getView().findViewById(R.id.txtPayWeekNo);
txtPayWeek.setText(getString(R.string.txtCurrentWeek, payPeriod.getPayWeekNo()));
txtEmpSearch = (AppCompatAutoCompleteTextView) getView().findViewById(R.id.txtEmpLookup);
autoAdapter = new AutoSuggestAdapter(context, R.layout.support_simple_spinner_dropdown_item);
txtEmpSearch.setThreshold(2);
txtEmpSearch.setAdapter(autoAdapter);
// Fires when an Employee is selected
txtEmpSearch.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, final View view, int position, long id) {
InputMethodManager in = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
in.hideSoftInputFromWindow(view.getApplicationWindowToken(), 0);
Employee emp = (Employee) parent.getItemAtPosition(position);
((MainActivity)getActivity()).setEmployee(emp);
}
});
txtEmpSearch.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
handler.removeMessages(TRIGGER_AUTO_COMPLETE);
handler.sendEmptyMessageDelayed(TRIGGER_AUTO_COMPLETE, AUTO_COMPLETE_DELAY);
}
#Override
public void afterTextChanged(Editable s) {
if(txtEmpSearch.getText().toString().equals("")){
}
}
});
handler = new Handler(new Handler.Callback() {
#Override
public boolean handleMessage(Message msg) {
if (msg.what == TRIGGER_AUTO_COMPLETE) {
if (!TextUtils.isEmpty(txtEmpSearch.getText())) {
makeApiCall(txtEmpSearch.getText().toString());
}
}
return false;
}
});
}
}
private void getJobs(String term){
APICall.getJobsByPartial(context, term, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
List<Function> jobs = new ArrayList<>();
try{
JSONArray array = new JSONArray(response);
jobs = new APIHelper().populateFunctionList(array);
jobAdapter.setData(jobs);
jobAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
}
}
The code above does work, the issue was with how I was testing it. I had to use the first AutoCompleteTextView, pick a suggestion, then use the second one. If I tried to use the second one first, it does not work.
Related
OH = order history
Hi, i doing an order application
i face a problem is the order history did not display the information of card view
but it can detect that this user got how many order but still did not display the information
fragment page for order list
`
package com.example.mod3;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
/**
* A simple {#link Fragment} subclass.
* Use the {#link order_list_frag#newInstance} factory method to
* create an instance of this fragment.
*/
public class order_list_frag extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
RecyclerView order_view_list;
ArrayList<Order_History_Data> OH_data_list;
DatabaseReference database;
//OH_adapter my_adapter;
private FirebaseAuth mAuth;
private static FirebaseDatabase FD = FirebaseDatabase.getInstance();
private static DatabaseReference db = FD.getReference("Users").child(FirebaseAuth.getInstance().getCurrentUser().getUid());
public static String id = db.push().getKey();
public order_list_frag() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment order_list_frag.
*/
// TODO: Rename and change types and number of parameters
public static order_list_frag newInstance(String param1, String param2) {
order_list_frag fragment = new order_list_frag();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_order_list_frag, container, false);
order_view_list = v.findViewById(R.id.RV_orderlist);
order_view_list.setLayoutManager(new LinearLayoutManager(getContext()));
OH_data_list = new ArrayList<>();
//my_adapter = new OH_adapter(getContext(),OH_data_list);
database = FirebaseDatabase.getInstance().getReference().child("Users").child(FirebaseAuth.getInstance().getCurrentUser().getUid()).child("order");
//order_view_list.setAdapter(my_adapter);
database.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for (DataSnapshot dataSnapshot : snapshot.getChildren()){
Order_History_Data user_data = dataSnapshot.getValue(Order_History_Data.class);
OH_data_list.add(user_data);
}
OH_adapter my_adapter;
my_adapter = new OH_adapter(getContext(),OH_data_list);
order_view_list.setAdapter(my_adapter);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(getContext(), "Fail to get data.", Toast.LENGTH_SHORT).show();
}
});
return v;
}
}
OH_adapter
`
package com.example.mod3;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class OH_adapter extends RecyclerView.Adapter<OH_adapter.OH_ViewHolder> {
private final Context OH_CT;
private final ArrayList<Order_History_Data> OH_data_list;
public OH_adapter(Context OH_CT, ArrayList<Order_History_Data> OH_data_list) {
this.OH_CT = OH_CT;
this.OH_data_list = OH_data_list;
}
#NonNull
#Override
public OH_ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(OH_CT).inflate(R.layout.item,parent,false);
return new OH_ViewHolder(v);
}
#Override
public void onBindViewHolder(#NonNull OH_ViewHolder holder, int position) {
Order_History_Data data = OH_data_list.get(position);
holder.date.setText(data.getOH_date());
//holder.delivery_fee.setText(data.getOH_delivery_fee());
//holder.extra_note.setText(data.getOH_extra_note());
holder.name.setText(data.getOH_name());
//holder.status.setText(data.getOH_status());
//holder.payment.setText(data.getOH_payment());
//holder.price.setText(data.getOH_price());
//holder.quantity.setText(data.getOH_quantity());
//holder.time.setText(data.getOH_time());
holder.total_price.setText(data.getOH_total());
holder.type.setText(data.getOH_type());
//holder.volume.setText(data.getOH_volume());
holder.v.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent np = new Intent(OH_CT, Order_details_page.class);
np.putExtra("date", data.getOH_date());
//np.putExtra("delivery_fee", data.getOH_delivery_fee());
//np.putExtra("extra_note", data.getOH_extra_note());
np.putExtra("name", data.getOH_name());
//np.putExtra("status", data.getOH_status());
//np.putExtra("payment", data.getOH_payment());
//np.putExtra("price", data.getOH_price());
//np.putExtra("quantity", data.getOH_quantity());
//np.putExtra("time", data.getOH_time());
np.putExtra("total_price", data.getOH_total());
np.putExtra("type", data.getOH_type());
//np.putExtra("volume", data.getOH_volume());
np.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
OH_CT.startActivity(np);
}
});
}
#Override
public int getItemCount() {
return OH_data_list.size();
}
public static class OH_ViewHolder extends RecyclerView.ViewHolder{
private TextView date,delivery_fee, extra_note,name,status,payment,price,quantity,time, total_price,type,volume;
private View v;
public OH_ViewHolder(#NonNull View itemView) {
super(itemView);
name = itemView.findViewById(R.id.order_product);
total_price = itemView.findViewById(R.id.order_price);
type = itemView.findViewById(R.id.order_type);
date= itemView.findViewById(R.id.order_date);
v = itemView;
}
}
}
Order Data
`
package com.example.mod3;
public class Order_History_Data {
String OH_date;
String OH_delivery_fee;
String OH_extra_note;
String OH_name;
String OH_status;
String OH_payment;
String OH_price;
String OH_quantity;
String OH_time;
String OH_total;
String OH_type;
String OH_volume;
public Order_History_Data() {}
public String getOH_date() {
return OH_date;
}
public String getOH_delivery_fee() {
return OH_delivery_fee;
}
public String getOH_extra_note() {
return OH_extra_note;
}
public String getOH_name() {
return OH_name;
}
public String getOH_status() {
return OH_status;
}
public String getOH_payment() {
return OH_payment;
}
public String getOH_price() {
return OH_price;
}
public String getOH_quantity() {
return OH_quantity;
}
public String getOH_time() {
return OH_time;
}
public String getOH_total() {
return OH_total;
}
public String getOH_type() {
return OH_type;
}
public String getOH_volume() {
return OH_volume;
}
public Order_History_Data(String OH_date, String OH_delivery_fee, String OH_extra_note, String OH_name, String OH_status, String OH_payment, String OH_price, String OH_quantity, String OH_time, String OH_total, String OH_type, String OH_volume) {
this.OH_date = OH_date;
this.OH_delivery_fee = OH_delivery_fee;
this.OH_extra_note = OH_extra_note;
this.OH_name = OH_name;
this.OH_status = OH_status;
this.OH_payment = OH_payment;
this.OH_price = OH_price;
this.OH_quantity = OH_quantity;
this.OH_time = OH_time;
this.OH_total = OH_total;
this.OH_type = OH_type;
this.OH_volume = OH_volume;
}
}
I hope it can display the basic data on the card view
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 :)
Whenever I've tried to save Reviews class data to my Post class, the terminal output this message and i'm not sure how to update the relational data in back4app correctly Here is the error message.
com.parse.ParseException: java.lang.IllegalStateException: unable to encode an association with an unsaved ParseObject
package com.example.rentahome.fragments;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import android.provider.ContactsContract;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RatingBar;
import android.widget.Toast;
import com.example.rentahome.Post;
import com.example.rentahome.R;
import com.example.rentahome.ReviewAdapter;
import com.example.rentahome.Reviews;
import com.parse.FindCallback;
import com.parse.ParseException;
import com.parse.ParseObject;
import com.parse.ParseQuery;
import com.parse.ParseRelation;
import com.parse.ParseUser;
import com.parse.SaveCallback;
import java.util.ArrayList;
import java.util.List;
/**
* A simple {#link Fragment} subclass.
* Use the {#link ReviewFragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class ReviewFragment extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
public Post loadpost;
public EditText description;
public RatingBar ratingBar;
public Button submit;
public void updatePost(Post post){
loadpost = post;
}
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
public ReviewFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment ReviewFragment.
*/
// TODO: Rename and change types and number of parameters
public static ReviewFragment newInstance(String param1, String param2) {
ReviewFragment fragment = new ReviewFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_review, container, false);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState){
super.onViewCreated(view, savedInstanceState);
description = view.findViewById(R.id.submitReview_description);
ratingBar = view.findViewById(R.id.submitReview_ratingbar);
submit = view.findViewById(R.id.submitReview_submitbtn);
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ParseRelation<ParseObject> relation = loadpost.getRelation("Reviews");
if(ratingBar.getNumStars() == 0){
Toast.makeText(getContext(), "Rate the house!",Toast.LENGTH_SHORT).show();
}else if(description.getText().toString().isEmpty()){
Toast.makeText(getContext(),"Describe the house!", Toast.LENGTH_SHORT).show();
}else{
ParseObject temp = ParseObject.create("Reviews");
temp.put("Description",description.getText().toString());
temp.put("author", ParseUser.getCurrentUser());
temp.put("likesCount",0);
temp.put("dislikesCount",0);
temp.put("rating", (float)ratingBar.getNumStars());
temp.saveInBackground(new SaveCallback() {
#Override
public void done(ParseException e) {
}
});
relation.add(temp);
loadpost.saveInBackground(new SaveCallback() {
#Override
public void done(ParseException e) {
if(e!=null){
Log.e("ReviewFragment","Issue with saving posts..", e);
Toast.makeText(getContext(), "Error while saving", Toast.LENGTH_SHORT).show();
return;
}
}
});
Homefragment nextFrag= new Homefragment();
getActivity().getSupportFragmentManager().beginTransaction()
.replace(R.id.flContainer, nextFrag)
.addToBackStack(null)
.commit();
}
}
});
}
}
The basic idea was to grab a loadpost from existing post data and create a Reviews object and then appending it to the loadpost and saving it.
I used this documentation to try to find out my solution
https://docs.parseplatform.org/android/guide/#relational-data
Reviews temp2 = new Reviews();
temp2.setAuthor(ParseUser.getCurrentUser());
temp2.setDescription(description.getText().toString());
temp2.setRating((float)ratingBar.getNumStars());
temp2.setdislikesCount(0);
temp2.setlikesCount(0);
temp2.saveInBackground(new SaveCallback() {
#Override
public void done(ParseException e) {
if(e!=null){
Log.e("ReviewFragment","Issue with saving posts..", e);
Toast.makeText(getContext(), "Error while saving", Toast.LENGTH_SHORT).show();
return;
}
relation.add(temp2);
loadpost.saveInBackground(new SaveCallback() {
#Override
public void done(ParseException e) {
if(e!=null){
Log.e("ReviewFragment","Issue with saving posts..", e);
Toast.makeText(getContext(), "Error while saving", Toast.LENGTH_SHORT).show();
return;
}
}
});
}
});
All I had to do was to call a object and save it inside the save in background function.
I don't know why I am getting this error.
I had implemented filterResults().
Actually, when I search first time in edit text and click on it, it works fine.
Then when I come back and search for some city again, it shows 2 same entries. I have added screenshots.
Then when I come back and search 3rd time I got 3 same entries for each city searched.
My java class:
package com.wordpress.myselfnikunj.cofighter;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import androidx.navigation.Navigation;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
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.wordpress.myselfnikunj.cofighter.Adapters.CountryListAdapter;
import com.wordpress.myselfnikunj.cofighter.Model.CountryNamesModel;
import org.json.JSONArray;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class AffectedCountriesFragment extends Fragment {
EditText searchEditText;
ListView listView;
public static List<CountryNamesModel> countryNamesModelList = new ArrayList<>();
CountryNamesModel countryNamesModel;
CountryListAdapter countryListAdapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_affected_countries, container, false);
searchEditText = (EditText) view.findViewById(R.id.searchEditText);
listView = (ListView) view.findViewById(R.id.countriesListView);
countryListAdapter = new CountryListAdapter(getContext(), countryNamesModelList);
// listView.setAdapter(countryListAdapter);
fetchData();
searchEditText.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
countryListAdapter.getFilter().filter(charSequence);
countryListAdapter.notifyDataSetChanged();
}
#Override
public void afterTextChanged(Editable editable) {
}
});
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Bundle position = new Bundle();
position.putInt("position", i);
Navigation.findNavController(view).navigate(R.id.action_affectedCountriesFragment_to_countryDetailsFragment, position);
}
});
return view;
}
private void fetchData() {
String Url = "https://corona.lmao.ninja/v2/countries/";
RequestQueue requestQueue = Volley.newRequestQueue(getContext());
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(
Url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.i("hehes","entered");
try {
Log.i("hehe", response.toString());
for (int i = 0; i < response.length(); i++) {
JSONObject jsonObject = response.getJSONObject(i);
String countryName = jsonObject.getString("country");
String cases = jsonObject.getString("cases");
String todayCases = jsonObject.getString("todayCases");
String deaths = jsonObject.getString("deaths");
String recovered = jsonObject.getString("recovered");
String todayDeaths = jsonObject.getString("todayDeaths");
String active = jsonObject.getString("active");
String critical = jsonObject.getString("critical");
JSONObject object = jsonObject.getJSONObject("countryInfo");
String flagUrl = object.getString("flag");
countryNamesModel = new CountryNamesModel(getContext(),flagUrl, countryName, cases, todayCases, deaths, todayDeaths, recovered, active, critical);
countryNamesModelList.add(countryNamesModel);
}
countryListAdapter.notifyDataSetChanged();
listView.setAdapter(countryListAdapter);
}catch (Exception e) {
Log.i("error", e.getMessage());
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.i("errors", error.getMessage());
Toast.makeText(getContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
}
}
);
requestQueue.add(jsonArrayRequest);
}
My custom Adapter
package com.wordpress.myselfnikunj.cofighter.Adapters;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Filter;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.bumptech.glide.Glide;
import com.wordpress.myselfnikunj.cofighter.AffectedCountriesFragment;
import com.wordpress.myselfnikunj.cofighter.Model.CountryNamesModel;
import com.wordpress.myselfnikunj.cofighter.R;
import com.wordpress.myselfnikunj.cofighter.UpdatesFragment;
import java.util.ArrayList;
import java.util.List;
public class CountryListAdapter extends ArrayAdapter<CountryNamesModel> {
private Context context;
private List<CountryNamesModel> countryModelList;
private List<CountryNamesModel> countryModelListFiltered;
public CountryListAdapter( Context context, List<CountryNamesModel> countryModelList) {
super(context, R.layout.countryitem, countryModelList);
this.context = context;
this.countryModelList = countryModelList;
this.countryModelListFiltered = countryModelList;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.countryitem, null, true);
TextView tvCountryName = view.findViewById(R.id.countryName);
ImageView imageView = view.findViewById(R.id.countryImageFlag);
tvCountryName.setText(countryModelListFiltered.get(position).getCountry());
Glide.with(context).load(countryModelListFiltered.get(position).getFlag()).into(imageView);
return view;
}
#Override
public int getCount() {
return countryModelListFiltered.size();
}
#Nullable
#Override
public CountryNamesModel getItem(int position) {
return countryModelListFiltered.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#NonNull
#Override
public Filter getFilter() {
Filter filter = new Filter() {
#Override
protected FilterResults performFiltering(CharSequence charSequence) {
FilterResults filterResults = new FilterResults();
if (charSequence == null
|| charSequence.length() == 0
) {
filterResults.count = countryModelList.size();
filterResults.values = countryModelList;
} else {
List<CountryNamesModel> resultsModel = new ArrayList<>();
String searchStr = charSequence.toString().toLowerCase();
for (CountryNamesModel itemsModel: countryModelList) {
if(itemsModel.getCountry().toLowerCase().contains(searchStr)) {
resultsModel.add(itemsModel);
}
filterResults.count = resultsModel.size();
filterResults.values = resultsModel;
}
}
return filterResults;
}
#Override
protected void publishResults(CharSequence charSequence, FilterResults results) {
countryModelListFiltered = (List<CountryNamesModel>) results.values;
UpdatesFragment.countryNamesModelList = (List<CountryNamesModel>) results.values;
//AffectedCountriesFragment.countryNamesModelList = (List<CountryNamesModel>) results.values;
notifyDataSetChanged();
}
};
return filter;
}
}
Screenshots
Second Time
Third Time
When you navigate to another fragment view of the AffectedCountriesFragment getting destroyed and public void onDestroyView() is called. When you return back public View onCreateView is called again. But your fragment was not totally destroyed and all of its variables still exist and are in the state they were left.
It means that when you navigate to the next fragment your countryNamesModelList stays filled and when you return back to the AffectedCountriesFragment the same filled list getting filled again resulting in duplicated entries.
What you can do?
Track the state of your fragment. Create a new class-level variable private View view; that will hold the view of your fragment.
// If null - must be initialized and returned in `onCreateView`
// If not null - must be returned in `onCreateView` immediately
// avoiding recreation of the same view (performance improvement)
private View view;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if (view == null) {
// Inflate the layout for this fragment ONLY IF IT IS NULL
View view = inflater.inflate(R.layout.fragment_affected_countries, container, false);
searchEditText = (EditText) view.findViewById(R.id.searchEditText);
listView = (ListView) view.findViewById(R.id.countriesListView);
countryListAdapter = new CountryListAdapter(getContext(), countryNamesModelList);
// listView.setAdapter(countryListAdapter);
fetchData();
searchEditText.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
countryListAdapter.getFilter().filter(charSequence);
countryListAdapter.notifyDataSetChanged();
}
#Override
public void afterTextChanged(Editable editable) {
}
});
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Bundle position = new Bundle();
position.putInt("position", I);
Navigation.findNavController(view).navigate(R.id.action_affectedCountriesFragment_to_countryDetailsFragment, position);
}
});
}
return view;
}
Make sure you are not missing something in an understanding of Activity and Fragment lifecycles. Here is a good example of their lifecycles.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I'm a newbie coding witch android studio and I try to save data on editText inside a recyclerview but data disappear or is duplicated in another editText.
Could someone help me please ?
Here is my code :
TaskActivity.java
package com.example.davidsimon.appexploit.activities;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Point;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.opengl.EGLDisplay;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.example.davidsimon.appexploit.R;
import com.example.davidsimon.appexploit.classes.ReturnResponse;
import com.example.davidsimon.appexploit.classes.Task;
import com.example.davidsimon.appexploit.classes.TaskAdapter;
import com.example.davidsimon.appexploit.classes.TaskToSend;
import com.example.davidsimon.appexploit.classes.User;
import com.example.davidsimon.appexploit.services.JsonService;
import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.appindexing.Thing;
import com.google.android.gms.common.api.GoogleApiClient;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import static android.R.attr.button;
import static android.R.attr.title;
public class TasksActivity extends AppCompatActivity {
private List<Task> taskList = new ArrayList<>();
private RecyclerView recyclerView;
public TaskAdapter mAdapter;
Button GoPhoto;
String user;
JsonService service;
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
private GoogleApiClient client;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tasks);
Button uploadButton = (Button) findViewById(R.id.butUpload);
GoPhoto = (Button) findViewById(R.id.butt_photo);
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(getString(R.string.base_url))
.addConverterFactory(GsonConverterFactory.create())
.build();
service = retrofit.create(JsonService.class);
Button takePictureButton = (Button) findViewById(R.id.butt_photo);
user = getIntent().getStringExtra("user");
//imageView = (ImageView) findViewById(R.id.imageview);
uploadButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
TaskToSend task;
List<TaskToSend> listTask = new ArrayList<>();
for (int i = 0; i < mAdapter.getItemCount(); i++) {
task = new TaskToSend(mAdapter.getItem(i).getTitle(), String.valueOf(mAdapter.getItem(i).isState()), mAdapter.getItem(i).getComment(), user);
if (task.getState() == "true") {
task.setState("Fait");
} else {
task.setState("Non fait");
}
listTask.add(task);
}
service.saveTasks(listTask).enqueue(new Callback<ReturnResponse>() {
#Override
public void onResponse(Call<ReturnResponse> call, Response<ReturnResponse> response) {
Log.wtf("Fichier", "Réponse");
}
#Override
public void onFailure(Call<ReturnResponse> call, Throwable t) {
Log.wtf("Fichier", "Pas de réponse");
}
});
Intent TakstoUpload = new Intent(TasksActivity.this, UploadActivity.class);
startActivity(TakstoUpload);
}
});
takePictureButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, 0);
}
});
service.getTasks().enqueue(new Callback<List<Task>>() {
#Override
public void onResponse(Call<List<Task>> call, Response<List<Task>> response) {
List<Task> listeTaches = response.body();
Log.wtf("Nombre de taches", "Nombre de taches : " + listeTaches.size());
Calendar c = Calendar.getInstance();
int DayOfWeek = c.get(Calendar.DAY_OF_WEEK);
for (Task t : listeTaches) {
if (t.getPeriod()== DayOfWeek || t.getPeriod()== 0) {
taskList.add(t);
}
}
displayRecyclerView();
}
#Override
public void onFailure(Call<List<Task>> call, Throwable t) {
Log.wtf("GetTasks Failure", t.toString());
}
});
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}
public void displayRecyclerView() {
recyclerView = (RecyclerView) findViewById(R.id.tasks_recycler_view);
mAdapter = new TaskAdapter(taskList);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(mAdapter);
}
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
public Action getIndexApiAction() {
Thing object = new Thing.Builder()
.setName("Tasks Page") // TODO: Define a title for the content shown.
// TODO: Make sure this auto-generated URL is correct.
.setUrl(Uri.parse("http://[ENTER-YOUR-URL-HERE]"))
.build();
return new Action.Builder(Action.TYPE_VIEW)
.setObject(object)
.setActionStatus(Action.STATUS_TYPE_COMPLETED)
.build();
}
#Override
public void onStart() {
super.onStart();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client.connect();
AppIndex.AppIndexApi.start(client, getIndexApiAction());
}
#Override
public void onStop() {
super.onStop();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
AppIndex.AppIndexApi.end(client, getIndexApiAction());
client.disconnect();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
Bitmap mImageBitmap = (Bitmap) extras.get("data");
}
}
#Override
protected void onDestroy() {
super.onDestroy();
}
}
Here my adapter TaskAdapter :
package com.example.davidsimon.appexploit.classes;
import android.content.Context;
import android.graphics.Movie;
import android.support.v7.widget.ListViewCompat;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.TextView;
import com.example.davidsimon.appexploit.R;
import com.example.davidsimon.appexploit.activities.TasksActivity;
import java.util.ArrayList;
import java.util.List;
import static android.R.attr.data;
import static android.R.attr.value;
import static com.example.davidsimon.appexploit.R.id.checkBox;
/**
* Created by David SIMON on 22/08/2016.
*/
public class TaskAdapter extends RecyclerView.Adapter<TaskAdapter.MyViewHolder> {
private List<Task> TaskList;
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView title;
public CheckBox checkBox;
public EditText finalComment;
public MyViewHolder(View view) {
super(view);
title = (TextView) view.findViewById(R.id.title);
checkBox = (CheckBox) view.findViewById(R.id.checkBox);
finalComment = (EditText) view.findViewById(R.id.FinalComment);
TextWatcher textWatcher = new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
int position = (int) finalComment.getTag();
TaskList.get(position).setComment(charSequence.toString());
}
#Override
public void afterTextChanged(Editable editable) {
}
};
finalComment.addTextChangedListener(textWatcher);
}
}
public TaskAdapter(List<Task> TaskList) {
this.TaskList = TaskList;
}
#Override
public TaskAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.recyvlerview, parent, false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
Task task = TaskList.get(position);
holder.title.setText(task.getTitle());
holder.finalComment.setTag(position);
holder.checkBox.setOnCheckedChangeListener(null);
holder.checkBox.setChecked(task.isState());
holder.checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
task.setState(b);
}
});
}
public Task getItem(int position){
return TaskList.get(position);
}
#Override
public int getItemCount() {
return TaskList.size();
}
}
And my Task.java
package com.example.davidsimon.appexploit.classes;
/**
* Created by David SIMON on 05/08/2016.
*/
public class Task {
String title;
boolean state;
String comment;
int period;
String type;
public Task(String title, boolean state, String comment, String type, int period) {
this.title = title;
this.state = state;
this.comment = comment;
this.type = type;
this.period = period;
}
#Override
public String toString() {
return "Title : "+ title +
"\nState : " + state +
"\nComment : " + comment +
"\nPeriod : " + period +
"\nType : " + type;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public void setState(boolean state) {
this.state = state;
}
public boolean isState() {
return state;
}
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public int getPeriod() { return period; }
public void setPeriod(int period) { this.period = period; }
}
I just want to save data in my EditText "finalcomment". I already search some similar problem but I think my level is too low.
Thanks in advance
A RecyclerView will reuse your views. So whenever you scroll onBindViewHolder will be called. Within that method you need to setup the view with the correct data. You need to set the EditText in your onBindViewHolder which will likely require you to save the tex that has been entered. Here's an example of how you'd do that without the save logic:
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
Task task = TaskList.get(position);
holder.title.setText(task.getTitle());
holder.finalComment.setTag(position);
// You need to save the entered text and then set it in onBindViewHolder
holder.finalComment.setText(THE TEXT FOR THE EDIT TEXT);
holder.checkBox.setOnCheckedChangeListener(null);
holder.checkBox.setChecked(task.isState());
holder.checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
task.setState(b);
}
});
}
I think you have a problem in recycling views.
Your RecyclerView reuse views that exited from the screen for other object, to save time and memory.
So what you need is to always set all desired data into onBindViewHolder method. Otherwise if a view exit from the visible screen and it is reused, it will be reused with old data.
Using EditText into RecyclerView is not a good decision, because you are mixing user inputs with presentation data.
If you want to keep this approach, you must find a way to save data associated to each RecyclerView item, to be then always able to set them to the right recycled view when it becomes again visible.
Obviously you need also to keep information of empty views.
Hope I have clarified enough
I seen a problem, if my solution doesn't work then let me know!
Inside your TaskAdapter class, onBindViewHolder() method:
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
Task task = TaskList.get(position);
holder.title.setText(task.getTitle());
//this one is wrong
//holder.finalComment.setTag(position);
//while doing this you will get the text of final comment in your
//edit text of final comment
holder.finalComment.setText(task.getComment());
holder.checkBox.setOnCheckedChangeListener(null);
holder.checkBox.setChecked(task.isState());
holder.checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
task.setState(b);
}
});
}