Android Spinner Inside RecyclerView Get Current View When Selected - java

I have a RecyclerView implementing a LinearLayout of CardViews through an adapter. Inside each CardView, I have a spinner. What I need to do is get the CardViews position when a spinner is selected. Ex.. if I have 10 CardViews in a list on the screen with a spinner in each, and a select a value from the spinner in the 5th item, I need to get that 5th position as well as the selected value.
I'm able to get the selected value just fine. The issue is with getting the CardViews position. The CardViews are being generated from an ArrayList.
I will include my code below along with an image of the desired results. Any help is greatly appreciated!!
RecyclerView Adapter
public class PopularAdapter extends RecyclerView.Adapter<PopularAdapter.MyViewHolder> {
PopularFragment mPopularFragment;
private Context mContext;
private ArrayList<GameData> gameDataArr = new ArrayList<GameData>();
private String userId;
public PopularAdapter(Context context, ArrayList<GameData> gameDataArr, PopularFragment mPopularFragment, String userId) {
mContext = context;
this.gameDataArr = gameDataArr;
this.mPopularFragment = mPopularFragment;
this.userId = userId;
}
public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public TextView title;
public ImageView thumbnail;
private CardView mCardView;
PopularFragment mPopularFragment;
Spinner mGameSpinner;
LinearLayout mSpinnerLayout;
public MyViewHolder(View view, final PopularFragment mPopularFragment, final String userId) {
super(view);
this.mPopularFragment = mPopularFragment;
mSpinnerLayout = (LinearLayout) view.findViewById(R.id.spinner_layout);
title = (TextView) view.findViewById(R.id.item_title);
thumbnail = (ImageView) view.findViewById(R.id.item_main_img);
mCardView = (CardView) view.findViewById(R.id.item_cardview);
mCardView.setOnClickListener(this);
mGameSpinner = (Spinner) view.findViewById(R.id.game_spinner_options);
mGameSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long l) {
//String ASIN = gameDataArr.get(position).getAmazonId();
System.out.println(parent.getId()); // <--- prints the same value for each item.
if(userId == null){
Toast.makeText(mPopularFragment.getActivity(), "You must be logged in.", Toast.LENGTH_LONG).show();
return;
}
FirebaseDbHelper mFirebaseDbHelper = new FirebaseDbHelper();
if(position == 0){
// remove from db
// mFirebaseDbHelper.removeOwnedGame(ASIN, userId);
} else if(position == 1){
// add to owned games
// mFirebaseDbHelper.addOwnedGame(ASIN, userId);
} else {
// add to wishlist games
// mFirebaseDbHelper.addWishlistGame(ASIN, userId);
}
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
}
#Override
public void onClick(View view) {
System.out.println("click: " + getPosition());
//mPopularFragment.openGameActivity(getPosition());
}
}
#Override
public PopularAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
System.out.println("parent: " + parent);
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.list_item, parent, false);
return new PopularAdapter.MyViewHolder(itemView, mPopularFragment, userId);
}
#Override
public void onBindViewHolder(final PopularAdapter.MyViewHolder holder, final int position) {
GameData game = gameDataArr.get(position);
holder.title.setText(game.getTitle());
Picasso.with(mContext).load(game.getFeatImgUrl()).resize(160, 200).into(holder.thumbnail);
}
#Override
public int getItemCount() {
return gameDataArr.size();
}
}
CardView
<android.support.v7.widget.CardView
xmlns:card_view="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/item_cardview"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:layout_marginBottom="0dp"
card_view:cardCornerRadius="4dp"
>
<LinearLayout
android:padding="16dp"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:id="#+id/item_main_img"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_toLeftOf="#+id/right_content"
android:scaleType="fitXY"
android:adjustViewBounds="false"/>
<LinearLayout
android:id="#+id/right_content"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/item_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="16dp" />
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Spinner
android:id="#+id/game_spinner_options"
android:entries="#array/game_dropdown"
android:layout_width="wrap_content"
android:layout_height="wrap_content"></Spinner>
<Button
android:text="Buy Now"
android:id="#+id/game_buy_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
</LinearLayout>
</LinearLayout>
</android.support.v7.widget.CardView>
Popular Fragment
public class PopularFragment extends Fragment {
#BindView(R.id.popular_recyclerView)
RecyclerView mPopularRecyclerView;
private RecyclerView.Adapter mAdapter;
private ArrayList<GameData> gamesArray = new ArrayList<GameData>();
ApiResultsObject apiResults;
private FirebaseAuth auth;
private FirebaseUser user;
private FirebaseAuth.AuthStateListener authListener;
private String userId;
public PopularFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_popular, container, false);
ButterKnife.bind(this, view);
// bus instance
MyBus.getInstance().register(this);
// get api url
// trigger async task
// use results
String amazonApiUrl = getAmazonApiUrl();
if(amazonApiUrl != null){
new AmazonAsyncTask().execute(amazonApiUrl);
}
//get firebase auth instance
auth = FirebaseAuth.getInstance();
//get current user
user = FirebaseAuth.getInstance().getCurrentUser();
//add a auth listener
authListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
// User is signed in
System.out.println("User logged in. Game activity.");
userId = user.getUid();
} else {
// User is signed out
System.out.println("User not logged in. Game activity");
}
}
};
// Inflate the layout for this fragment
return view;
}
private String getAmazonApiUrl() {
String amazonApiUrl = "";
AmazonQuery amazonQuery = new AmazonQuery("ItemSearch");
amazonApiUrl = amazonQuery.buildUrl();
return amazonApiUrl;
}
private void setData(ApiResultsObject data) {
gamesArray = data.getGamesArray();
if (data != null) {
mAdapter = new PopularAdapter(getActivity().getBaseContext(), gamesArray, this, userId);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getActivity());
mPopularRecyclerView.setLayoutManager(mLayoutManager);
mPopularRecyclerView.setAdapter(mAdapter);
}
}
#Subscribe
public void onAsyncTaskResults(BrowseAsyncTaskResult event) {
apiResults = event.getResults();
if (apiResults != null) {
setData(apiResults);
}
}
#Override
public void onDestroy() {
MyBus.getInstance().unregister(this);
super.onDestroy();
}
#Override
public void onStart() {
super.onStart();
auth.addAuthStateListener(authListener);
}
#Override
public void onStop() {
super.onStop();
if (authListener != null) {
auth.removeAuthStateListener(authListener);
}
}
}

