如何将数据从一个活动传递到另一活动

时间:2019-06-28 11:13:16

标签: java android android-activity

我正在创建一个事件应用程序,其中包含recyclerview中的事件列表。

事件recyclerview包含事件名称,图像,日期和时间,心脏图像(例如:Instagram上的心形按钮),当用户单击“感兴趣的”按钮时,其颜色将更改。

单击任何事件后,将显示其描述,并且有两个按钮:“感兴趣”和“进行”。如果用户单击“感兴趣”,则recyclerview中的心脏颜色将变为黄色。该事件还将保存在另一个列表中,直到将其从保存的列表中删除为止。

到目前为止,单击“感兴趣”按钮,我已经将该事件保存到保存的列表中。但是我不知道如何同时更改心形颜色以及如何保留它,直到事件从保存的列表中删除为止。

第一个活动调用回收站视图适配器

import android.content.Intent;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;


public class EventActivity extends AppCompatActivity {

    //this is the JSON Data URL
    //make sure you are using the correct ip else it will not work
    private static final String URL_PRODUCTS = "https://www.test.magicalballoons.co.in/priyanka/event.php?";

    //a list to store all the products

    List<Product> productList;


    //the recyclerview
    RecyclerView recyclerView;
    ImageView homemenu;

    //SwipeRefreshLayout swiper;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_event);
        getSupportActionBar().hide();


        homemenu = findViewById(R.id.homemenu);

       // swiper = findViewById(R.id.swiper);



        //getting the recyclerview from xml
        recyclerView = findViewById(R.id.recyclerView);
        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));



        //initializing the productlist
        productList = new ArrayList<>();

        homemenu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(EventActivity.this, MainActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
                startActivity(intent);
                finish();
            }
        });




        //this method will fetch and parse json
        //to display it in recyclerview
        loadProducts();
    }

    private void loadProducts() {

        /*
         * Creating a String Request
         * The request type is GET defined by first parameter
         * The URL is defined in the second parameter
         * Then we have a Response Listener and a Error Listener
         * In response listener we will get the JSON response as a String
         * */
        StringRequest stringRequest = new StringRequest(Request.Method.GET, URL_PRODUCTS,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {
                            //converting the string to json array object
                            JSONArray array = new JSONArray(response);

                            //traversing through all the object
                            for (int i = 0; i < array.length(); i++) {

                                //getting product object from json array
                                JSONObject product = array.getJSONObject(i);

                                //adding the product to product list
                                productList.add(new Product(
                                        product.getString("id"),
                                        product.getString("name"),
                                        product.getString("date"),
                                        product.getString("location"),
                                        product.getString("image"),
                                        product.getString("details")
                                ));
                            }

                            //creating adapter object and setting it to recyclerview
                            RecyclerViewAdapter adapter = new   RecyclerViewAdapter(EventActivity.this, productList);
                            recyclerView.setAdapter(adapter);
                            adapter.notifyDataSetChanged();
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Toast.makeText(EventActivity.this, error.getMessage(), Toast.LENGTH_SHORT).show();

                    }
                });

        //adding our stringrequest to queue
        Volley.newRequestQueue(this).add(stringRequest);
    }




    public void onBackPressed() {

        Intent intent = new Intent(EventActivity.this, MainActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        startActivity(intent);
        finish();

    }


}

