Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
187 views
in Technique[技术] by (71.8m points)

android - 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

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



    }
}

How to do this,

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...