You can set an OnClickListener on mGameSpinner in your onBindViewHolder().
onBindViewHolder(final PopularAdapter.MyViewHolder holder, final int position)
You can then store/use the position parameter as it will be the index into your gameArray for that particular spinner. You can then use that index to grab the spinner's currently selected value and do whatever you need to do with it.

I think you should set a tag for each view in the RV through the holder in onBindViewHolder. Something like:
holder.itemView.setTag(game.getId());
The game's Id should be one of the data points in the ArrayList you passed into the Adpater. So it'd be easier to add a getId() method to your game object.
Once you have an integer Id to call on that's unique to each game in the list, you can simply find that Id within the Spinner's onItemSelectedListener with:
int ID = (int) holder.itemView.getTag();
Then you can use ID within your if-else statements to know which game within your card list the spinner is selected for.

#Override
public void onBindViewHolder(final LanguagesAdapter.MyViewHolder holder, final int position) {
holder.edit_language_name.setText(edit_languageDetails_ArrayList.get(position).getEt_language_name());
sp_langage_rating=edit_languageDetails_ArrayList.get(position).getEt_language_ratings();
String ss=sp_langage_rating;
if(sp_langage_rating != null) {
if(sp_langage_rating.equals("Beginner"))
{
adapterLanguage = new ArrayAdapter<CharSequence>(context, R.layout.my_spinner_items, strarray_language);
adapterLanguage.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
holder.sp_languages.setAdapter(adapterLanguage);
}
else if(sp_langage_rating.equals("Intermediate")) {
adapterLanguage = new ArrayAdapter<CharSequence>(context, R.layout.my_spinner_items, strarray_language1);
adapterLanguage.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
holder.sp_languages.setAdapter(adapterLanguage);
}else if(sp_langage_rating.equals("Expert")){
adapterLanguage = new ArrayAdapter<CharSequence>(context, R.layout.my_spinner_items, strarray_language2);
adapterLanguage.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
holder.sp_languages.setAdapter(adapterLanguage);
}
}else{
adapterLanguage = new ArrayAdapter<CharSequence>(context, R.layout.my_spinner_items, strarray_language);
adapterLanguage.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
holder.sp_languages.setAdapter(adapterLanguage);
}
Log.d("print","yes");
}

Related

How to change color and font on ListView after reading firebase DB

