如何将值从RecycleAdapter传递到MainActivity或其他活动

时间:2016-01-26 07:37:31

标签: android android-recyclerview recycler-adapter

我正在购买购物车应用程序,项目显示如下。有一个加号,减号(+/-)按钮来选择数量。

如果产品数量发生变化,我需要将“productname”和“quantity”传递给主要活动,以便我可以使用它们来准备最终购物车。我得到了一些使用数据库或一些内容提供商的建议,

我不知道怎么做..请帮助

Recycle Adapter for Shoping cart

MainActivity.java

import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.Window;
import android.widget.Toast;

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

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class MainActivity extends AppCompatActivity {

RecyclerView recyclerView;
RecycleAdapter recycleAdapter;
List<HashMap<String, String>> onlineData;
ProgressDialog pd;

Toolbar toolbar;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    recyclerView = (RecyclerView) findViewById(R.id.recyle_view);
    toolbar= (Toolbar) findViewById(R.id.anim_toolbar);
    setSupportActionBar(toolbar);

    LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getBaseContext());
    recyclerView.setLayoutManager(linearLayoutManager);
    recyclerView.setHasFixedSize(true);

    final String url = "http://www.qa4.org/?json=get_recent_posts&count=45";
    new AsyncHttpTask().execute(url);



}

public class AsyncHttpTask extends AsyncTask<String, Void, Integer> {

    @Override
    protected void onPreExecute() {
        pd=new ProgressDialog(MainActivity.this);
        pd.requestWindowFeature(Window.FEATURE_NO_TITLE);
        pd.setMessage("Loading please wait...");
        pd.setCancelable(false);
        pd.show();
    }