Recyclerview适配器

   import android.app.Activity;
    import android.app.Dialog;
    import android.app.TimePickerDialog;
    import android.content.Context;
    import android.content.DialogInterface;
    import android.content.Intent;
    import android.graphics.Color;
    import android.graphics.drawable.ColorDrawable;
    import android.os.Handler;
    import android.support.v4.widget.SwipeRefreshLayout;
    import android.support.v7.app.AlertDialog;
    import android.support.v7.widget.CardView;
    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.EditText;
    import android.widget.ImageView;
    import android.widget.LinearLayout;
    import android.widget.ProgressBar;
    import android.widget.TextView;
    import android.widget.Toast;

    import com.android.volley.AuthFailureError;
    import com.android.volley.Request;
    import com.android.volley.RequestQueue;
    import com.android.volley.Response;
    import com.android.volley.VolleyError;
    import com.android.volley.toolbox.JsonArrayRequest;
    import com.android.volley.toolbox.StringRequest;
    import com.android.volley.toolbox.Volley;
    import com.bumptech.glide.Glide;
    import com.bumptech.glide.request.RequestOptions;
    import com.google.firebase.auth.FirebaseAuth;
    import com.google.firebase.auth.FirebaseUser;

    import org.json.JSONArray;
    import org.json.JSONException;
    import org.json.JSONObject;

    import java.text.BreakIterator;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;
    import java.util.Random;

    import static com.example.priyankaregistration.URLs.URL_EVENT;

    /**
     * Created by Aws on 11/03/2018.
     */

    public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.MyViewHolder> {

        private RequestQueue requestQueue;
        private JsonArrayRequest request;

        private Context mContext;
        private List<Product> mData;
        RequestOptions option;
        TextView total;
        ImageView colorheart,heart;




       // Dialog myDailog;
        private Dialog myDialog;





        public RecyclerViewAdapter(Context mContext, List<Product> mData) {
            this.mContext = mContext;
            this.mData = mData;
            //this.swiper = swiper;



            option=new RequestOptions().fitCenter().placeholder(R.drawable.background).error(R.drawable.background);
        }

        @Override
        public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

            View view;
            LayoutInflater inflater = LayoutInflater.from(mContext);
            view = inflater.inflate(R.layout.fragment_conferences, parent, false);
            final MyViewHolder viewHolder = new MyViewHolder(view);
            myDialog = new Dialog(mContext);
            colorheart = (ImageView) view.findViewById(R.id.colorheart);
            heart = (ImageView) view.findViewById(R.id.heart);



            total = (TextView) view.findViewById(R.id.count);
           StringRequest stringRequest = new StringRequest(Request.Method.POST, URLs.URL_COUNT,
                    new Response.Listener<String>() {
                        @Override
                        public void onResponse(String response) {
                            //progressDialog.dismiss();
                            try {

                                JSONObject jsonObject = new JSONObject(response);

                               total.setText(jsonObject.getString("countid"));

                            } catch (JSONException e) {
                                e.printStackTrace();

                            }
                        }
                    },
                    new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {

                        }
                    }) {
                @Override
                protected Map<String, String> getParams()  {
                    Map<String, String> params = new HashMap<>();
                    params.put("eventid", mData.get(viewHolder.getAdapterPosition()).getId());
                    return params;
                }
            };
            RequestQueue requestQueue = Volley.newRequestQueue(mContext);
            requestQueue.add(stringRequest);






            viewHolder.view_container.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    Intent intent = new Intent(mContext, Description.class);

                    intent.putExtra("eventname",mData.get(viewHolder.getAdapterPosition()).getName());
                    intent.putExtra("eventid",mData.get(viewHolder.getAdapterPosition()).getId());
                    intent.putExtra("eventdate",mData.get(viewHolder.getAdapterPosition()).getDate());
                    intent.putExtra("eventloc",mData.get(viewHolder.getAdapterPosition()).getLocation());
                    intent.putExtra("eventimg",mData.get(viewHolder.getAdapterPosition()).getImage());
                    intent.putExtra("details",mData.get(viewHolder.getAdapterPosition()).getDetails());

                    mContext.startActivity(intent);



                }
            });


                    return viewHolder;
        }







        @Override
        public void onBindViewHolder(final MyViewHolder holder, final int position) {
            holder.textViewName.setText(mData.get(position).getName());
            holder.textViewDate.setText("Date : " + mData.get(position).getDate());
            holder.textViewLocation.setText("Time : " + mData.get(position).getLocation());
            Glide.with(mContext).load(mData.get(position).getImage()).apply(option).into(holder.img_thumbnail);



        }





        @Override
        public int getItemCount() {
            return mData.size();
        }



        public static class MyViewHolder extends  RecyclerView.ViewHolder{


            TextView textViewName,textViewDate, textViewLocation,total;
            ImageView img_thumbnail;

            //LinearLayout view_container;
            CardView view_container;

            public MyViewHolder(View itemView) {
                super(itemView);

                view_container = itemView.findViewById(R.id.container);

                textViewName = itemView.findViewById(R.id.textViewName);
                textViewDate = itemView.findViewById(R.id.textViewDate);
                textViewLocation = itemView.findViewById(R.id.textViewLocation);

                total = itemView.findViewById(R.id.count);

                img_thumbnail=itemView.findViewById(R.id.imageView);

            }
        }



    }

这是第二项活动

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.method.ScrollingMovementMethod;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.support.design.widget.Snackbar;


import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;


public class Description extends AppCompatActivity {