How to handle the problem of showing empty view for ListView because I don't know which data I have to put when I'm reading data from my firebase DB and display it in the ListView. and I'm using CustomListAdapter to change font color and the background color of ListView
Note: I'm reading data from firebase database and display it in ListView, any solution
CustomListAdapter.java
public class CustomListAdapter extends BaseAdapter {
private static final int HERO_COUNT = 12;
private Context context;
private List<String> items;
public CustomListAdapter(Context context) {
this.context = context;
items = new ArrayList<>();
}
#Override
public int getCount() {
return HERO_COUNT;
}
#Override
public String getItem(int position) {
if (position >= 0 && position < items.size()) {
return items.get(position);
}
return "";
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View v, ViewGroup parent) {
View mView = v;
if (mView == null) {
LayoutInflater vi = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mView = vi.inflate(R.layout.custom_list, null, false);
TextView text = (TextView) mView.findViewById(R.id.textView);
//textView.setTextColor(Color.BLUE);
text.setText(getItem(position));
if (items.isEmpty()) {
// Set holder color
} else {
text.setTextColor(Color.WHITE);
int color = Color.argb(200, 255, 64, 64);
text.setBackgroundColor(color);
}
}
return mView;
}
public void updateList(List<String> updatedItems) {
items.clear();
items.addAll(updatedItems);
notifyDataSetChanged();
}
}
ViewDatabase.java
public class ViewDatabase extends AppCompatActivity {
private static final String TAG = "ViewDatabase";
//add Firebase Database stuff
private FirebaseDatabase mFirebaseDatabase;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
private DatabaseReference myRef;
private String userID;
private ListView mListView;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.view_database_layout);
mListView = (ListView) findViewById(R.id.listview);
CustomListAdapter adapter = new CustomListAdapter(this);
mListView.setAdapter(adapter);
//declare the database reference object. This is what we use to access the database.
//NOTE: Unless you are signed in, this will not be useable.
mAuth = FirebaseAuth.getInstance();
mFirebaseDatabase = FirebaseDatabase.getInstance();
myRef = mFirebaseDatabase.getReference();
FirebaseUser user = mAuth.getCurrentUser();
// userID = user.getUid();
userID = "";
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
// User is signed in
Log.d(TAG, "onAuthStateChanged:signed_in:" + user.getUid());
toastMessage("Successfully signed in.");
} else {
// User is signed out
Log.d(TAG, "onAuthStateChanged:signed_out");
toastMessage("Successfully signed out.");
}
// ...
}
};
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// This method is called once with the initial value and again
// whenever data at this location is updated.
showData(dataSnapshot);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void showData(DataSnapshot dataSnapshot) {
for (DataSnapshot ds : dataSnapshot.getChildren()) {
DailyInfo uInfo = new DailyInfo();
uInfo.setHero1(ds.child(userID).getValue(DailyInfo.class).getHero1()); //set the name1
uInfo.setHero2(ds.child(userID).getValue(DailyInfo.class).getHero2()); //set the name2
uInfo.setHero3(ds.child(userID).getValue(DailyInfo.class).getHero3()); //set the name3
uInfo.setHero4(ds.child(userID).getValue(DailyInfo.class).getHero4()); //set the name4
uInfo.setHero5(ds.child(userID).getValue(DailyInfo.class).getHero5()); //set the name5
uInfo.setHero6(ds.child(userID).getValue(DailyInfo.class).getHero6()); //set the name6
uInfo.setHero7(ds.child(userID).getValue(DailyInfo.class).getHero7()); //set the name7
uInfo.setHero8(ds.child(userID).getValue(DailyInfo.class).getHero8()); //set the name8
uInfo.setHero9(ds.child(userID).getValue(DailyInfo.class).getHero9()); //set the name9
uInfo.setHero10(ds.child(userID).getValue(DailyInfo.class).getHero10()); //set the name10
uInfo.setHero11(ds.child(userID).getValue(DailyInfo.class).getHero11()); //set the name11
uInfo.setHero12(ds.child(userID).getValue(DailyInfo.class).getHero12()); //set the name12
//display all the information
Log.d(TAG, "showData: Hero1: " + uInfo.getHero1());
Log.d(TAG, "showData: Hero2: " + uInfo.getHero2());
Log.d(TAG, "showData: Hero3: " + uInfo.getHero3());
Log.d(TAG, "showData: Hero4: " + uInfo.getHero4());
Log.d(TAG, "showData: Hero5: " + uInfo.getHero5());
Log.d(TAG, "showData: Hero6: " + uInfo.getHero6());
Log.d(TAG, "showData: Hero7: " + uInfo.getHero7());
Log.d(TAG, "showData: Hero8: " + uInfo.getHero8());
Log.d(TAG, "showData: Hero9: " + uInfo.getHero9());
Log.d(TAG, "showData: Hero10: " + uInfo.getHero10());
Log.d(TAG, "showData: Hero11: " + uInfo.getHero11());
Log.d(TAG, "showData: Hero12: " + uInfo.getHero12());
ArrayList<String> array = new ArrayList<>();
array.add(uInfo.getHero1());
array.add(uInfo.getHero2());
array.add(uInfo.getHero3());
array.add(uInfo.getHero4());
array.add(uInfo.getHero5());
array.add(uInfo.getHero6());
array.add(uInfo.getHero7());
array.add(uInfo.getHero8());
array.add(uInfo.getHero9());
array.add(uInfo.getHero10());
array.add(uInfo.getHero11());
array.add(uInfo.getHero12());
/* ArrayAdapter adapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1,array);
mListView.setAdapter(adapter);*/
if (mListView.getAdapter() instanceof CustomListAdapter) {
((CustomListAdapter) mListView.getAdapter()).updateList(array);
mListView.setBackgroundColor(ContextCompat.getColor(mListView.getContext(), R.color.category_colors));
}
}
}
#Override
public void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthListener);
}
#Override
public void onStop() {
super.onStop();
if (mAuthListener != null) {
mAuth.removeAuthStateListener(mAuthListener);
}
}
/**
* customizable toast
*
* #param message
*/
private void toastMessage(String message) {
Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
}
}
view_database_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="#+id/tvUserInfo"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="User Information"
android:textAlignment="center"
android:textColor="#color/colorPrimaryDark"
android:textSize="25sp"/>
<ListView
android:id="#+id/listview"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
</LinearLayout>
custom_list.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/textView"
android:textSize="20px" android:paddingTop="10dip" android:paddingBottom="10dip"/>
</LinearLayout>
DailyInfo.java
public class DailyInfo {
private String hero1;
private String hero2;
private String hero3;
private String hero4;
private String hero5;
private String hero6;
private String hero7;
private String hero8;
private String hero9;
private String hero10;
private String hero11;
private String hero12;
public DailyInfo(){
}
public String getHero1() {
return hero1;
}
public void setHero1(String hero1) {
this.hero1 = hero1;
}
public String getHero2() {
return hero2;
}
public void setHero2(String hero2) {
this.hero2 = hero2;
}
public String getHero3() {
return hero3;
}
public void setHero3(String hero3) {
this.hero3 = hero3;
}
public String getHero4() {
return hero4;
}
public void setHero4(String hero4) {
this.hero4 = hero4;
}
public String getHero5() {
return hero5;
}
public void setHero5(String hero5) {
this.hero5 = hero5;
}
public String getHero6() {
return hero6;
}
public void setHero6(String hero6) {
this.hero6 = hero6;
}
public String getHero7() {
return hero7;
}
public void setHero7(String hero7) {
this.hero7 = hero7;
}
public String getHero8() {
return hero8;
}
public void setHero8(String hero8) {
this.hero8 = hero8;
}
public String getHero9() {
return hero9;
}
public void setHero9(String hero9) {
this.hero9 = hero9;
}
public String getHero10() {
return hero10;
}
public void setHero10(String hero10) {
this.hero10 = hero10;
}
public String getHero11() {
return hero11;
}
public void setHero11(String hero11) {
this.hero11 = hero11;
}
public String getHero12() {
return hero12;
}
public void setHero12(String hero12) {
this.hero12 = hero12;
}
}
You're creating the adapter after receiving the response on ValueEventListener:
CustomListAdapter adapter = new CustomListAdapter(ViewDatabase.this , R.layout.custom_list , mList);
ListView mListView= findViewById(R.id.listview);
mListView.setAdapter(adapter);
Instead of that, set the adapter on ViewDatabase within onCreate for instance and set the color based on that initial state.
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.view_database_layout);
mListView = findViewById(R.id.listview);
CustomListAdapter adapter = new CustomListAdapter(this);
mListView.setAdapter(adapter);
//[...]
}
And, instead of creating the adapter, update it:
private void showData(DataSnapshot dataSnapshot) {
//[...]
if (mListView.getAdapter() instanceof CustomListAdapter) {
((CustomListAdapter)mListView.getAdapter()).updateList(array);
}
}
You could also replace ArrayAdapter with BaseAdapter as the extended class:
public class CustomListAdapter extends BaseAdapter {
private static final int HERO_COUNT = 12;
private Context context;
private List<String> items;
public CustomListAdapter(Context context) {
this.context = context;
items = new ArrayList<>();
}
#Override
public int getCount() {
return HERO_COUNT;
}
#Override
public String getItem(int position) {
if (position >= 0 && position < items.size()) {
return items.get(position);
}
return "";
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View v, ViewGroup parent) {
View mView = v;
if (mView == null) {
LayoutInflater vi = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mView = vi.inflate(R.layout.custom_list, null, false);
}
//Bind view content here
//TODO associate holder to tag
return mView;
}
public void updateList(List<String> updatedItems) {
items.clear();
items.addAll(updatedItems);
notifyDataSetChanged();
}
}
}
EDIT:
In order to have a default background color on the list to be changed when the values are received, you can set the default color on the main layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="#+id/tvUserInfo"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="User Information"
android:textAlignment="center"
android:textColor="#color/colorPrimaryDark"
android:textSize="25sp"/>
<ListView
android:id="#+id/listview"
android:background="#color/empty_color"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
</LinearLayout>
And then change it when the values are received:
private void showData(DataSnapshot dataSnapshot) {
//[...]
if (mListView.getAdapter() instanceof CustomListAdapter) {
((CustomListAdapter)mListView.getAdapter()).updateList(array);
listView.setBackgroundColor(ContextCompat.getColor(listView.getContext(), R.color.loaded_color));
}
}
If what you want is to change the row color then you'll need to change the row layout on getView when the string is empty.
EDIT 2
Specified where to make the view changes
You are modifying the view only when it hasn't been created before, which won't be the case the next time around, that's it, when the data is available. So, based on your code (should consider including a holder btw):
public View getView(int position, View v, ViewGroup parent) {
View mView = v;
if (mView == null) {
LayoutInflater vi = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mView = vi.inflate(R.layout.custom_list, null, false);
}
TextView text = (TextView) mView.findViewById(R.id.textView);
text.setText(getItem(position));
if (items.isEmpty()) {
// Set holder color
} else {
text.setTextColor(Color.WHITE);
}
return mView;
}

