Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass values from RecycleAdapter to MainActivity or Other Activities

I am working on a shopping cart app,Items are displayed as below.There is a plus, minus (+/-) buttons to choose the number of quantity.

If product quantity is changed, I need to pass "productname" and "quantity" to the main activity so that I could use them to prepare final cart. I got some suggestions to use database or some content providers,

I am not sure how to do it.., please help

Recycle Adapter for Shoping cart

MainActivity.java

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

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

How to do this,

like image 811
Joseph Joseph Avatar asked Jan 26 '16 07:01

Joseph Joseph


People also ask

How do you pass data from second activity to first activity?

Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main. xml. Step 4 − Add the following code to res/layout/activity_second.

How pass data from RecyclerView to another activity in Android Studio?

Following this, you can just use getIntent() in your second activity and obtain the values and display them. I want to shed some light on the working of intents . Using an intent , you can pass data between activities. See my onBindViewHolder() code.


2 Answers

You should create interface, and activity implements this interface.

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

When you create adapter (last parameter is this interface)

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 } 

// In Adapter

  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());     } 
like image 162
Phuoc Huynh Avatar answered Sep 22 '22 08:09

Phuoc Huynh


I failed to do it with both Interface and Observer pattern. But Local Broadcast worked for me.

In Adapter

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

Main Activity

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();         }     }; 
like image 22
Joseph Joseph Avatar answered Sep 22 '22 08:09

Joseph Joseph