    TextView textViewName,textViewDate, textViewLocation, details;
    ImageView evimg,going,interest;
    RequestOptions option;
    ImageView homemenu;







    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.details);
        getSupportActionBar().hide();

        option=new RequestOptions().fitCenter().placeholder(R.drawable.background).error(R.drawable.background);

        textViewName = findViewById(R.id.textViewName);

        evimg = findViewById(R.id.evimg);
        details = findViewById(R.id.details);
        going = findViewById(R.id.going);
        interest = findViewById(R.id.interest);
        homemenu = findViewById(R.id.homemenu);



        textViewName.setText(getIntent().getStringExtra("eventname"));
        //textViewDate.setText(getIntent().getStringExtra("eventdate"));
        //textViewLocation.setText(getIntent().getStringExtra("eventloc"));
        details.setText(getIntent().getStringExtra("details"));
        details.setMovementMethod(new ScrollingMovementMethod());


        Glide.with(this).load(getIntent().getStringExtra("eventimg")).apply(option).into(evimg);

        going.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                StringRequest stringRequest = new StringRequest(Request.Method.GET, URLs.URL_EVENT+"?userid=" + SharedPrefManager.getInstance(getApplicationContext()).getUserId() + "&eventid="+ getIntent().getStringExtra("eventid"),
                        new Response.Listener<String>() {
                            @Override
                            public void onResponse(String response) {

                                try {
                                    JSONObject jsonObject = new JSONObject(response);
                                    String message = jsonObject.getString("name");
                                    Intent intent = new Intent(Description.this,Ticket.class);

                                    intent.putExtra("code",message);
                                    intent.putExtra("eventimg",getIntent().getStringExtra("eventimg"));
                                    intent.putExtra("activity","NO");
                                   // intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
                                    jsonrequest();
                                    startActivity(intent);
                                    finish();

                                    //Toast.makeText(mContext,message,Toast.LENGTH_LONG).show();


                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }

                            }
                        },
                        new Response.ErrorListener() {
                            @Override
                            public void onErrorResponse(VolleyError error) {
                                Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();

                            }
                        }) {
                    @Override
                    protected Map<String, String> getParams() throws AuthFailureError {
                        Map<String, String> params = new HashMap<>();
                        //params.put("userid",SharedPrefManager.getInstance(getApplicationContext()).getUserId());
                        //params.put("eventid",getIntent().getStringExtra("eventid"));

                        return params;
                    }
                };

                RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
                requestQueue.add(stringRequest);


            }
        });



        interest.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(final View v) {

                StringRequest stringRequest = new StringRequest(Request.Method.POST, URLs.URL_EVENTSAVED ,
                        new Response.Listener<String>() {
                            @Override
                            public void onResponse(String response) {

                                try {
                                    JSONObject jsonObject = new JSONObject(response);
                                    //String message = jsonObject.getString("name")
                                    Toast.makeText(getApplicationContext(),jsonObject.getString("message"),Toast.LENGTH_LONG).show();



                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }
                        },
                        new Response.ErrorListener() {
                            @Override
                            public void onErrorResponse(VolleyError error) {
                                Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
                            }
                        }) {
                    @Override
                    protected Map<String, String> getParams() throws AuthFailureError {
                        Map<String, String> params = new HashMap<>();
                        params.put("userid",SharedPrefManager.getInstance(getApplicationContext()).getUserId());
                        params.put("eventid",getIntent().getStringExtra("eventid"));

                        return params;
                    }
                };

                RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
                requestQueue.add(stringRequest);
            }
        });


        homemenu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Description.this, MainActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
                startActivity(intent);
                finish();
            }
        });


    }

    private void jsonrequest() {


        StringRequest stringRequest = new StringRequest(Request.Method.POST, URLs.URL_EVENTDELETED,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        //progressDialog.dismiss();
                        try {
                            JSONObject jsonObject = new JSONObject(response);
                            Toast.makeText(getApplicationContext(),jsonObject.getString("Event removed from saved list"),Toast.LENGTH_LONG).show();


                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
                        //progressDialog.dismiss();
                    }
                }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> params = new HashMap<>();
                params.put("userid",SharedPrefManager.getInstance(getApplicationContext()).getUserId());
                params.put("eventid",getIntent().getStringExtra("eventid"));

                return params;
            }
        };
        RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
        requestQueue.add(stringRequest);
    }


}

我的recyclerview中有心脏图像。当我在“描述”活动中单击兴趣按钮时,recyclerview中的心脏图像会发生变化。

4 个答案:

答案 0 :(得分:0)

假设您将事件保存在某个模型类中,则可以在调用适配器的onBindViewHolder方法时进行检查,检查事件是否标记为保存。如果是这样,则您需要将心脏图像更改为另一个黄色的心脏图像,或者可以在心脏图像上应用淡色使其变为黄色。