Setting an id to a Switch

I have a recycle view which populates data from a server, the components inside are a textView and a Switch. The server can return n number of data. How can i set a unique id to the Switch2 when I am populating the data, because later I will need to set a listener to the Switches, My server actually returns a unique id but I'm not so sure on how to set it to the Switch2, or is there any alternate parameters that can be used to identify the Switch?
layout
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
tools:layout_editor_absoluteY="81dp">
<android:android.support.v7.widget.CardView xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
card_view:cardElevation="1dp"
card_view:cardUseCompatPadding="true"
>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Switch
android:id="#+id/switch2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="left|center_vertical"
android:paddingLeft="5dip"
android:layout_marginTop="16dp"
app:layout_constraintTop_toTopOf="parent"
tools:layout_editor_absoluteX="254dp" />
<TextView
android:id="#+id/user_set_light_id"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:fontFamily="sans-serif"
android:text="TextView"
android:textSize="20dp"
tools:layout_editor_absoluteX="27dp"
tools:layout_editor_absoluteY="23dp" />
</RelativeLayout>
</android:android.support.v7.widget.CardView>
</android.support.constraint.ConstraintLayout>
adapter
public class populateLights_adapter extends RecyclerView.Adapter<populateLights_adapter.ViewHolder> {
private List<populate_lights> listItems;
private Context context;
public populateLights_adapter(List<populate_lights> listItems, Context context) {
this.listItems = listItems;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.addlight_items, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
populate_lights listItem = listItems.get(position);
holder.lightText.setText(listItem.getLightName());
holder.status.setChecked(listItem.getState());
}
#Override
public int getItemCount() {
return listItems.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
public TextView lightText;
public Switch status;
public ViewHolder(View itemView) {
super(itemView);
lightText = (TextView) itemView.findViewById(R.id.user_set_light_id);
status = (Switch) itemView.findViewById(R.id.switch2);
}
}
}
java class
public class populate_lights {
private String lightName;
private boolean state;
public populate_lights(String lightName, boolean state){
this.lightName = lightName;
this.state = state;
}
public String getLightName(){
return lightName;
}
public boolean getState(){
return state;
}
}
main
public class lightsControl extends Fragment {
View myView;
public static final String URL = "serverurl.com";
private RecyclerView recyclerView;
private RecyclerView.Adapter adapter;
private List<populate_lights> listItems;
private Switch mySwitch;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
myView = inflater.inflate(R.layout.lightscontrol, container, false);
recyclerView = (RecyclerView) myView.findViewById(R.id.lightsView);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this.getActivity()));
listItems = new ArrayList<>();
loadData();
adapter = new populateLights_adapter(listItems, myView.getContext());
recyclerView.setAdapter(adapter);
return myView;
}
private void loadData(){
final ProgressDialog progressDialog = new ProgressDialog(myView.getContext());
progressDialog.setMessage("Loading");
progressDialog.show();
StringRequest stringRequest = new StringRequest(Request.Method.POST,
URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
progressDialog.dismiss();
Snackbar mySnackbar = Snackbar.make(myView, "Data Fetched!", Snackbar.LENGTH_SHORT);
mySnackbar.show();
Log.v("DATA_RESPONSE", response);
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray array = jsonObject.getJSONArray("lightData");
for(int i=0;i<array.length();i++){
JSONObject obj = array.getJSONObject(i);
Log.v("LIGHT ID ", "index=" + obj.getString("LightID"));
Log.v("Value ", "index=" + obj.getBoolean("Value"));
populate_lights popLights = new populate_lights(
obj.getString("LightID"), //unique id
obj.getBoolean("Value") //value returns true, or false
);
listItems.add(popLights);
}
adapter = new populateLights_adapter(listItems, myView.getContext());
recyclerView.setAdapter(adapter);
}
catch(Exception e){
e.printStackTrace();
}
}},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Snackbar mySnackbar = Snackbar.make(myView, "Oops, there was an error communicating with our server, try again", Snackbar.LENGTH_SHORT);
mySnackbar.show();
Log.v("LoginFormERROR", "index=" + error);
progressDialog.dismiss();
}
}
)
};
RequestQueue requestQueue = Volley.newRequestQueue(myView.getContext());
requestQueue.add(stringRequest);
}
public void showErrorAlert(){
AlertDialog.Builder builder1 = new AlertDialog.Builder(myView.getContext());
builder1.setMessage("Opps, something went wring");
builder1.setCancelable(true);
builder1.setPositiveButton(
"Main Menu",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
getActivity().onBackPressed();
}
});
AlertDialog alert11 = builder1.create();
alert11.show();
}
}
screenshot
See if this code prints the right position in the logs. Put this inside the constructor of the view holder in the adapter class:
status.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
Log.d("Position: ", String.valueOf(getLayoutPosition()));
}
});

