so i am trying to make an note keeping app and i have basicly 1 activity with 1 main fragment that opens a second fragment so the user can enter data, the problem is when i send the bundle from the second fragment to the first one, because if i put bundle get arguments in the first one it crashes and i understand why but im not sure how to make it so that it doesnt
Fragment 1
package app.web.fragments.secure_note;
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.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.firebase.analytics.FirebaseAnalytics;
import java.util.List;
import app.web.markodunovic.passwordmanager.R;
import app.web.markodunovic.passwordmanager.adapter.NoteAdapter;
import app.web.markodunovic.passwordmanager.room_note.Note;
import app.web.markodunovic.passwordmanager.view_model.NoteViewModel;
public class Secure_Notes_Fragment extends Fragment {
public static final String TAG = "BACK";
private FirebaseAnalytics mFirebaseAnalytics = FirebaseAnalytics.getInstance(getActivity());
private FloatingActionButton floatingActionButton;
private NoteViewModel noteViewModel;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
if (container == null) {
return null;
}
View view = inflater.inflate(R.layout.fragment_secure_notes, container, false);
RecyclerView recyclerView = view.findViewById(R.id.recycler_view);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
recyclerView.setHasFixedSize(true);
NoteAdapter noteAdapter = new NoteAdapter();
recyclerView.setAdapter(noteAdapter);
noteViewModel = new ViewModelProvider(getActivity()).get(NoteViewModel.class);
noteViewModel.getAllNotes().observe(getActivity(), new Observer<List<Note>>() {
#Override
public void onChanged(List<Note> notes) {
//update recycler view
//Toast.makeText(getActivity(), "On Changed", Toast.LENGTH_SHORT).show();
// it works yey
noteAdapter.setNotes(notes);
}
});
floatingActionButton = view.findViewById(R.id.button_add_note);
floatingActionButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
fire(mFirebaseAnalytics);
//Toast.makeText(getContext(), "I Dun Been Clicked", Toast.LENGTH_SHORT).show();
//getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new PassWord_Fragment()).commit();
newFragment();
}
});
passedData();
return view;
}
private void passedData() {
Bundle bundle = this.getArguments();
if (!bundle.isEmpty()){
String title = bundle.getString("title");
String description = bundle.getString("description");
int value = bundle.getInt("number");
Toast.makeText(getContext(), ""+title+description+value, Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(getContext(), "Bundle Empty", Toast.LENGTH_SHORT).show();
}
}
private void newFragment() {
//sends data need to use bundle instead of intent in fragments
Bundle bundle = new Bundle();
bundle.putString("test","the test works");
NoteAddEditFragment noteAddEditFragment = new NoteAddEditFragment();
noteAddEditFragment.setArguments(bundle);
FragmentTransaction fragmentTransaction = getActivity().getSupportFragmentManager()
.beginTransaction().replace(R.id.fragment_container,noteAddEditFragment).addToBackStack(TAG);
noteAddEditFragment.setArguments(bundle);
fragmentTransaction.commit();
}
private void fire(FirebaseAnalytics mFirebaseAnalytics) {
Bundle firebaseAnalytics = new Bundle();
firebaseAnalytics.putString(FirebaseAnalytics.Param.SCREEN_NAME, "clicked fab button switched to NoteAddEditFragment");
firebaseAnalytics.putString(FirebaseAnalytics.Param.SCREEN_CLASS, "NoteAddEditFragment");
mFirebaseAnalytics.logEvent(FirebaseAnalytics.Event.SCREEN_VIEW, firebaseAnalytics);
}
}
Fragment 2
package app.web.fragments.secure_note;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.NumberPicker;
import android.widget.Toast;
import android.widget.Toolbar;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;
import java.util.Objects;
import app.web.markodunovic.passwordmanager.R;
public class NoteAddEditFragment extends Fragment {
private EditText editTextTitle, editTextDescription;
private NumberPicker numberPicker;
private Button buttonBack, buttonSave;
public static final String TITLE = "title";
public static final String DESCRIPTION = "description";
public static final String NUMBERPICKER = "number";
#Nullable
#Override
public View onCreateView(LayoutInflater inflater,ViewGroup container,Bundle savedInstanceState) {
if (container==null){
return null;
}
View view = inflater.inflate(R.layout.fragment_secure_notes_edit_update,container,false);
setButtons(view);
checkPassedVallue();
return view;
}
private void setButtons(View view) {
editTextTitle = view.findViewById(R.id.edit_text_title);
editTextDescription = view.findViewById(R.id.edit_text_description);
numberPicker = view.findViewById(R.id.number_picker_priority);
numberPicker.setMinValue(1);
numberPicker.setMaxValue(100);
buttonBack = view.findViewById(R.id.notes_back_button);
buttonBack.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getContext(), "Note not saved", Toast.LENGTH_SHORT).show();
FragmentTransaction fragmentTransaction = getActivity().getSupportFragmentManager()
.beginTransaction().replace(R.id.fragment_container,new Secure_Notes_Fragment());
fragmentTransaction.commit();
}
});
buttonSave = view.findViewById(R.id.notes_save_button);
buttonSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String title = editTextTitle.getText().toString().trim();
String description = editTextDescription.getText().toString().trim();
int numberP = numberPicker.getValue();
if (!title.isEmpty() && !description.isEmpty() && numberP > 0){
//Toast.makeText(getContext(), "ok", Toast.LENGTH_SHORT).show();
Bundle bundle = new Bundle();
bundle.putString(TITLE,title);
bundle.putString(DESCRIPTION,description);
bundle.putInt(NUMBERPICKER,numberP);
Secure_Notes_Fragment secure_notes_fragment = new Secure_Notes_Fragment();
FragmentTransaction fragmentTransaction = getActivity().getSupportFragmentManager()
.beginTransaction().replace(R.id.fragment_container,secure_notes_fragment);
secure_notes_fragment.setArguments(bundle);
fragmentTransaction.commit();
}else{
Toast.makeText(getContext(), "Cant Be Empty", Toast.LENGTH_SHORT).show();
}
}
});
}
private void checkPassedVallue() {
Bundle bundle = this.getArguments();
String passedVallue = bundle.getString("test");
Toast.makeText(getContext(), "this is the passed vallue: " + passedVallue, Toast.LENGTH_SHORT).show();
}
}
Related
I have a navigation drawer activity that shows a list of restaurants based on some data passed from the previous activity as the home fragment. On clicking on one of the restaurant cards, another fragment is created which shows the details of the restaurant. All of these fragments have the navigation drawer activity as their parent activity. When I am selecting the home fragment menu on the navigation item, the fragment does not replace the previous fragment rather it superimposes itself on the previous fragment. I will add some images to explain the scenario.
This is my Navigation Drawer -
This is the home fragment containing the restaurant lists -
This is the fragment showing the restaurant details when clicking on one restaurant -
When I press the home item on the navigation drawer from the restaurant detail screen this happens -
Here is the relevant code-
MainActivity2.class
package com.example.wfdmockapp;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.view.Menu;
import com.example.wfdmockapp.ui.home.HomeFragment;
import com.google.android.material.snackbar.Snackbar;
import com.google.android.material.navigation.NavigationView;
import androidx.annotation.NonNull;
import androidx.core.view.GravityCompat;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.appcompat.app.AppCompatActivity;
import com.example.wfdmockapp.databinding.ActivityMain2Binding;
public class MainActivity2 extends AppCompatActivity{
private static final String TAG = "MainActivity2";
private String cityId = null;
private String townId = null;
private DrawerLayout drawer;
private AppBarConfiguration mAppBarConfiguration;
private ActivityMain2Binding binding;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityMain2Binding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
setSupportActionBar(binding.appBarMain.toolbar);
binding.appBarMain.fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
drawer = binding.drawerLayout;
NavigationView navigationView = binding.navView;
// Passing each menu ID as a set of Ids because each
// menu should be considered as top level destinations.
mAppBarConfiguration = new AppBarConfiguration.Builder(
R.id.nav_home)
.setOpenableLayout(drawer)
.build();
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_content_main);
NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration);
NavigationUI.setupWithNavController(navigationView, navController);
Intent getRestaurantIntent = getIntent();
cityId = getRestaurantIntent.getStringExtra("cityId");
townId = getRestaurantIntent.getStringExtra("townId");
Bundle bundle = new Bundle();
bundle.putString("cityId",cityId);
bundle.putString("townId",townId);
System.out.println(cityId+" "+townId);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.setReorderingAllowed(true)
.replace(R.id.nav_host_fragment_content_main, HomeFragment.class, bundle)
.commit();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main_activity2, menu);
return true;
}
#Override
public boolean onSupportNavigateUp() {
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_content_main);
return NavigationUI.navigateUp(navController, mAppBarConfiguration)
|| super.onSupportNavigateUp();
}
}```
HomeFragment.Java
public class HomeFragment extends Fragment {
private static final String TAG = "HomeFragment";
private RequestQueue mRequestQueue;
private String cityId = null;
private String townId = null;
private String ShopListUrl= Global.base_url+"v1/get-shop-list";
private ArrayList<Shop> shops = new ArrayList<>();
private RecyclerView recyclerView;
private ShopRecyclerViewAdapter adapter;
private GifImageView loadingAnimation;
#Override
public View onCreateView(#NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
Bundle bundle = this.getArguments();
if(bundle!=null){
cityId = bundle.getString("cityId");
townId = bundle.getString("townId");
System.out.println(cityId+" "+townId);
}
return inflater.inflate(R.layout.fragment_home, container, false);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mRequestQueue = Volley.newRequestQueue(getContext());
loadingAnimation = view.findViewById(R.id.loading_animation);
initRecyclerView(view);
getShopList();
}
public void getShopList(){
Log.d(TAG,"Creating Shop Object");
JSONObject shopInfoObject = new JSONObject();
try {
shopInfoObject.put("city",cityId);
shopInfoObject.put("town",townId);
shopInfoObject.put("shop_type",null);
shopInfoObject.put("api_token","a4e426652ed46154d67c8af897e77022");
} catch (JSONException e) {
e.printStackTrace();
}
Log.d(TAG,"JSON Shop Object created,collecting response for Request");
JsonObjectRequest ShopListRequest = new JsonObjectRequest(Request.Method.POST, ShopListUrl, shopInfoObject, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
Log.d(TAG,"Getting response");
JSONArray shopList = response.getJSONArray("shopList");
for(int i=0;i<shopList.length();i++){
JSONObject jsonObject = shopList.getJSONObject(i);
Shop shop = new Shop();
shop.setShopId(jsonObject.getString("shopId"));
shop.setName(jsonObject.getString("title"));
shop.setTypeName(jsonObject.getString("typeName"));
shop.setLogo(Global.base_imageUrl+jsonObject.getString("logo"));
shop.setSpecialOffer(jsonObject.getString("special_offer_text"));
shop.setDeliveredBy(jsonObject.getInt("deliveredBy"));
shop.setMixMatch(jsonObject.getInt("mixAndMatch"));
shop.setDeliveryFee(jsonObject.getString("delivery_fee"));
shop.setMinimumOrder(jsonObject.getString("minOrder"));
shop.setPaymentModeText(jsonObject.getString("paymentModeText"));
shop.setShopStatus(jsonObject.getString("currentStatus"));
shops.add(shop);
}
adapter.notifyDataSetChanged();
Log.d(TAG,"Shop data fetched");
loadingAnimation.setVisibility(View.GONE);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
if (error instanceof TimeoutError) {
Global.displayToast("Timeout! Please Try Again",getContext());
}
}
});
ShopListRequest.setRetryPolicy(new DefaultRetryPolicy(
6000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
mRequestQueue.add(ShopListRequest);
}
public void initRecyclerView(View view){
recyclerView = view.findViewById(R.id.recycler_view);
adapter = new ShopRecyclerViewAdapter(shops,getContext(),this);
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
}
}```
RestaurantDetailsFragment.Java
package com.example.wfdmockapp;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.TimeoutError;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.bumptech.glide.Glide;
import com.example.wfdmockapp.models.Restaurant;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import de.hdodenhof.circleimageview.CircleImageView;
import pl.droidsonroids.gif.GifImageView;
public class RestaurantDetailsFragment extends Fragment {
private static final String TAG = "RestaurantDetails";
private RequestQueue mRequestQueue;
private Restaurant restaurant = new Restaurant();
private String getShopDetailsUrl = Global.base_url+"v1/get-shop-details";
private String shopId;
private ArrayList<String> FoodTypeList;
//UI Components
private TextView name;
private TextView typeName;
private TextView shopMessage;
private TextView minOrder;
private TextView paymentModeText;
private RecyclerView foodTypeListRecyclerView;
private FoodTypeRecyclerViewAdapter adapter;
private TextView deliveryText;
private TextView deliveryFee;
private TextView deliveryTime;
private TextView shopStatus;
private CircleImageView shopLogo;
private LinearLayout shopDetailsView;
private GifImageView loadingAnimation;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
shopId = getArguments().getString("shopId");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_restaurant_details, container, false);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
loadingAnimation = view.findViewById(R.id.shop_details_loading_animation);
shopDetailsView = view.findViewById(R.id.shop_view);
shopDetailsView.setVisibility(View.GONE);
FoodTypeList = restaurant.getFoodTypeList();
mRequestQueue = Volley.newRequestQueue(getContext());
initRecyclerView(view);
initUIComponents(view);
showRestaurantDetails(view);
}
public void showRestaurantDetails(View view){
JSONObject ShopInfoObject = new JSONObject();
try {
ShopInfoObject.put("api_token","cadbc10d3aa13257cd7c69bb3d434d00");
ShopInfoObject.put("shopId",shopId);
} catch (JSONException e) {
e.printStackTrace();
}
JsonObjectRequest getShopDetailsRequest = new JsonObjectRequest(Request.Method.POST, getShopDetailsUrl, ShopInfoObject, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray shopDetails = response.getJSONArray("shop");
String deliveryTextResponse = response.getString("deliveryText");
restaurant.setDeliveryText(deliveryTextResponse);
for(int i=0;i<shopDetails.length();i++){
JSONObject shopJsonObject = shopDetails.getJSONObject(i);
restaurant.setName(shopJsonObject.getString("title"));
restaurant.setTypeName(shopJsonObject.getString("typeName"));
restaurant.setShop_message(shopJsonObject.getString("shop_message"));
String ImageUrl = Global.base_imageUrl+shopJsonObject.getString("logo");
restaurant.setLogo(ImageUrl);
restaurant.setMinOrder(shopJsonObject.getString("minOrder"));
restaurant.setStatus(shopJsonObject.getString("currentStatus"));
JSONArray foodTypeListJSONArray = shopJsonObject.getJSONArray("foodTypeList");
for(int j=0;j<foodTypeListJSONArray.length();j++){
JSONObject foodTypeListJSONObject = foodTypeListJSONArray.getJSONObject(j);
Log.d(TAG,foodTypeListJSONObject.getString("foodTypeName"));
restaurant.addFoodListItems(foodTypeListJSONObject.getString("foodTypeName"));
}
adapter.notifyDataSetChanged();
restaurant.setDelivery_fee(shopJsonObject.getString("delivery_fee"));
JSONObject deliveryHours = shopJsonObject.getJSONObject("deliveryHours");
String openingHours = deliveryHours.getString("openingHour");
String closingHours = deliveryHours.getString("closingHour");
restaurant.setDeliveryTime("Delivery: "+openingHours+" - "+closingHours);
restaurant.setPaymentModeText(shopJsonObject.getString("paymentModeText"));
setUIComponentValues(restaurant,view);
loadingAnimation.setVisibility(View.GONE);
shopDetailsView.setVisibility(View.VISIBLE);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
if (error instanceof TimeoutError) {
Global.displayToast("Timeout error!Please try again",getContext());
}
}
});
getShopDetailsRequest.setRetryPolicy(new DefaultRetryPolicy(
5000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
mRequestQueue.add(getShopDetailsRequest);
}
public void initUIComponents(View view){
name = view.findViewById(R.id.shopName);
typeName = view.findViewById(R.id.shopTypename);
shopMessage = view.findViewById(R.id.shop_message);
minOrder = view.findViewById(R.id.min_order);
paymentModeText = view.findViewById(R.id.payment_Method);
deliveryFee = view.findViewById(R.id.min_delivery_fee);
deliveryText = view.findViewById(R.id.delivery_time_today);
deliveryTime = view.findViewById(R.id.shop_delivery_time);
shopLogo = view.findViewById(R.id.shopLogo);
shopStatus = view.findViewById(R.id.status);
}
public void setUIComponentValues(Restaurant restaurant,View view){
Glide.with(getContext()).load(restaurant.getLogo()).into(shopLogo);
name.setText(restaurant.getName());
typeName.setText(restaurant.getTypeName());
String message = restaurant.getShop_message();
System.out.println(message);
if(message.equals("")||message.equals("null")){
Log.d(TAG,"No shop message,hiding field");
LinearLayout shopMsgField = view.findViewById(R.id.shop_message_field);
shopMsgField.setVisibility(View.GONE);
}else{
shopMessage.setText(message);
}
minOrder.setText("\u20ac "+restaurant.getMinOrder()+" MIN ");
paymentModeText.setText(restaurant.getPaymentModeText());
deliveryFee.setText("Delivery \u20ac "+restaurant.getDelivery_fee());
String text = restaurant.getDeliveryText();
if(text.equals("null")||text.equals("")){
deliveryText.setVisibility(View.GONE);
}else{
deliveryText.setText(text);
}
deliveryTime.setText(restaurant.getDeliveryTime());
Global.setCurrentStatusText(restaurant.getStatus(),shopStatus);
}
public void initRecyclerView(View view){
foodTypeListRecyclerView = view.findViewById(R.id.FoodTypeRecyclerView);
adapter = new FoodTypeRecyclerViewAdapter(FoodTypeList,getContext());
foodTypeListRecyclerView.setAdapter(adapter);
foodTypeListRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
}
}```
ShopRecyclerViewAdapter.java
package com.example.wfdmockapp;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
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 androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import com.example.wfdmockapp.models.Shop;
import java.io.FileNotFoundException;
import java.util.ArrayList;
public class ShopRecyclerViewAdapter extends RecyclerView.Adapter<ShopRecyclerViewAdapter.ViewHolder> {
private static final String TAG="ShopRecyclerViewAdapter";
private ArrayList<Shop> shops;
private Context mContext;
private Fragment fragment;
public ShopRecyclerViewAdapter(ArrayList<Shop> shops,Context mContext,Fragment fragment) {
this.shops = shops;
this.mContext = mContext;
this.fragment = fragment;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
Log.d(TAG,"Reached onCreate");
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.shoplistitem,parent,false);
ViewHolder holder = new ViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
Log.d(TAG,"Reached onBind");
try{
Glide.with(mContext).load(shops.get(position).getLogo()).into(holder.shopLogo);
}catch (Exception e){
Glide.with(mContext).load(R.drawable.shop_logo_base).into(holder.shopLogo);
}
holder.deliveryFee.setText("Delivery \u20ac "+shops.get(position).getDeliveryFee());
holder.minOrder.setText("\u20ac "+shops.get(position).getMinimumOrder()+" MIN ");
holder.paymentMethod.setText(shops.get(position).getPaymentModeText());
String status = shops.get(position).getShopStatus();
Global.setCurrentStatusText(status,holder.shopStatus);
holder.shopName.setText(shops.get(position).getName());
holder.shopTypeName.setText(shops.get(position).getTypeName());
String offerText = shops.get(position).getSpecialOffer();
if(!(offerText==null)){
holder.shopOffer.setText(offerText);
}else{
holder.offerSection.setVisibility(View.GONE);
}
int deliveredBy = shops.get(position).getDeliveredBy();
makeViewInvisible(holder.delivery_layout,deliveredBy);
int mixAndMatch = shops.get(position).getMixMatch();
makeViewInvisible(holder.mixMatchLayout,mixAndMatch);
holder.parent_layout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Bundle bundle = new Bundle();
bundle.putString("shopId",shops.get(position).getShopId());
FragmentManager fm = fragment.getActivity().getSupportFragmentManager();
FragmentTransaction fragmentTrans = fm.beginTransaction();
fragmentTrans.replace(R.id.nav_host_fragment_content_main,RestaurantDetailsFragment.class,bundle);
fragmentTrans.setReorderingAllowed(true);
fragmentTrans.addToBackStack(null);
fragmentTrans.commit();
}
});
}
#Override
public int getItemCount() {
return shops.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
ImageView shopLogo;
TextView shopName;
TextView shopTypeName;
TextView shopOffer;
TextView minOrder;
TextView deliveryFee;
TextView paymentMethod;
TextView shopStatus;
RelativeLayout offerSection;
RelativeLayout parent_layout;
RelativeLayout delivery_layout;
RelativeLayout mixMatchLayout;
public ViewHolder(#NonNull View itemView) {
super(itemView);
shopLogo = itemView.findViewById(R.id.shop_logo);
shopName = itemView.findViewById(R.id.shop_title);
shopTypeName = itemView.findViewById(R.id.shop_typename);
shopOffer = itemView.findViewById(R.id.offer_text);
offerSection = itemView.findViewById(R.id.offer_section);
minOrder = itemView.findViewById(R.id.shop_min_order);
deliveryFee = itemView.findViewById(R.id.deliver_fee);
shopStatus = itemView.findViewById(R.id.status);
paymentMethod = itemView.findViewById(R.id.shop_payment);
parent_layout = itemView.findViewById(R.id.parent_layout);
delivery_layout = itemView.findViewById(R.id.delivered_by);
mixMatchLayout = itemView.findViewById(R.id.mix_and_match);
}
}
public void makeViewInvisible(View view,int flag){
if(flag==1){
view.setVisibility(View.GONE);
}
}
}```
You need to pop the fragment onBackPressed and function needs to execute from MainActivity thus.
MainActivity
public void popFragment() {
if (getSupportFragmentManager() == null)
return;
getSupportFragmentManager().popBackStack();
}
#Override
public void onBackPressed() {
if (getSupportFragmentManager().getBackStackEntryCount() > 1) {
popFragment();
}
}
Turns out, the problem was in the ShopRecyclerViewAdapter.java file.
In the line
FragmentManager fm = fragment.getActivity().getSupportFragmentManager
fragment.getActivity made the context null. Grabbing context from view instead solved the problem.
I replaced the above line with the following:
FragmentManager fm = ((FragmentActivity) view.getContext()).getSupportFragmentManager()
Here is the reference to the solution:
Replace fragment from recycler adapter
I am using recyclerview in fragment dynamically, now i want to open new activity on click of items with the same object / item.
AllCoursesFeagment.java
package com.example.learningapp.ui.NavigationDrawer.AllCourses;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.example.learningapp.Adapters.AllCoursesMyAdapter;
import com.example.learningapp.Interface.APIinterface;
import com.example.learningapp.Models.CourseListModel;
import com.example.learningapp.R;
import com.example.learningapp.Responses.CourseListResponse;
import com.example.learningapp.RetrofitAPIs.RetrofitAPI;
import com.example.learningapp.utility.ConstantData;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class AllCoursesFragment extends Fragment {
private RecyclerView recyclerView;
private List<CourseListModel> courseListModelList;
public AllCoursesFragment() {
// Required empty public constructor
}
// TODO: Rename and change types and number of parameters
public static AllCoursesFragment newInstance() {
return new AllCoursesFragment();
}
#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 view = inflater.inflate(R.layout.fragment_all_courses,null);
recyclerView = view.findViewById(R.id.allCourseList_RV);
APIinterface apIinterface = RetrofitAPI.getClient().create(APIinterface.class);
Call<CourseListResponse> call = apIinterface.getAllCourses(ConstantData.AppKey);
call.enqueue(new Callback<CourseListResponse>() {
#Override
public void onResponse(Call<CourseListResponse> call, Response<CourseListResponse> response){
if (response.isSuccessful()){
courseListModelList = response.body().getCourseList();
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
recyclerView.setAdapter(new AllCoursesMyAdapter(getActivity(),courseListModelList));
}
}
#Override
public void onFailure(Call<CourseListResponse> call, Throwable t) {
Toast.makeText(getActivity(),"Something went wrong",Toast.LENGTH_LONG).show();
}
});
return view;
}
}
AllCoursesMyAdapter.java
This is my adapter class.
package com.example.learningapp.Adapters;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.example.learningapp.Activities.CheckoutActivity;
import com.example.learningapp.Models.CourseListModel;
import com.example.learningapp.R;
import java.util.List;
public class AllCoursesMyAdapter extends RecyclerView.Adapter<AllCoursesMyAdapter.RecyclerVH> {
Context context;
List<CourseListModel> courseListModelList;
public AllCoursesMyAdapter(Context context, List<CourseListModel> courseListModelList) {
this.context = context;
this.courseListModelList = courseListModelList;
}
#NonNull
#Override
public RecyclerVH onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.single_row_design_allcourses,parent,false);
return new RecyclerVH(view);
}
#Override
public void onBindViewHolder(#NonNull RecyclerVH holder, int position) {
final CourseListModel courseListModel = courseListModelList.get(position);
holder.courseTitle.setText(courseListModel.getCourseName());
holder.courseDesc.setText(courseListModel.getCourseDescription());
holder.buyBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
moveToNewActivity();
//Toast.makeText(context,"Item Clicked"+position,Toast.LENGTH_SHORT).show();
Intent intent = new Intent(context, CheckoutActivity.class);
intent.putExtra("coursetitle",courseListModel.getCourseName());
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
});
}
private void moveToNewActivity () {
Activity activity = new Activity();
Intent i = new Intent(activity, CheckoutActivity.class);
context.startActivity(i);
((Activity) context).overridePendingTransition(0, 0);
}
#Override
public int getItemCount() {
return courseListModelList.size();
}
public class RecyclerVH extends RecyclerView.ViewHolder {
TextView courseTitle,courseDesc;
Button buyBtn;
public RecyclerVH(#NonNull View itemView) {
super(itemView);
courseTitle = itemView.findViewById(R.id.course_title);
courseDesc = itemView.findViewById(R.id.course_desc);
buyBtn = itemView.findViewById(R.id.btn_buycourse);
}
}
}
I'm gettng crashed when i clicked item
holder.buyBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
moveToNewActivity();
//Toast.makeText(context,"Item Clicked"+position,Toast.LENGTH_SHORT).show();
Intent intent = new Intent(context, CheckoutActivity.class);
intent.putExtra("coursetitle",courseListModel.getCourseName());
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
});
Here i am using a stored list of objects and now i want to move to the new activity when i clicked on an item with given position, but i am not able to do that.
private void moveToNewActivity () {
Activity activity = new Activity(); //this is wrong, delete this
...
}
you can't and shouldn't create an instance of an activity like this, it's something the OS has to schedule and handle for you.
you already seem to have context defined somewhere, so that means:
private void moveToNewActivity () {
Intent i = new Intent(context, CheckoutActivity.class);
context.startActivity(i);
...
}
so that means:
#Override
public void onClick(View v) {
moveToNewActivity();
}
I try to passing data from cardview when clicked to DetailFragment, in this case I try to use interface in my adapter, but I get an error a null object reference in mOnItemClickListener.onClick(i).
I try to passing data from cardview when clicked to DetailFragment, in this case I try to use interface in my adapter.
I want to passing data to DetailMoviesFragment Class.
this is my CardviewMovieAdapter Class
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import java.util.ArrayList;
public class CardviewMovieAdapter extends RecyclerView.Adapter<CardviewMovieAdapter.CardViewViewHolder> {
private ArrayList<Movie> listMovie;
Context context;
OnItemClickListener mOnItemClickListener;
public void setListMovie(ArrayList<Movie> listMovie) {
this.listMovie = listMovie;
}
public ArrayList<Movie> getListMovie() {
return listMovie;
}
public interface OnItemClickListener {
void onClick(int position);
}
public void setOnItemClickListener(final OnItemClickListener mItemClickListener) {
this.mOnItemClickListener = mItemClickListener;
}
public CardviewMovieAdapter(ArrayList<Movie> listMovie, Context context) {
this.listMovie = listMovie;
this.context = context;
}
#NonNull
#Override
public CardviewMovieAdapter.CardViewViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.list_movie, viewGroup,false);
return new CardViewViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull final CardviewMovieAdapter.CardViewViewHolder cardViewViewHolder, final int i) {
final Movie movie = listMovie.get(i);
Glide.with(cardViewViewHolder.itemView.getContext())
.load(movie.getImageMovie())
.apply(new RequestOptions().override(350, 550))
.into(cardViewViewHolder.imgPhoto);
cardViewViewHolder.tvTitle.setText(movie.getTitleMovie());
cardViewViewHolder.tvDesc.setText(movie.getDescription());
cardViewViewHolder.btnDetail.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(cardViewViewHolder.itemView.getContext(), "Detail "+
listMovie.get(cardViewViewHolder.getAdapterPosition()).getTitleMovie(), Toast.LENGTH_SHORT).show();
}
});
cardViewViewHolder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(cardViewViewHolder.itemView.getContext(), "Kamu Memilih "+movie.getTitleMovie(), Toast.LENGTH_SHORT).show();
mOnItemClickListener.onClick(i);
}
});
// cardViewViewHolder.itemView.setOnClickListener(new View.OnClickListener() {
// #Override
// public void onClick(View v) {
// Toast.makeText(cardViewViewHolder.itemView.getContext(), "Kamu Memilih "+movie.getTitleMovie(), Toast.LENGTH_SHORT).show();
// }
// });
}
#Override
public int getItemCount() {
return listMovie.size();
}
public class CardViewViewHolder extends RecyclerView.ViewHolder {
ImageView imgPhoto;
TextView tvTitle, tvDesc;
Button btnDetail;
public CardViewViewHolder(#NonNull View itemView) {
super(itemView);
imgPhoto = itemView.findViewById(R.id.img_item_photo);
tvTitle = itemView.findViewById(R.id.tv_title);
tvDesc = itemView.findViewById(R.id.tv_desc);
btnDetail = itemView.findViewById(R.id.btn_detail);
}
}
}
This is my MoviesFragment Class
import android.content.Intent;
import android.content.res.TypedArray;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.widget.CardView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ListView;
import java.util.ArrayList;
/**
* A simple {#link Fragment} subclass.
*/
public class MoviesFragment extends Fragment implements View.OnClickListener{
private RecyclerView rvMovie;
private String[] dataMovieTitle;
private String[] dataDescription;
private TypedArray dataPhoto;
private ArrayList<Movie> movies;
Button btnDetail;
private CardviewMovieAdapter adapter;
View view;
final static String KEY = "KEY";
public MoviesFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
view = inflater.inflate(R.layout.fragment_movies, container, false);
//adapter = new CardviewMovieAdapter(movies,getContext());
rvMovie = view.findViewById(R.id.rv_movies);
prepare();
addItem();
showRecyclerCardView();
adapter = new CardviewMovieAdapter(movies, getContext());
adapter.setOnItemClickListener(new CardviewMovieAdapter.OnItemClickListener() {
#Override
public void onClick(int position) {
final Movie movie = movies.get(position);
DetailMoviesFragment detailMoviesFragment = new DetailMoviesFragment();
// Bundle mBundle = new Bundle();
// mBundle.putString(detailMoviesFragment.EXTRA_TITLE, movie.getTitleMovie());
// mBundle.putString(detailMoviesFragment.EXTRA_DESCRIPTION, movie.getDescription());
// mBundle.putInt(detailMoviesFragment.EXTRA_PHOTO, movie.getImageMovie());
// detailMoviesFragment.setArguments(mBundle);
MoviesFragment.newInstance(movie.getTitleMovie(), movie.getDescription(), movie.getImageMovie());
FragmentManager mFragmentManager = getFragmentManager();
if (mFragmentManager!= null) {
FragmentTransaction mFragmentTransaction = mFragmentManager.beginTransaction();
mFragmentTransaction.replace(R.id.containterFragment, detailMoviesFragment, DetailMoviesFragment.class.getSimpleName());
mFragmentTransaction.addToBackStack(null);
mFragmentTransaction.commit();
}
}
});
return view;
}
public static MoviesFragment newInstance(String title, String desc, int image) {
MoviesFragment moviesFragment = new MoviesFragment();
Bundle args = new Bundle();
args.putInt("image", image);
args.putString("title", title);
args.putString("desc", desc);
moviesFragment.setArguments(args);
return moviesFragment;
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
private void showRecyclerCardView(){
rvMovie.setLayoutManager(new LinearLayoutManager(getActivity()));
CardviewMovieAdapter adapter = new CardviewMovieAdapter(movies,getActivity());
rvMovie.setAdapter(adapter);
}
private void prepare() {
dataMovieTitle = getResources().getStringArray(R.array.data_movie_name);
dataDescription = getResources().getStringArray(R.array.data_desc_movie);
dataPhoto = getResources().obtainTypedArray(R.array.data_photo_movie);
}
private void addItem(){
movies = new ArrayList<>();
for (int i=0; i < dataMovieTitle.length; i++){
Movie movie = new Movie();
movie.setImageMovie(dataPhoto.getResourceId(i, -1));
movie.setTitleMovie(dataMovieTitle[i]);
movie.setDescription(dataDescription[i]);
movies.add(movie);
}
}
#Override
public void onClick(View v) {
if(v.getId() == R.id.card_view){
}
}
}
and this is DetailMoviesActivity Class
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import com.squareup.picasso.Picasso;
public class DetailMovieActivity extends AppCompatActivity {
Movie movie;
TextView tvTitle, tvDesc;
ImageView ivMovie;
Button btnDetail;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail_movie);
initView();
}
private void initView() {
movie = (Movie) getIntent().getSerializableExtra("informasi");
String judul = movie.getTitleMovie();
String desc = movie.getDescription();
int img = movie.getImageMovie();
tvTitle.setText(judul);
tvDesc.setText(desc);
Picasso.get().load(img).into(ivMovie);
}
}
You can try with delete the setOnItemClickListener and call intent from cardViewViewHolder.itemView.setOnClickListener
My problem is, that i am trying to pass
final List<PieEntry> entries = new ArrayList<>(); to another fragment, which is more or less empty until now.
My complete code is this: ( of the fragment which initiates the ArrayList)
package com.example.nextpietwo;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.github.mikephil.charting.animation.Easing;
import com.github.mikephil.charting.charts.PieChart;
import com.github.mikephil.charting.components.Description;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.PieData;
import com.github.mikephil.charting.data.PieDataSet;
import com.github.mikephil.charting.data.PieEntry;
import com.github.mikephil.charting.highlight.Highlight;
import com.github.mikephil.charting.listener.OnChartValueSelectedListener;
import java.util.ArrayList;
import java.util.List;
public class SecondFragment extends Fragment {
// Store instance variables
private String title;
private int page;
// newInstance constructor for creating fragment with arguments
public static SecondFragment newInstance(int page, String title) {
SecondFragment fragmentSecond = new SecondFragment();
Bundle args = new Bundle();
args.putInt("someInt", page);
args.putString("someTitle", title);
fragmentSecond.setArguments(args);
return fragmentSecond;
}
// Store instance variables based on arguments passed
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
page = getArguments().getInt("someInt", 0);
title = getArguments().getString("someTitle");
}
// Inflate the view for the fragment based on layout XML
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.fragment_second, container, false);
TextView tvLabel2 = (TextView) view.findViewById(R.id.textView2);
//Alle Objekte hier einfügen (wie textview tvavel2)
final List<PieEntry> entries = new ArrayList<>();
final Button button = (Button) view.findViewById(R.id.button);
final TextView textView = (TextView) view.findViewById(R.id.textView);
final TextView textView2 = (TextView) view.findViewById(R.id.textView2);
final EditText editText = (EditText) view.findViewById(R.id.editText);
final EditText editText2 = (EditText) view.findViewById(R.id.editText2);
final EditText editText3 = (EditText) view.findViewById(R.id.editText3);
button.setOnClickListener(new View.OnClickListener() {
public void onClick (View view) {
if (editText3.getText().toString().matches("")) {
Toast.makeText(getActivity(), "You did not enter a Valid Item ID", Toast.LENGTH_LONG).show();
return;
} else if (editText2.getText().toString().matches("")) {
Toast.makeText(getActivity(), "You did not enter a Valid Quantitiy", Toast.LENGTH_LONG).show();
return;
} else {
String nomen = (editText3.getText().toString());
float number = Float.parseFloat(editText2.getText().toString());
entries.add(new PieEntry(number, nomen));
Bundle args = new Bundle();
args.putStringArrayList("array", ArrayList);
FirstFragment.setArguments(args);
editText3.setText("");
editText2.setText("");
editText3.requestFocus();
}
}
});
return view;
}
}
Simple explanations are appreciated!
Thanks in advance.
First of all make the make you PieEntry Parcelable by implementing interface Parcelable
Code to writeen in first Fragemnt
SecondFragment secondfragment //where data needs to be pass
Bundle bundle = new Bundle();
bundle.putParcelableArrayList("data", data);
secondfragment.setArguments(bundle);
data is a list of PieEntry
Code to written in second Fragemnt
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
data =getArguments().getParcelableArrayList("data");
}
}
I am implementing navigation drawer in my app and having a code as below
MainActivity.java
import android.support.v4.app.Fragment;
import android.app.FragmentManager;
import android.os.Bundle;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import com.example.project.project.TimeSheet.ObjectDrawerItem;
public class MainActivity extends AppCompatActivity {
private String[] mNavigationDrawerItemTitles;
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// get list items from strings.xml
mNavigationDrawerItemTitles = getResources().getStringArray(R.array.nav_drawer_items);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
// 2.1 create ActionBarDrawerToggle
ObjectDrawerItem[] drawerItem = new ObjectDrawerItem[3];
drawerItem[0] = new ObjectDrawerItem(R.mipmap.timesheet, "Time Sheet");
drawerItem[1] = new ObjectDrawerItem(R.mipmap.claims, "Claims");
DrawerItemCustomAdapter adapter = new DrawerItemCustomAdapter(this, R.layout.listview_item_row, drawerItem);
mDrawerList.setAdapter(adapter);
}
public class DrawerItemClickListener implements ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectItem(position);
}
private void selectItem(int position) {
Fragment fragment = null;
switch (position) {
case 0:
fragment=new Information();
break;
case 1:
fragment = new Claims();
break;
default:
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();
mDrawerList.setItemChecked(position, true);
mDrawerList.setSelection(position);
getActionBar().setTitle(mNavigationDrawerItemTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
} else {
Log.e("MainActivity", "Error in creating fragment");
}
}
}
}
I'm seeing a red line underneath fragment
fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();
When I point to the fragment , I get
Wrong 2nd ArgumentType.Found 'android.support.v4.app.Fragment', required 'android.app.Fragment';
And this is part of my Information activity
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Spinner;
import com.example.project.project.database.MyDatabaseHelper;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
public class Information extends Fragment implements View.OnClickListener {
private Spinner spinner;
private MyDatabaseHelper dbHelper;
private com.example.project.project.API.InfoAPI ts;
private static EditText txtDate;
private DateDialog dialog;
private static String a;
private static String date1;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
View info = inflater.inflate(R.layout.information, container, false);
dialog=new DateDialog();
ts = new com.example.project.project.API.InfoAPI(getActivity());
txtDate = (EditText) info.findViewById(R.id.editText5);
spinner = (Spinner) info.findViewById(R.id.spinner);
txtDate.setOnClickListener(this);
addItemsOnSpinner();
btnSaved.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
String date=txtDate.getText().toString();
ts.insertTimeSheet(spinner.getSelectedItem().toString(),spinner2.getSelectedItem().toString(),date,spinner3.getSelectedItem().toString());
Toast.makeText(getApplicationContext(), "Saved", Toast.LENGTH_SHORT).show();
}
});
Button button=(Button)info.findViewById(R.id.button5);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
Intent intent = new Intent(getActivity().getApplicationContext(), WorkForce.class);
a = spinner.getSelectedItem().toString();
intent.putExtra("a",a);
startActivity(intent);
}
});
return info;
}
public void onClick(View arg0) {
FragmentTransaction ft = getFragmentManager().beginTransaction();
dialog.show(ft, "DatePicker");
}
public void addItemsOnSpinner() {
List<String> list = new ArrayList<String>();
list.add("1");
list.add("2");
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_dropdown_item, list);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
}
LogCat error
Error:(86, 80) error: incompatible types: android.support.v4.app.Fragment cannot be converted to android.app.Fragment
If I import android.app.Fragment to both activities, I get incompatible types in my Information.java
public void onClick(View arg0) {
FragmentTransaction ft = getFragmentManager().beginTransaction();
dialog.show(ft, "DatePicker");
}
Change
getFragmentManager()
to
getSupportFragmentManager()