    @Override
    protected Integer doInBackground(String... params) {
        Integer result = 0;
        HttpURLConnection urlConnection;
        try {
            URL url = new URL(params[0]);
            urlConnection = (HttpURLConnection) url.openConnection();
            int statusCode = urlConnection.getResponseCode();

            // 200 represents HTTP OK
            if (statusCode == 200) {
                BufferedReader r = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
                StringBuilder response = new StringBuilder();
                String line;
                while ((line = r.readLine()) != null) {
                    response.append(line);
                }
                parseResult(response.toString());
                result = 1; // Successful
            } else {
                result = 0; //"Failed to fetch data!";
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result; //"Failed to fetch data!";
    }

    @Override
    protected void onPostExecute(Integer result) {
        // Download complete. Let us update UI
        pd.dismiss();

        if (result == 1) {
            recycleAdapter = new RecycleAdapter(MainActivity.this,onlineData);
            recyclerView.setAdapter(recycleAdapter);
        } else {
            Toast.makeText(MainActivity.this, "Failed to fetch data!", Toast.LENGTH_SHORT).show();
        }
    }
}

private void parseResult(String result) {
    try {
        JSONObject response = new JSONObject(result);
        JSONArray posts = response.optJSONArray("posts");
        onlineData = new ArrayList<>();

        for (int i = 0; i < posts.length(); i++) {
            JSONObject post = posts.optJSONObject(i);

            HashMap<String, String> item = new HashMap<>();
            item.put("title", post.optString("title"));

            JSONArray jsonArray = post.getJSONArray("attachments");
            JSONObject jsonObject1 = jsonArray.getJSONObject(0);
            JSONObject jsonArrayImages = jsonObject1.getJSONObject("images");
            JSONObject jsonArrayThumb = jsonArrayImages.getJSONObject("thumbnail");

            item.put("thump", jsonArrayThumb.optString("url"));

            onlineData.add(item);


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

}

RecycleAdapter.java

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
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.TextView;

import com.squareup.picasso.Picasso;

import java.util.HashMap;
import java.util.List;

public class RecycleAdapter extends RecyclerView.Adapter<RecycleAdapter.ViewHolderRec> {

    List<HashMap<String, String>> onlineData;
    SQLiteDatabase db;
    Context context;
    RecycleAdapter(Context context,List<HashMap<String, String>> onlineData){
        this.onlineData = onlineData;
        this.context=context;
    }

    @Override
    public ViewHolderRec onCreateViewHolder(ViewGroup parent, int viewType) {
        return new ViewHolderRec( LayoutInflater.from(parent.getContext()).inflate(R.layout.item_recycle, parent, false));

       }

    @Override
    public void onBindViewHolder(ViewHolderRec holder, int position) {

    HashMap<String,String> map =onlineData.get(position);

        //Download image using picasso library
        Picasso.with(context).load(map.get("thump"))
                .error(R.drawable.placeholder)
                .placeholder(R.drawable.placeholder)
                .into(holder.iv);

        holder.tv.setText(map.get("title"));

    }

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

    public class ViewHolderRec extends RecyclerView.ViewHolder implements View.OnClickListener{
        ImageView iv;
        TextView tv, quantity;
        ImageView Add_Cart;
        ImageView Remove_Cart;

        public ViewHolderRec(View itemView) {
            super(itemView);
            iv = (ImageView) itemView.findViewById(R.id.thumbnail);
            tv = (TextView) itemView.findViewById(R.id.title);
            quantity = (TextView)itemView.findViewById(R.id.cart_qty);
            Add_Cart = (ImageView)itemView.findViewById(R.id.cart_add);
            Remove_Cart = (ImageView)itemView.findViewById(R.id.cart_remove);
            itemView.setOnClickListener(this);
            Add_Cart.setOnClickListener(this);
            Remove_Cart.setOnClickListener(this);
        }

        @Override
        public void onClick(View v) {
            if(v.getId() == Add_Cart.getId())
            {
                 increment();



            }
            else if(v.getId() == Remove_Cart.getId())
            {
                decrement();

            }
        }

        public void increment(){
            int currentNos = Integer.parseInt(quantity.getText().toString()) ;
           quantity.setText(String.valueOf(++currentNos));
        }

        public void decrement(){
            int currentNos = Integer.parseInt(quantity.getText().toString()) ;

            quantity.setText(String.valueOf(--currentNos));
        }



    }
}

如何做到这一点,

6 个答案:

答案 0 :(得分:29)

您应该创建接口,而活动会实现此接口。

public interface OnItemClick {
    void onClick (String value);
}

创建适配器时(最后一个参数是此接口)

public class MainActivity extends AppCompatActivity implements OnItemClick {
 recycleAdapter = new RecycleAdapter(MainActivity.this,onlineData, this);
            recyclerView.setAdapter(recycleAdapter);

 @Override
 void onClick (String value){
// value this data you receive when increment() / decrement() called
}

//在适配器

  private OnItemClick mCallback;

RecycleAdapter(Context context,List<HashMap<String, String>>     onlineData,OnItemClick listener){
    this.onlineData = onlineData;
    this.context = context;
    this.mCallback = listener;
 }
    ....

    public void increment(){
        int currentNos = Integer.parseInt(quantity.getText().toString()) ;
        quantity.setText(String.valueOf(++currentNos));
        mCallback.onClick(quantity.getText().toString());
    }

    public void decrement(){
        int currentNos = Integer.parseInt(quantity.getText().toString()) ;
        quantity.setText(String.valueOf(--currentNos));
        mCallback.onClick(quantity.getText().toString());
    }

答案 1 :(得分:23)

我没有使用Interface和Observer模式。但是Local Broadcast为我工作了。

在适配器

String ItemName = tv.getText().toString();
                String qty = quantity.getText().toString();
                Intent intent = new Intent("custom-message");
                //            intent.putExtra("quantity",Integer.parseInt(quantity.getText().toString()));
                intent.putExtra("quantity",qty);
                intent.putExtra("item",ItemName);
                LocalBroadcastManager.getInstance(context).sendBroadcast(intent);

主要活动

public void onCreate(Bundle savedInstanceState) {

  ...

  // Register to receive messages.
  // We are registering an observer (mMessageReceiver) to receive Intents
  // with actions named "custom-message".
  LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver,
      new IntentFilter("custom-message"));
}

...
public BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            // Get extra data included in the Intent
            String ItemName = intent.getStringExtra("item");
            String qty = intent.getStringExtra("quantity");
             Toast.makeText(MainActivity.this,ItemName +" "+qty ,Toast.LENGTH_SHORT).show();
        }
    };

答案 2 :(得分:5)

解决此问题的三种流行方法

  1. 接口
  2. Phuoc Huynh已经解释了如何使用接口来解决这个问题。

    1. 观察者模式。
    2. 尝试在观察者周围搜索,了解其工作原理。我们将注册想要接收具有他们想要接收的事件类型的事件的类。将有一个管理器类来管理接收器的注册和取消注册,以及将事件发送到所有接收器

      public class EventManager {
          private static EventManager eventManager;
          private static Object syncObject = new Object();
          private HashMap<String, ArrayList<EventListener>> listeners = new   HashMap<>();
      
          private EventManager(){}
      
          public static EventManager getInstance() {
              if (eventManager == null) {
                  synchronized (syncObject) {
                      if (eventManager == null) {
                          eventManager = new EventManager();
                      }
                  }
              }
              return eventManager;
          }
      
          public synchronized void registerListener(String event, EventListener listener) {
              if (listeners.containsKey(event)) {
                  listeners.get(event).add(listener);
              } else {
                  ArrayList<EventListener> arrayList = new ArrayList<>();
                  arrayList.add(listener);
                  listeners.put(event, arrayList);
              }
          }
      
          public synchronized void unRegisterListener(String event, EventListener listener) {
              if (listeners.containsKey(event)) {
                  listeners.get(event).remove(listener);
                  if (listeners.get(event).size() == 0) {
                      listeners.remove(event);
                  }
              }
          }
      
          public void sendEvent(String event, Object o) {
              if (listeners.containsKey(event)) {
                  ArrayList<EventListener> listener = listeners.get(event);
                  for (EventListener eventListener : listener) {
                      eventListener.onEvent(o);
                  }
              }
          }
      }
      

      您的MainActivity将自身注册为递增和递减事件的接收者,并实现IEventListener的onEvent方法

      public class MainActivity extends AppCompatActivity implements IEventListener{
          @Override
          protected void onCreate(Bundle onSavedInstanceState) {
              EventManager.getInstance().registerEvent("increment", this);
              EventManager.getInstance().registerEvent("decrement", this)
          }
      
          @Override
          public void onEvent(String event) {
              if (event.equals("increment") {
                  //increment
              } else if (event.equals("decrement") {
                  //decrement
              }
          }
      
          @Override
          protected void onDestroy() {
              EventManager.getInstance().unRegisterEvent("increment", this);
              EventManager.getInstance().unRegisterEvent("decrement", this)
          }
      }
      

      在适配器类中发送事件

      EventManager.getInstance().sendEvent("increment");
      EventManager.getInstance().sendEvent("decrement");
      
      1. LocalBroadcasts
      2. LocalBroadcasts的工作方式与上面的示例相同。您已获得LocalBroadcastManger的实例并在其上发送广播。在活动的onCreate中定义广播接收器,并使用Activity中的registerReceiver()进行注册。在寄存器接收器中传递一个intent过滤器,其actiontype与您希望活动接收的广播相同。确保在不需要广播时或在活动的onDestroy中取消注册广播

答案 3 :(得分:1)

查看此内容。它对我有用。

只需粘贴您的活动或片段

rvSelectedProductList = Recyclerview
selcetedItemAdapter = RecyclerView Adapter
              rvSelectedProductList.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
                    @Override
                    public void onGlobalLayout() {

                        final int itemCount = selectedItemAdapter.getItemCount();

                        for (int i = 0; i < itemCount; i++) {
                            TextView tvSelling = rvSelectedProductList.getChildAt(i).findViewById(R.id.tvSelling);
                            TextView textViewDrawerTitle = rvSelectedProductList.getChildAt(i).findViewById(R.id.tvCartQty);


                            String totalamount = tvSelling.getText().toString();
                            String qty = textViewDrawerTitle.getText().toString();
                            System.out.println("qty" + qty);
                            System.out.println("total" + totalamount);
                        }
                        rvSelectedProductList.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                    }
                });

答案 4 :(得分:0)

将这些代码添加到onBindViewHolder

LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver, new IntentFilter("message_subject_intent"));

   public BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
    String name= intent.getStringExtra("id");
    Toast.makeText(MainActivity.this, name, Toast.LENGTH_SHORT).show();
    }
};

在MainActivity上添加

{{1}}

答案 5 :(得分:0)

//Simply it works for me
//In onBindViewHolder of RecyclerAdapter write the following code on clickEvent of any view;


Intent intent = new Intent(tContext, TargetActivity.class);
intent.putExtra("key", "value");
tContext.startActivity(intent);


//TargetActivity.java

  String str = getIntent().getStringExtra("key");
//You got the value as String :)