get selected single checkbox in recycler view

I have multiple options for a poll and user can select only one option. i am getting options in recycler view with a checkbox and textview.
i want to uncheck previous selected checkbox if user select another checkbox and get selected text by pressing submit button.
here is my recycler view code.
public class Poll_Options_recyclerView_Adapter extends RecyclerView.Adapter<Poll_Options_recyclerView_Adapter.MyViewHolder> {
public List<Poll_Option_Result> result = new ArrayList<>();
Context mycontext;
public Poll_Options_recyclerView_Adapter(List<Poll_Option_Result> result, Context context) {
this.result = result;
this.mycontext = context;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.custom_option_rec_list, parent, false);
return new MyViewHolder(itemView, mycontext, result);
}
public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView poll_option;
CheckBox checkBox;
List<Poll_Option_Result> result_List = new ArrayList<>();
Context mycontext;
public MyViewHolder(View itemView, Context mycontext, List<Poll_Option_Result> result_List) {
super(itemView);
this.result_List = result_List;
this.mycontext = mycontext;
poll_option = (TextView) itemView.findViewById(R.id.optionA);
checkBox=(CheckBox)itemView.findViewById(R.id.check_box);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
}
}
#Override
public void onBindViewHolder(Poll_Options_recyclerView_Adapter.MyViewHolder holder, int position) {
final Poll_Option_Result ResultList = result.get(position);
holder.poll_option.setText(ResultList.getOption());
}
#Override
public int getItemCount() {
return result.size();
}
}
and here is my recycler view custom xml code.
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:weightSum="5"
>
<CheckBox
android:id="#+id/check_box"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="0.5"/>
<TextView
android:layout_width="0dp"
android:layout_weight="4.5"
android:layout_height="wrap_content"
android:text="xyz"
android:layout_marginLeft="20dp"
android:textColor="#color/colortoolbartitle"
android:padding="5dp"
android:id="#+id/optionA"/>
private int mCheckedPostion = -1;// no selection by default
Done by adding this code in onBindViewHolder
#Override
public void onBindViewHolder(final Poll_Options_recyclerView_Adapter.MyViewHolder holder, final int position) {
final Poll_Option_Result ResultList = result.get(position);
holder.poll_option.setText(ResultList.getOption());
//check checkbox and uncheck previous selected button
holder.checkBox.setChecked(position == mCheckedPostion);
holder.checkBox.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (position == mCheckedPostion) {
holder.checkBox.setChecked(false);
StringGen.username = "";
mCheckedPostion = -1;
} else {
mCheckedPostion = position;
StringGen.username = holder.poll_option.getText().toString();
Toast.makeText(mycontext, "select : "+position+holder.poll_option.getText(), Toast.LENGTH_SHORT).show();
notifyDataSetChanged();
}
}
});
}

How To Make a Phone Call with Button click in Recyclerview

