简体   繁体   中英

how to move from a fragment to a new activity when i clicked an item of recyclerview?

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();
 } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM