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.
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
The sourcecode of the project is given below
non-static method show(FragmentManager,String) cannot be referenced from a static context
my AdminHomeActivity and the AdminComplaintDetailsFragment classes are given below.
Full project source codeof error
Main project source code
AdminHomeFragment.java
package com.example.ecomplaint;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.ProgressBar;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
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;
public class AdminHomeFragment extends Fragment {
ListView listview;
public static ArrayList arrayList;
FirebaseDatabase rootNode;
DatabaseReference reference;
public static CustomRow adapter;
public static ArrayList adapterData;
FloatingActionButton mainbutton,registerbutton,logoutbutton;
Animation fabOpen,fabClose,rotateForward,rotateBackward;
boolean isOpen=false;
DatabaseReference referenceExpert;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_admin_home,container,false);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
final ProgressBar simpleProgressBar = (ProgressBar) view.findViewById(R.id.progressBar);
rootNode = FirebaseDatabase.getInstance();
reference = rootNode.getReference("Complaints");
mainbutton=(FloatingActionButton) view.findViewById(R.id.floatingActionButton);
registerbutton=(FloatingActionButton) view.findViewById(R.id.registerbutton);
logoutbutton=(FloatingActionButton) view.findViewById(R.id.logout_button);
fabOpen= AnimationUtils.loadAnimation(getContext(),R.anim.from_buttom_anim);
fabClose= AnimationUtils.loadAnimation(getContext(),R.anim.to_buttom_anim);
rotateForward= AnimationUtils.loadAnimation(getContext(),R.anim.rotate_open_anim);
rotateBackward= AnimationUtils.loadAnimation(getContext(),R.anim.rotate_close_anim);
mainbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
animatefab();
}
});
registerbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(getContext(),RegistrationActivity.class);
startActivity(i);
}
});
logoutbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
FirebaseAuth.getInstance().signOut();
startActivity(new Intent(getContext(),MainActivity.class));
}
});
listview=view.findViewById(R.id.list);
listview.setItemsCanFocus(false);
arrayList = new ArrayList<Complaint>();
adapterData = new ArrayList<Complaint>();
adapter = new CustomRow(getContext(), arrayList);
listview.setAdapter(adapter);
simpleProgressBar.setVisibility(View.VISIBLE);
//arrayList.add(new Complaint("123","this is title","akhil","19bce1564","ragging","rahul","registered"));
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if(!arrayList.isEmpty()){
arrayList.clear();
}
for(DataSnapshot dataSnapshot:snapshot.getChildren()){
Complaint complaint=dataSnapshot.getValue(Complaint.class);
// if(complaint.getComplaintFrom().getEmail().equals(FirebaseAuth.getInstance().getCurrentUser().getEmail())){
//get all users complaint
arrayList.add(complaint);
// }
adapter.notifyDataSetChanged();
listview.requestLayout();
simpleProgressBar.setVisibility(View.INVISIBLE);
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Complaint present = (Complaint) arrayList.get(position);
AdminComplaintDetailsFragment admincomplaintDetailsFragment= new AdminComplaintDetailsFragment(present);
AdminComplaintDetailsFragment.show(((FragmentActivity)getContext()).getSupportFragmentManager(), admincomplaintDetailsFragment.getTag());
//Toast.makeText(getContext(), "hii", Toast.LENGTH_SHORT).show();
}
});
}
private void animatefab(){
if (isOpen){
mainbutton.startAnimation(rotateForward);
registerbutton.startAnimation(fabClose);
logoutbutton.startAnimation(fabClose);
registerbutton.setClickable(false);
logoutbutton.setClickable(false);
isOpen=false;
}
else{
mainbutton.startAnimation(rotateBackward);
registerbutton.startAnimation(fabOpen);
logoutbutton.startAnimation(fabOpen);
registerbutton.setClickable(true);
logoutbutton.setClickable(true);
isOpen=true;
}
}
}
AdminComplaintDetailsFragment.java
package com.example.ecomplaint;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import com.google.android.material.bottomsheet.BottomSheetDialogFragment;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import java.util.HashMap;
import java.util.Locale;
/**
* A simple {#link Fragment} subclass.
* Use the {#link ComplaintDetailsFragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class AdminComplaintDetailsFragment extends BottomSheetDialogFragment {
FirebaseDatabase rootNode;
DatabaseReference reference;
String[] items = {"Under investigation","Reviewing complaint","Investigation complete","Case Closed"};
AutoCompleteTextView autoCompleteTxt;
ArrayAdapter<String> adapterItems;
// 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;
Complaint present;
public AdminComplaintDetailsFragment() {
// Required empty public constructor
}
public AdminComplaintDetailsFragment(Complaint present){
this.present=present;
}
/**
* 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 ComplaintDetailsFragment.
*/
// TODO: Rename and change types and number of parameters
public static AdminComplaintDetailsFragment newInstance(String param1, String param2) {
AdminComplaintDetailsFragment fragment = new AdminComplaintDetailsFragment();
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_complaint_details, container, false);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
if(present.getStatus().equals("registered")){
rootNode = FirebaseDatabase.getInstance();
reference = rootNode.getReference("Complaints");
present.setStatus("Seen");
HashMap hashMap=new HashMap();
hashMap.put("status","Seen");
reference.child(present.complaintID).updateChildren(hashMap);
Log.i("this",reference.child("complaintID").child(present.complaintID).child("status").toString());
}
TextView title=view.findViewById(R.id.details_title);
title.setText(present.getTitle());
TextView name=view.findViewById(R.id.details_name);
name.setText(present.getName());
TextView regno=view.findViewById(R.id.details_regno);
regno.setText(present.getRegno());
TextView incident=view.findViewById(R.id.details_info);
incident.setText(present.getIncident_info());
TextView ComplaintFrom=view.findViewById(R.id.complaintFrom);
ComplaintFrom.setText(present.getComplaintFrom().getName());
TextView status=view.findViewById(R.id.details_status);
status.setText(present.getStatus().toUpperCase(Locale.ROOT));
autoCompleteTxt = view.findViewById(R.id.auto_complete_txt);
adapterItems = new ArrayAdapter<String>(getContext(),R.layout.list_item,items);
autoCompleteTxt.setAdapter(adapterItems);
autoCompleteTxt.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String item = parent.getItemAtPosition(position).toString();
rootNode = FirebaseDatabase.getInstance();
reference = rootNode.getReference("Complaints");
present.setStatus(item);
HashMap hashMap=new HashMap();
hashMap.put("status",item);
reference.child(present.complaintID).updateChildren(hashMap);
Log.i("this",reference.child("complaintID").child(present.complaintID).child("status").toString());
status.setText(present.getStatus().toUpperCase(Locale.ROOT));
//Toast.makeText(getContext(),"Item: "+item,Toast.LENGTH_SHORT).show();
}
});
}
}
The show method on AdminComplaintDetailsFragment is not static which is what you are doing via AdminComplaintDetailsFragment.show.
Use the variable admincomplaintDetailsFragment that you've initialized.
Change
AdminComplaintDetailsFragment.show(((FragmentActivity)getContext()).getSupportFragmentManager(), admincomplaintDetailsFragment.getTag());
to
admincomplaintDetailsFragment.show(requireActivity.getSupportFragmentManager(), admincomplaintDetailsFragment.getTag());
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.
I've tried to set up a click and toch listener for my RecyclerView with tutorials. But every tutorial I've tried I finaly failed because I've set the RecyclerView up with an other tutorial and all tutorials are looking different. Please can you help me detect click for each row? For example when a user clicks my first row (which is a logout field) it should logout the user from the app. All of my logout actions are working but the click on RecyclerView don't.
My SettingsAdapter:
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
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.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import java.util.List;
/**
* Created by Johannes on 19.01.2017.
*/
public class SettingsAdapter extends RecyclerView.Adapter<SettingsAdapter.MySettingHolder> {
private List<Settings> settingList;
public class MySettingHolder extends RecyclerView.ViewHolder {
public ImageView settingImage;
public TextView settingTitle, settingSubtitle;
public MySettingHolder(View view) {
super(view);
settingImage = (ImageView) view.findViewById(R.id.settingImage);
settingTitle = (TextView) view.findViewById(R.id.settingTitle);
settingSubtitle = (TextView) view.findViewById(R.id.settingSubtitle);
}
}
public SettingsAdapter (List<Settings> settingList) {
this.settingList = settingList;
}
#Override
public MySettingHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.settings_list_row, parent, false);
return new MySettingHolder(itemView);
}
#Override
public void onBindViewHolder(MySettingHolder holder, int position) {
// Setting for one entry
Settings setting = settingList.get(position);
holder.settingImage.setImageResource(setting.getSettingImageUrl());
// If the settingSubtitle is empty it should be not visible and just the settingTitle
if (setting.getSettingSubtitle().equals("")) {
holder.settingTitle.setText(setting.getSettingTitle());
holder.settingSubtitle.setVisibility(View.GONE);
} else {
holder.settingTitle.setText(setting.getSettingTitle());
holder.settingSubtitle.setText(setting.getSettingSubtitle());
}
}
#Override
public int getItemCount() {
return settingList.size();
}
}
This is my SettingsFragment where I implement the RecyclerView
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
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.CalendarView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
import static android.content.Context.MODE_PRIVATE;
/**
* A simple {#link Fragment} subclass.
* Activities that contain this fragment must implement the
* {#link SettingsFragment.OnFragmentInteractionListener} interface
* to handle interaction events.
* Use the {#link SettingsFragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class SettingsFragment extends Fragment {
// Variables
private OnFragmentInteractionListener mListener;
// Variables for Recycler View
private List<Settings> settingList = new ArrayList<>();
private RecyclerView accountRecyclerView;
private SettingsAdapter aAdapter;
public SettingsFragment() {
// Required empty public constructor
}
//Change the title in action bar
public void onResume(){
super.onResume();
String titleString = getResources().getString(R.string.title_activity_navigation_drawer_settings);
// Set title bar
((NavigationDrawerActivity) getActivity())
.setActionBarTitle(titleString);
}
public static SettingsFragment newInstance() {
SettingsFragment fragment = new SettingsFragment();
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_settings, container, false);
accountRecyclerView = (RecyclerView) view.findViewById(R.id.account_recycler_view);
aAdapter = new SettingsAdapter(settingList);
RecyclerView.LayoutManager aLayoutManager = new LinearLayoutManager(getActivity().getApplicationContext()) {
// Disable scrolling in the RecyclerView
#Override
public boolean canScrollVertically() {
return false;
}
};
// Setup account RecyclerView
accountRecyclerView.setLayoutManager(aLayoutManager);
accountRecyclerView.setItemAnimator(new DefaultItemAnimator());
prepareAccountData();
accountRecyclerView.setAdapter(aAdapter);
return view;
}
private void prepareAccountData() {
// Create new setting
Settings setting = new Settings(R.drawable.ic_menu_logout, "Abmelden", "Deine Daten bleibe erhalten");
// Add Object to list
settingList.add(setting);
// Notify data changes
aAdapter.notifyDataSetChanged();
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
}
#Override
public void onStart() {
super.onStart();
try {
mListener = (OnFragmentInteractionListener) getActivity();
} catch (ClassCastException e) {
throw new ClassCastException(getActivity().toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}
#Override
public void onBindViewHolder(MySettingHolder holder, int position) {
// Setting for one entry
Settings setting = settingList.get(position);
holder.settingImage.setImageResource(setting.getSettingImageUrl());
// If the settingSubtitle is empty it should be not visible and just the settingTitle
if (setting.getSettingSubtitle().equals("")) {
holder.settingTitle.setText(setting.getSettingTitle());
holder.settingSubtitle.setVisibility(View.GONE);
} else {
holder.settingTitle.setText(setting.getSettingTitle());
holder.settingSubtitle.setText(setting.getSettingSubtitle());
}
holder.type = setting.getType();
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
MySettingHolder holder = (MySettingHolder )(v.getTag());
switch (holder.type) {
case 1:
// do logout
break;
case 2:
// do other stuff
break;
default:
break;
}
}
});
// set viewholder
holder.itemView.setTag(holder);
}
Also remind to update your ViewHolder like this and to add a type variable into Settings.class
public class MySettingHolder extends RecyclerView.ViewHolder {
public int type;
public ImageView settingImage;
public TextView settingTitle, settingSubtitle;
public MySettingHolder(View view) {
super(view);
settingImage = (ImageView) view.findViewById(R.id.settingImage);
settingTitle = (TextView) view.findViewById(R.id.settingTitle);
settingSubtitle = (TextView) view.findViewById(R.id.settingSubtitle);
}
}
I'm trying to create the favorites list from Json Objects which I received by URL.
When I got Json array, I defined methods OnItemLongClickListener and OnItemClickListener that get different things:
The OnItemClickListener method has to open another activity with description of product
The OnItemLongClickListener method has to add product to favorite list
The Problem that method OnItemClickListener which I defined in MainActivity is override method OnItemLongClickListener which I defined in FragmentActivty and the method OnItemLongClickListener doesn't work at all then I tried to define both methods in FragmentActivity but after that both methods don't work at all.
Is there any way to determine this problem?
Main Activity:
package com.boom.kayakapp.activities;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.StrictMode;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.JsonArrayRequest;
import com.boom.kayakapp.R;
import com.boom.kayakapp.adapters.AirlinesAdapter;
import com.boom.kayakapp.controllers.AppController;
import com.boom.kayakapp.fragment.AirlinesFragment;
import com.boom.kayakapp.fragment.FavoriteFragment;
import com.boom.kayakapp.model.Airlines;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends ActionBarActivity {
private Fragment contentFragment;
AirlinesFragment airlinesFragment;
FavoriteFragment favoriteFragment;
// JSON Node names
public static final String TAG_NAME = "name";
public static final String TAG_PHONE = "phone";
public static final String TAG_SITE = "site";
public static final String TAG_LOGO = "logoURL";
public static final String TAG_CODE = "code";
// Log tag
private static final String TAG = MainActivity.class.getSimpleName();
// Airlines json url
private static final String url = "https://www.kayak.com/h/mobileapis/directory/airlines";
public ProgressDialog pDialog;
public List<Airlines> airlinesList = new ArrayList<Airlines>();
public ListView listView;
public AirlinesAdapter adapter;
#Override
protected void onCreate (Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
listView = (ListView) findViewById(R.id.list);
adapter = new AirlinesAdapter(this, airlinesList);
listView.setAdapter(adapter);
pDialog = new ProgressDialog(this);
// Showing progress dialog before making http request
pDialog.setMessage("Loading...");
pDialog.show();
// Listview on item click listener
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String name = ((TextView) view.findViewById(R.id.name))
.getText().toString();
String phone = ((TextView) view.findViewById(R.id.phone))
.getText().toString();
String site = ((TextView) view.findViewById(R.id.site))
.getText().toString();
String logoURL = String.valueOf(((ImageView) view.findViewById(R.id.logoURL)));
// Starting single contact activity
Intent in = new Intent(getApplicationContext(),
SingleContactActivity.class);
in.putExtra(TAG_NAME, name);
in.putExtra(TAG_PHONE, phone);
in.putExtra(TAG_SITE, site);
in.putExtra(TAG_LOGO, logoURL);
startActivity(in);
}
});
// changing action bar color
getSupportActionBar().setBackgroundDrawable(
new ColorDrawable(Color.parseColor("#1b1b1b")));
// Creating volley request obj
JsonArrayRequest airlinesReq = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
hidePDialog();
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
Airlines airlines = new Airlines();
airlines.setName(obj.getString("name"));
airlines.setLogoURL(obj.getString("logoURL"));
airlines.setPhone(obj.getString("phone"));
airlines.setCode(obj.getInt("code"));
airlines.setSite(obj.getString("site"));
// adding airlines to movies array
airlinesList.add(airlines);
} catch (JSONException e) {
e.printStackTrace();
}
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(airlinesReq);
FragmentManager fragmentManager = getSupportFragmentManager();
/*
* This is called when orientation is changed.
*/
if (savedInstanceState != null) {
if (savedInstanceState.containsKey("content")) {
String content = savedInstanceState.getString("content");
if (content.equals(FavoriteFragment.ARG_ITEM_ID)) {
if (fragmentManager.findFragmentByTag(FavoriteFragment.ARG_ITEM_ID) != null) {
setFragmentTitle(R.string.favorites);
contentFragment = fragmentManager
.findFragmentByTag(FavoriteFragment.ARG_ITEM_ID);
}
}
}
if (fragmentManager.findFragmentByTag(AirlinesFragment.ARG_ITEM_ID) != null) {
airlinesFragment = (AirlinesFragment) fragmentManager
.findFragmentByTag(AirlinesFragment.ARG_ITEM_ID);
contentFragment = airlinesFragment;
}
} else {
airlinesFragment = new AirlinesFragment();
// setFragmentTitle(R.string.app_name);
switchContent(airlinesFragment, AirlinesFragment.ARG_ITEM_ID);
}
}
#Override
public void onDestroy () {
super.onDestroy();
hidePDialog();
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
protected void onSaveInstanceState(Bundle outState) {
if (contentFragment instanceof FavoriteFragment) {
outState.putString("content", FavoriteFragment.ARG_ITEM_ID);
} else {
outState.putString("content", AirlinesFragment.ARG_ITEM_ID);
}
super.onSaveInstanceState(outState);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_favorites:
setFragmentTitle(R.string.favorites);
favoriteFragment = new FavoriteFragment();
switchContent(favoriteFragment, FavoriteFragment.ARG_ITEM_ID);
return true;
}
return super.onOptionsItemSelected(item);
}
public void switchContent(Fragment fragment, String tag) {
FragmentManager fragmentManager = getSupportFragmentManager();
while (fragmentManager.popBackStackImmediate()) ;
if (fragment != null) {
FragmentTransaction transaction = fragmentManager
.beginTransaction();
transaction.replace(R.id.content_frame, fragment, tag);
//Only FavoriteFragment is added to the back stack.
if (!(fragment instanceof AirlinesFragment)) {
transaction.addToBackStack(tag);
}
transaction.commit();
contentFragment = fragment;
}
}
protected void setFragmentTitle(int resourseId) {
setTitle(resourseId);
getSupportActionBar().setTitle(resourseId);
}
/*
* We call super.onBackPressed(); when the stack entry count is > 0. if it
* is instanceof ProductListFragment or if the stack entry count is == 0, then
* we finish the activity.
* In other words, from ProductListFragment on back press it quits the app.
*/
#Override
public void onBackPressed() {
FragmentManager fm = getSupportFragmentManager();
if (fm.getBackStackEntryCount() > 0) {
super.onBackPressed();
} else if (contentFragment instanceof AirlinesFragment
|| fm.getBackStackEntryCount() == 0) {
finish();
}
}
}
FragmentActivity:
package com.boom.kayakapp.fragment;
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;
import com.boom.kayakapp.R;
import com.boom.kayakapp.adapters.AirlinesAdapter;
import com.boom.kayakapp.model.Airlines;
import com.boom.kayakapp.util.SharedPreference;
import java.util.ArrayList;
import java.util.List;
public class AirlinesFragment extends Fragment implements OnItemClickListener, OnItemLongClickListener{
public static final String ARG_ITEM_ID = "airlines_list";
Activity activity;
ListView airlinesListView;
List<Airlines> airlines;
AirlinesAdapter airlinesAdapter;
public AirlinesFragment() {
airlines = new ArrayList<>();
}
SharedPreference sharedPreference;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
activity = getActivity();
sharedPreference = new SharedPreference();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_list, container,
false);
findViewsById(view);
airlinesAdapter = new AirlinesAdapter(activity, airlines);
airlinesListView.setAdapter(airlinesAdapter);
airlinesListView.setOnItemClickListener(this);
airlinesListView.setOnItemLongClickListener(this);
return view;
}
private void findViewsById(View view) {
airlinesListView = (ListView) view.findViewById(R.id.list);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
Airlines airlines = (Airlines) parent.getItemAtPosition(position);
Toast.makeText(activity, airlines.toString(), Toast.LENGTH_LONG).show();
}
#Override
public boolean onItemLongClick(AdapterView<?> arg0, View view,
int position, long arg3) {
ImageView button = (ImageView) view.findViewById(R.id.favorite_button);
String tag = button.getTag().toString();
if (tag.equalsIgnoreCase("grey")) {
sharedPreference.addFavorite(activity, airlines.get(position));
Toast.makeText(activity,
activity.getResources().getString(R.string.add_favr),
Toast.LENGTH_SHORT).show();
button.setTag("red");
button.setImageResource(R.drawable.heart_red);
} else {
sharedPreference.removeFavorite(activity, airlines.get(position));
button.setTag("grey");
button.setImageResource(R.drawable.heart_grey);
Toast.makeText(activity,
activity.getResources().getString(R.string.remove_favr),
Toast.LENGTH_SHORT).show();
}
return true;
}
#Override
public void onResume() {
getActivity().setTitle(R.string.app_name);
super.onResume();
}
}
In my way I deleted definition both Methods from FavoriteFragment and defined it in MainActivity:
Json Array
listView = (ListView) findViewById(R.id.list);
adapterAirlines = new AirlinesAdapter(this, airlinesList);
listView.setAdapter(adapterAirlines);
pDialog = new ProgressDialog(this);
// Showing progress dialog before making http request
pDialog.setMessage("Loading...");
pDialog.show();
// Listview OnItemClickListener
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String name = ((TextView) view.findViewById(R.id.name))
.getText().toString();
String phone = ((TextView) view.findViewById(R.id.phone))
.getText().toString();
String site = ((TextView) view.findViewById(R.id.site))
.getText().toString();
String logoURL = String.valueOf(((ImageView) view.findViewById(R.id.logoURL)));
// Starting single contact activity
Intent in = new Intent(getApplicationContext(),
SingleContactActivity.class);
in.putExtra(TAG_NAME, name);
in.putExtra(TAG_PHONE, phone);
in.putExtra(TAG_SITE, site);
in.putExtra(TAG_LOGO, logoURL);
startActivity(in);
}
});
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view,
int position, long id) {
ImageView button = (ImageView) view.findViewById(R.id.favorite_button);
String tag = button.getTag().toString();
if (tag.equalsIgnoreCase("grey")) {
sharedPreference.addFavorite(MainActivity.this, airlinesList.get(position));
Toast.makeText(MainActivity.this,
MainActivity.this.getResources().getString(R.string.add_favr),
Toast.LENGTH_SHORT).show();
button.setTag("red");
button.setImageResource(R.drawable.heart_red);
} else {
sharedPreference.removeFavorite(MainActivity.this, airlinesList.get(position));
button.setTag("grey");
button.setImageResource(R.drawable.heart_grey);
Toast.makeText(MainActivity.this,
MainActivity.this.getResources().getString(R.string.remove_favr),
Toast.LENGTH_SHORT).show();
}
return true;
}
});
now it works