i want use the method ACTION_CALL . the problem is when i click the button of the first cardview the app call the phone number 11111111 . & when i click the button of the second card view the app call also the same number 1111111.
what i want is when i click the button of the first cardview it call 111111
and when i click on the button of the second cardview it call 22222222
item layout xml :
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
xmlns:app="http://schemas.android.com/tools"
android:id="#+id/card_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:background="#android:color/transparent"
app:contentPaddingBottom="50dp"
android:paddingBottom="50dp"
card_view:cardElevation="6dp"
>
<RelativeLayout
android:longClickable="true"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="5dp"
android:paddingBottom="7dp">
<ImageView
android:id="#+id/profileImage"
android:layout_width="70dp"
android:layout_height="50dp"
app:civ_border_color="#7f89e9"
android:layout_marginLeft="5dp"
android:background="#drawable/contact1"
android:layout_alignTop="#+id/txtCelebName"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<TextView
android:layout_marginTop="8dp"
android:id="#+id/txtCelebName"
android:textSize="15dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/profileImage"
android:text="Large Text"
android:layout_marginLeft="18dp"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:layout_marginLeft="18dp"
android:textSize="13dp"
android:id="#+id/txtCelebMovie"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/txtCelebName"
android:layout_toRightOf="#+id/profileImage"
android:text="Small Text"
android:textAppearance="?android:attr/textAppearanceSmall" />
<TextView
android:layout_marginLeft="5dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="............"
android:id="#+id/textView4"
android:layout_below="#+id/profileImage" />
<Button
android:background="#drawable/phonegreen"
android:layout_width="45dp"
android:layout_height="45dp"
android:id="#+id/buttonfordialog"
android:layout_above="#+id/textView"
android:layout_toRightOf="#+id/textView5"
android:layout_toEndOf="#+id/textView5"
android:layout_marginLeft="22dp"
android:layout_marginStart="22dp" />
</RelativeLayout>
Adapter :
public class ItemAdapter extends RecyclerView.Adapter<ItemAdapter.ItemHolder> {
private List<Celebrity> celebrityList;
private final View.OnClickListener btnListener;
public ItemAdapter(List<Celebrity> celebrityList, View.OnClickListener btnListener) {
this.celebrityList = celebrityList;
this.btnListener = btnListener;
}
#Override
public ItemHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.item_layout, parent, false);
return new ItemHolder(itemView, btnListener);
}
#Override
public void onBindViewHolder(ItemHolder holder, int position) {
Celebrity item = celebrityList.get(position);
holder.txtCelebName.setText(item.getName());
holder.txtCelebMovie.setText(item.getFamousMovie());
}
#Override
public int getItemCount() {
return celebrityList.size();
}
public class ItemHolder extends RecyclerView.ViewHolder {
private Button buttoncalling;
public TextView txtCelebName, txtCelebMovie;
public ImageView profileImage;
public ItemHolder(View view, View.OnClickListener btnListener) {
super(view);
txtCelebName = (TextView) view.findViewById(R.id.txtCelebName);
txtCelebMovie = (TextView) view.findViewById(R.id.txtCelebMovie);
profileImage = (ImageView) view.findViewById(R.id.profileImage);
buttoncalling = (Button) view.findViewById(R.id.buttonfordialog);
buttoncalling.setOnClickListener(btnListener);
}
}
}
Main java :
public class MainActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private ItemAdapter itemAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final View.OnClickListener btnListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder a_builder = new AlertDialog.Builder(MainActivity.this);
a_builder.setCancelable(false);
a_builder.setMessage("do you want to call this person!!!");
a_builder.setPositiveButton("yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:11111111111"));
if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
startActivity(callIntent);
}
});
a_builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
AlertDialog alert = a_builder.create();
alert.setTitle("Alert !");
alert.show();
}
};
final Toolbar toolbar = (Toolbar)findViewById(R.id.MyToolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
CollapsingToolbarLayout collapsingToolbarLayout = (CollapsingToolbarLayout)findViewById(R.id.collapse_toolbar);
collapsingToolbarLayout.setTitle("Service/DPNG");
ArrayList<Celebrity> itemList = new ArrayList<>();
fillDummyData(itemList);
recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
itemAdapter = new ItemAdapter(itemList, btnListener);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(itemAdapter);
}
private void fillDummyData(ArrayList<Celebrity> celebList) {
Celebrity celeb1 = new Celebrity();
celeb1.setName("Johny.D");
celeb1.setFamousMovie("Pirates ");
celeb1.setProfilePhotoLocation("#drawable/contact1");
celebList.add(celeb1);
Celebrity celeb2 = new Celebrity();
celeb2.setName("Arnold");
celeb2.setFamousMovie("The Terminator");
celeb2.setProfilePhotoLocation("http://ia.media-imdb.com/images/M/MV5BMTI3MDc4NzUyMV5BMl5BanBnXkFtZTcwMTQyMTc5MQ##._V1._SY209_CR13,0,140,209_.jpg");
celebList.add(celeb2);
This is pretty old but I hope someone may find this answer useful:
First of all, you're hard-coding the number to call in your button listener. Hence, whatever button you click on, you're asking it to make a call to 1111111.
What you need to do is to add a field in your Celebrity class for a phone number. Then in your adapter, create an interface that will be implemented in your MainActivity class. Thus, on click of an item (which in this case is a cardview), you retrieve the phone number of the celebrity, and feed that to your implemented interface where you make the call to the celebrity.
Doing so, you'll be retrieving the right phone number for each celebrity instead of using the hard-coded string you currently have.
Adapter:
public interface CardClickListener {
onCardClicked(Celebrity celebrity);
}
MainActivity:
public class MainActivity extends AppCompatActivity implements ItemAdapter.CardClickListener {
......
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
........
// add the following to your onCreate method
recyclerView.addOnItemTouchListener(new RecyclerTouchListener(this, recyclerView, new ClickListener() {
#Override
public void onClick(View view, int position) {
Celebrity celebrity = itemList.get(position);
onCardClicked(celebrity);
}
#Override
public void onLongClick(View view, int position) {
}
}));
.........
}
// implement your interface here
#Override
public void onCardClicked(Celebrity celebrity) {
// don't forget to check for permissions
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:" + celebrity.phone));
}
......
// add phone numbers to your class definitions
private void fillDummyData(ArrayList<Celebrity> celebList) {
Celebrity celeb1 = new Celebrity();
celeb1.setName("Johny.D");
celeb1.setFamousMovie("Pirates ");
celeb1.setPhone("111111");
celeb1.setProfilePhotoLocation("#drawable/contact1");
celebList.add(celeb1);
Celebrity celeb2 = new Celebrity();
celeb2.setName("Arnold");
celeb2.setFamousMovie("The Terminator");
celeb2.setPhone("222222");
celeb2.setProfilePhotoLocation("http://ia.mediaimdb.com/images/M/209_.jpg");
celebList.add(celeb2);
}
} //mainactivity
RecyclerTouchListener:
public class RecyclerTouchListener implements RecyclerView.OnItemTouchListener {
private GestureDetector gestureDetector;
private ClickListener clickListener;
public RecyclerTouchListener(Context context, final RecyclerView recyclerView, final ClickListener clickListener) {
this.clickListener = clickListener;
gestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
#Override
public boolean onSingleTapUp(MotionEvent e) {
return true;
}
#Override
public void onLongPress(MotionEvent e) {
View child = recyclerView.findChildViewUnder(e.getX(), e.getY());
if (child != null && clickListener != null) {
clickListener.onLongClick(child, recyclerView.getChildAdapterPosition(child));
}
}
});
}
#Override
public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
View child = rv.findChildViewUnder(e.getX(), e.getY());
if (child != null && clickListener != null && gestureDetector.onTouchEvent(e)) {
clickListener.onClick(child, rv.getChildAdapterPosition(child));
}
return false;
}
#Override
public void onTouchEvent(RecyclerView rv, MotionEvent e) {
}
#Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
}
ClickListener:
public interface ClickListener {
void onClick(View view, int position);
void onLongClick(View view, int position);
}