您可以使用此代码更改可绘制对象

heartImageView.setImageDrawable(ContextCompat.getDrawable(context, R.drawable.yellow_heart));

您可以使用此代码来着色

heartImageView.setColorFilter(Color.argb(255, 255, 255, 0))

编辑(基于评论)

如果心脏处于第一个活动中,而感兴趣的按钮处于第二个活动中,那么您需要做的就是在单击感兴趣的按钮时保存事件的状态。返回第一个活动后,可以检查事件的状态,然后使用上述两种方法中的任何一种来更新图像。

编辑2(基于共享的新代码)

从Volley呼叫获得响应后,应将事件ID保存在某个位置,以跟踪感兴趣的事件(可以在模型类或某些全局列表中)。回到第一个活动(其中包含recyclerview)时,您需要使用已存储的事件ID列表来检查每个事件ID,并为每个匹配的事件改变心脏。

答案 1 :(得分:0)

您可以将color onclick事件应用于心脏按钮,如以下代码所示:

your_image_id.setBackgroundColor(getResources().getColor(R.color.yellow));

答案 2 :(得分:0)

您可以在startActivityforresult的帮助下完成

在活动1中,以以下方式启动活动2:

Intent i = new Intent(this, Activity2.class);
startActivityForResult(i, 1);

在Activity2中,使用setResult将数据发送回去:

Intent intent = new Intent();
intent.putExtra("updatedArraylist", "arraylist")
setResult(RESULT_OK, intent);        
finish();

在Activity1中,使用onActivityResult接收数据:

public void onActivityResult(int requestCode, int resultCode, 
Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == 1) {
        if(resultCode == RESULT_OK) {
            String strArrayList = 
            data.getStringExtra("updatedArraylist");
            Gson gson = new Gson();
            Type youListType = new TypeToken<List<Model>>() {
            }.getType();
            List<Model> yourTypeList = gson.fromJson(strArrayList, 
            yourListType);
            ArrayList finalArraylist = new ArrayList<>(yourTypeList);
            yourArraylist.addAll(finalArraylist);    
            youtAdapter.notifyDataSetChanged();
        }     
    }
} 

答案 3 :(得分:0)

第一项活动

Intent intent = new Intent(getApplicationContext(), SecondActivity.class);
startActivityForResult(intent, 100);

第二个活动中,您必须先执行以下代码,然后该活动才能被finish()或按back键破坏(为此,您可以覆盖第二个活动的onBackPressed并删除超类调用,然后调用以下方法)。

private void exitWithResult(){
    Intent returnIntent = new Intent();
    returnIntent.putExtra("result", "Id of selected item");
    setResult(Activity.RESULT_OK, returnIntent);
    finish();
}

再次第一个活动,您必须在onActivityResult方法中处理结果。

@Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        if (requestCode == 100) {
            if(resultCode == Activity.RESULT_OK){
                String result=data.getStringExtra("result");
                Log.e("DATA", "" + result);
            }
            if (resultCode == Activity.RESULT_CANCELED) {
                //Write your code if there's no result
                Log.e("DATA", "No result");
            }
        }
    }

更新

您可以将接口用作从适配器到活动的回调。 startActivityForResult可以在接口的回调方法中调用。您必须通过适配器构造函数以及数据集将回调接口传递给适配器。

适配器

中声明此界面
public interface AdapterCallback{

        void onAdapterSelected(int pos);

    }

然后在第一个活动中实现这样的界面。

MyAdapter.AdapterCallback callback = new MyAdapter.AdapterCallback() {
        @Override
        public void onAdapterSelected(int pos) {
            Intent intent = new Intent(getApplicationContext(), 
            SecondActivity.class);
            startActivityForResult(intent, 100);
        }
    };

然后像这样设置适配器

RecyclerView rv = findViewById(R.id.rv_list);
rv.setHasFixedSize(true);
rv.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
MyAdapter adapter = new MyAdapter(callback);   //This is the only change
rv.setAdapter(adapter);

下面适配器中的更改。 (您应该像以前一样传递列表数据以及回调)

    private AdapterCallback callback;

        public MyAdapter(AdapterCallback callback) {
            this.callback = callback;
        }

        @Override
        public void onBindViewHolder(@NonNull ViewHolder viewHolder, final int i) {
            viewHolder.mBtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    callback.onAdapterSelected(i);
                }


   });
    }

接口也进入适配器内部。我在这里不再重复,就像我最初提到的那样