I have multiple recyclerViews ,which should appear after another XML view,

I have multiple recyclerViews ,which should appear after another XML view, but they just don't , am using an adapter class to manage this. after using log.v I found that the the functions itself"in Adappter class" arent called , and i don't know why ??
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/ScrollView01"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.linah.movielessonapp.Detailed_Movie">
<TextView
android:id="#+id/MovieTitle"
... />
<ImageView
android:id="#+id/MovieImage"
.../>
<TextView
android:id="#+id/MovieReview"
... />
<Button
android:id="#+id/Favbutton"
... />
<TextView
android:id="#+id/Date"
... />
<TextView
android:id="#+id/Rate"
.../>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.v7.widget.RecyclerView
android:id="#+id/Trailers_recycler_view"
android:scrollbars="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/MovieReview" />
<android.support.v7.widget.RecyclerView
android:id="#+id/reviews_recycler_view"
android:scrollbars="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/Trailers_recycler_view"
/>
</LinearLayout>
</RelativeLayout>
</ScrollView>
public class Detailed_Movie extends AppCompatActivity {
public static List<Movie_Details> movieDetailsList = new ArrayList<>();
private String ID;
public String Trailer_OR_Review = "trailer";
private boolean noConnection;
private boolean trailersDone;
private int trailersSize;
private static MoviesDetailedAdapter mAdapter;
private RecyclerView TrailerRecyclerView, ReviewsRecyclerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detailed__movie);
TrailerRecyclerView = (RecyclerView) findViewById(R.id.Trailers_recycler_view);
ReviewsRecyclerView = (RecyclerView) findViewById(R.id.reviews_recycler_view);
new getData().execute("trailer");
// adapter
mAdapter = new MoviesDetailedAdapter(movieDetailsList,TrailerRecyclerView.getContext(),Trailer_OR_Review);
// mAdapter = new MoviesDetailedAdapter(movieDetailsList,ReviewsRecyclerView.getContext(),Trailer_OR_Review);
TrailerRecyclerView.setLayoutManager(new LinearLayoutManager(TrailerRecyclerView.getContext()));
// ReviewsRecyclerView.setLayoutManager(new LinearLayoutManager(ReviewsRecyclerView.getContext()));
TrailerRecyclerView.setItemAnimator(new DefaultItemAnimator());
// ReviewsRecyclerView.setItemAnimator(new DefaultItemAnimator());
noConnection = false;
if(isOnline(Detailed_Movie.this)) {
new getData().execute("trailer");
mAdapter.notifyDataSetChanged();
}
// set the adapter
TrailerRecyclerView.setAdapter(mAdapter);
prepareMovieData();
Intent i = getIntent();
// http://api.themoviedb.org/3/movie/{id}/videos
String ImgPath = "http://image.tmdb.org/t/p/w185/";
String VideoPath = "http://www.youtube.com/watch?v=";
String MovieTitle = i.getExtras().getString("title");
Toast.makeText(getApplicationContext(),MovieTitle+" is selected!", Toast.LENGTH_SHORT).show();
ImageView img = (ImageView)findViewById(R.id.MovieImage);
TextView Title = (TextView)findViewById(R.id.MovieTitle);
TextView Review = (TextView)findViewById(R.id.MovieReview);
TextView Date = (TextView)findViewById(R.id.Date);
TextView Rate = (TextView)findViewById(R.id.Rate);
Button Fav = (Button) findViewById(R.id.Favbutton);
// get data from intent
assert Title != null;
Title. setText(i.getExtras().getString("title"));
assert Review != null;
Review.setText(i.getExtras().getString("review"));
assert Rate != null;
Rate. setText(i.getExtras().getString("rate"));
assert Date != null;
Date. setText(i.getExtras().getString("date"));
ID = i.getExtras().getString("id");
String Imgurl = i.getExtras().getString("img");
// append ImgPath
switch (ImgPath = new StringBuilder()
.append(ImgPath)
.append(Imgurl)
.toString()) {
}
// append VideoPath
VideoPath = new StringBuilder()
.append(VideoPath)
.append("6uEMl2BtcqQ")
.toString();
// VideoPath = VideoPath + getString(R.string.API_KEY);
final String finalVideoPath = VideoPath;
if (Fav != null) {
Fav.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_VIEW,
Uri.parse(finalVideoPath));
startActivity(intent);
}
});
}
Picasso.with(this)
.load(ImgPath)
.placeholder(R.drawable.loading) //this is optional the image to display while the url image is downloading
.error(R.drawable.error) //this is also optional if some error has occurred in downloading the image
.into(img);
TrailerRecyclerView.addOnItemTouchListener(new RecyclerTouchListener(getApplicationContext(), TrailerRecyclerView, new ClickListener() {
#Override
public void onClick(View view, int position) {
Movie_Details movie = movieDetailsList.get(position);
if (position < trailersSize) {
// String link = ((TextView) findViewById(R.id.Link)).getText().toString();
// String link = movie.getKey();
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.youtube.com/watch?v=" + movie.getKey())));
}
}
#Override
public void onLongClick(View view, int position) {
}
}));
}
private void prepareMovieData() {
Movie_Details movie = new Movie_Details("MovieTrailer","6uEMl2BtcqQ","Linah","verynice");
movieDetailsList.add(movie);
mAdapter.notifyDataSetChanged();
}
public interface ClickListener {
void onClick(View view, int position);
void onLongClick(View view, int position);
}
public static class RecyclerTouchListener implements RecyclerView.OnItemTouchListener {
private GestureDetector gestureDetector;
private MainActivity.ClickListener clickListener;
public RecyclerTouchListener(Context context, final RecyclerView recyclerView, final MainActivity.ClickListener clickListener) {
this.clickListener = clickListener;
gestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
#Override
public boolean onSingleTapUp(MotionEvent e) {
return true;
}
#Override
public void onLongPress(MotionEvent e) {
View child = recyclerView.findChildViewUnder(e.getX(), e.getY());
if (child != null && clickListener != null) {
clickListener.onLongClick(child, recyclerView.getChildPosition(child));
}
}
});
}
public RecyclerTouchListener(Context applicationContext, RecyclerView trailerRecyclerView, ClickListener clickListener) {
}
#Override
public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
View child = rv.findChildViewUnder(e.getX(), e.getY());
if (child != null && clickListener != null && gestureDetector.onTouchEvent(e)) {
clickListener.onClick(child, rv.getChildPosition(child));
}
return false;
}
#Override
public void onTouchEvent(RecyclerView rv, MotionEvent e) {
}
#Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
}
public class getData extends AsyncTask<String, Void, Void> {
...
}
}
class MoviesDetailedAdapter
public class MoviesDetailedAdapter extends RecyclerView.Adapter {
private List<Movie_Details> moviesList;
private Context context;
public String Trailer_OR_Review = "trailer";
public TextView TrailerName , Author , Content , TrailerLink ;
public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnCreateContextMenuListener {
public MyViewHolder(View view) {
super(view);
Log.v("here","MyViewHolder");
TrailerName = (TextView) view.findViewById(R.id.Name);
Author = (TextView) view.findViewById(R.id.Author);
TrailerLink = (TextView) view.findViewById(R.id.Link);
Content = (TextView) view.findViewById(R.id.Content);
view.setOnCreateContextMenuListener(this);
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
}
}
public MoviesDetailedAdapter(List<Movie_Details> moviesList,Context context, String trailerORReview) {
this.moviesList = moviesList;
this.context = context;
Trailer_OR_Review = trailerORReview;
Log.v("here","madapter");
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView;
Log.v("here","onCreateViewHolder");
itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.trailers_layout, parent, false);
/*
if (Trailer_OR_Review.equals("trailers")){
itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.trailers_layout, parent, false);
}
else{
itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.reviews_layout, parent, false);
}*/
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
Log.v("here","onBindViewHolder");
Movie_Details movie_details = moviesList.get(position);
Log.v("here",movie_details.getContent());
Log.v("here",movie_details.getName());
TrailerName.setText(movie_details.getName());
TrailerLink.setText(movie_details.getKey());
/*
if (Trailer_OR_Review.equals("trailers")){
TrailerName.setText(movie_details.getName());
TrailerLink.setText(movie_details.getKey());
}
else{
Author.setText(movie_details.getAuthor());
Content.setText(movie_details.getContent());
}*/
}

Categories