How To Make a Phone Call with Button click in Recyclerview - java

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

Related

What is the proper way to do a fragment in Android?

I'm relatively new to Android Studio and I'm doing an app, one of it's interface's function is to show the data of various user's and I saw various tutorials on how to list data using FirebaseRecyclerAdapter but they are not working. And now I'm trying to do fragments which I don't know how to do yet.
I'd like to know if this code is properly set up to do a fragment.
My MainActivity.java
public class MainActivity extends AppCompatActivity {
private RelativeLayout pills_layout, appoint_layout, add_pills_layout, add_appoints_layout, account_layout, add_button;
private TextView AccountName0, AccountAge0;
private RecyclerView recyclerView;
private LinearLayoutManager linearLayoutManager;
private FirebaseRecyclerAdapter adapter;
private View view;
private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
= new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.navigation_home:
Home();
return true;
case R.id.navigation_pills:
Pills();
return true;
case R.id.navigation_appointment:
Appointment();
return true;
case R.id.navigation_account:
Account();
return true;
}
return false;
}
};
public MainActivity() {
}
private void Account(){
RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) add_button.getLayoutParams();
params.addRule(RelativeLayout.BELOW, R.id.account);
pills_layout.setVisibility(View.GONE);
appoint_layout.setVisibility(View.GONE);
add_pills_layout.setVisibility(View.GONE);
add_appoints_layout.setVisibility(View.GONE);
//account_layout.setVisibility(View.VISIBLE);
add_button.setVisibility(View.VISIBLE);
/*Button accountChangePass = findViewById(R.id.AccountChangePass);
accountChangePass.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent ChangePW = new Intent(MainActivity.this, ChangePW.class);
startActivity(ChangePW);
}
});*/
}
private void Appointment() {
RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) add_button.getLayoutParams();
params.addRule(RelativeLayout.BELOW, R.id.add_appoints);
pills_layout.setVisibility(View.GONE);
appoint_layout.setVisibility(View.GONE);
add_pills_layout.setVisibility(View.GONE);
add_appoints_layout.setVisibility(View.VISIBLE);
//account_layout.setVisibility(View.GONE);
add_button.setVisibility(View.VISIBLE);
}
private void Pills() {
RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) add_button.getLayoutParams();
params.addRule(RelativeLayout.BELOW, R.id.add_pills);
pills_layout.setVisibility(View.GONE);
appoint_layout.setVisibility(View.GONE);
add_pills_layout.setVisibility(View.VISIBLE);
add_appoints_layout.setVisibility(View.GONE);
//account_layout.setVisibility(View.GONE);
add_button.setVisibility(View.VISIBLE);
}
private void Home() {
pills_layout.setVisibility(View.VISIBLE);
appoint_layout.setVisibility(View.VISIBLE);
add_pills_layout.setVisibility(View.GONE);
add_appoints_layout.setVisibility(View.GONE);
//account_layout.setVisibility(View.GONE);
add_button.setVisibility(View.GONE);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if (user == null) {
Intent VerifyLogin = new Intent(MainActivity.this, Launcher.class);
VerifyLogin.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(VerifyLogin);
}
pills_layout = findViewById(R.id.pills_layout);
appoint_layout = findViewById(R.id.appoint_layout);
add_pills_layout = findViewById(R.id.add_pills);
add_appoints_layout = findViewById(R.id.add_appoints);
//account_layout = findViewById(R.id.accountlist);
AccountName0 = findViewById(R.id.AccountName0);
AccountAge0 = findViewById(R.id.AccountAge0);
add_button = findViewById(R.id.add);
pills_layout.setVisibility(View.VISIBLE);
appoint_layout.setVisibility(View.VISIBLE);
add_pills_layout.setVisibility(View.GONE);
add_appoints_layout.setVisibility(View.GONE);
//account_layout.setVisibility(View.GONE);
add_button.setVisibility(View.GONE);
recyclerView = findViewById(R.id.accountlist);
linearLayoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.setHasFixedSize(true);
BottomNavigationView navigation = findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
}
public class ViewHolder extends RecyclerView.ViewHolder {
public RelativeLayout root;
public TextView txtTitle;
public TextView txtDesc;
public ViewHolder(View itemView) {
super(itemView);
root = itemView.findViewById(R.id.account);
txtTitle = itemView.findViewById(R.id.AccountName0);
txtDesc = itemView.findViewById(R.id.AccountAge0);
}
public void setTxtTitle(String string) {
txtTitle.setText(string);
}
public void setTxtDesc(String string) {
txtDesc.setText(string);
}
}
#Override
protected void onStart() {
super.onStart();
Query query = FirebaseDatabase.getInstance()
.getReference()
.child("Users");
FirebaseRecyclerOptions<Account> options =
new FirebaseRecyclerOptions.Builder<Account>()
.setQuery(query, new SnapshotParser<Account>() {
#NonNull
#Override
public Account parseSnapshot(#NonNull DataSnapshot snapshot) {
return new Account(snapshot.child("name").getValue().toString(),
snapshot.child("idade").getValue().toString());
}
})
.build();
adapter = new FirebaseRecyclerAdapter<Account, ViewHolder>(options) {
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.account, parent, false);
return new ViewHolder(view);
}
#Override
protected void onBindViewHolder(ViewHolder holder, final int position, Account model) {
holder.setTxtTitle(model.getName());
holder.setTxtDesc(model.getIdade());
holder.root.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(MainActivity.this, String.valueOf(position), Toast.LENGTH_SHORT).show();
}
});
}
};
recyclerView.setAdapter(adapter);
adapter.startListening();
}
#Override
protected void onStop() {
super.onStop();
Query query = FirebaseDatabase.getInstance()
.getReference()
.child("Users");
FirebaseRecyclerOptions<Account> options =
new FirebaseRecyclerOptions.Builder<Account>()
.setQuery(query, new SnapshotParser<Account>() {
#NonNull
#Override
public Account parseSnapshot(#NonNull DataSnapshot snapshot) {
return new Account(snapshot.child("name").getValue().toString(),
snapshot.child("idade").getValue().toString());
}
})
.build();
adapter = new FirebaseRecyclerAdapter<Account, ViewHolder>(options) {
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.account, parent, false);
return new ViewHolder(view);
}
#Override
protected void onBindViewHolder(ViewHolder holder, final int position, Account model) {
holder.setTxtTitle(model.getName());
holder.setTxtDesc(model.getIdade());
holder.root.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(MainActivity.this, String.valueOf(position), Toast.LENGTH_SHORT).show();
}
});
}
};
recyclerView.setAdapter(adapter);
adapter.stopListening();
}
};
My Account.java
public class Account {
private String name, idade;
public Account() {
}
public Account(String name, String idade) {
this.name = name;
this.idade = idade;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getIdade() {
return idade;
}
public void setIdade(String idade) {
this.idade = idade;
}
}
My account.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/account">
<RelativeLayout
android:id="#+id/AccountUser"
android:layout_width="match_parent"
android:layout_height="163dp"
android:layout_marginStart="15dp"
android:layout_marginLeft="15dp"
android:layout_marginTop="15dp"
android:layout_marginEnd="15dp"
android:layout_marginRight="15dp"
android:layout_marginBottom="15dp"
android:background="#drawable/edit_bg"
android:padding="15dp">
<RelativeLayout
android:id="#+id/AccountImage"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_user"/>
</RelativeLayout>
<RelativeLayout
android:id="#+id/AccountInfos"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#id/AccountImage"
android:layout_toEndOf="#id/AccountImage"
android:layout_marginStart="15dp"
android:layout_marginLeft="15dp">
<TextView
android:id="#+id/AccountName0"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingTop="5dp"
android:paddingBottom="5dp"
android:text="Nome1"
android:textColor="#color/colorWhite"
android:textSize="20sp"
android:textStyle="bold" />
<TextView
android:id="#+id/AccountAge0"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/AccountName0"
android:paddingTop="5dp"
android:paddingBottom="5dp"
android:text="Idade1"
android:textColor="#color/colorWhite"
android:textSize="20sp"
android:textStyle="bold" />
<Button
android:id="#+id/AccountChangePass"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/AccountAge0"
android:text="Mudar Palavra-Passe"
android:textColor="#color/colorWhite"
android:textSize="18sp"
android:textStyle="bold"
android:textAllCaps="false"
android:padding="10dp"
android:layout_marginTop="10dp"
android:background="#drawable/custom_button"/>
</RelativeLayout>
</RelativeLayout>
</RelativeLayout>
</RelativeLayout>
the best way to do that in my opinion is using Fragments.
Create 3 fragments:
Just check the checkBox that says " Create layout XML? "
Create a java class and add this code after create 3 fragments:
public class /* class name 1 */ extends FragmentPagerAdapter {
public /* class name 1 */ (FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position){
case 0:
Fragment1 fragment1= new Fragment1 ();
return fragment1;
case 1:
Fragment2 fragment2 = new Fragment2();
return fragment2 ;
case 2:
Fragment3 fragment3 = new Fragment3 ();
return fragment3 ;
default:
return null;
}
}
#Override
public int getCount() {
return 3;
}
public CharSequence getPageTitle(int position){
switch (position){
case 0:
return "/* set a name to fragment1*/";
case 1:
return "/* set a name to fragment2*/";
case 2:
return "/* set a name to fragment3*/";
default:
return null;
}
}
}
Now in your mainActivity.java add this code:
public class MainActivity extends AppCompatActivity {
private ViewPager mViewPager;
private /* class name 1 */ mSectionsPagerAdapter;
private TabLayout mTabLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mViewPager = findViewById(R.id.main_tabPager);
mSectionsPagerAdapter = new /* class name 1 */(getSupportFragmentManager());
mViewPager.setAdapter(mSectionsPagerAdapter);
mTabLayout = findViewById(R.id.main_tabs);
mTabLayout.setupWithViewPager(mViewPager);
}
}
Now in your mainactivity.xml add this:
<android.support.v4.view.ViewPager
android:id="#+id/main_tabPager"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:visibility="visible"
tools:ignore="UnknownId"></android.support.v4.view.ViewPager>
<android.support.design.widget.TabLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/colorAccent"
android:id="#+id/main_tabs">
</android.support.design.widget.TabLayout>
The final result will look like this:
I suppose pills_layout, appoint_layout, .. are your fragment layouts.
Maintaining them by changing their VISIBILITY property is not a good idea.
You have to use the supportFragmentManager instead.
Create a loadFragment method like this
public final boolean loadFragment(#NotNull Fragment fragment) {
this.getSupportFragmentManager().beginTransaction()
.replace(<<id of your fragment container layout>>, fragment, "fragment").commit();
return true;
}
And change your onNavigationItemSelected method to this:
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.navigation_home:
return loadFragment(new HomeFragment());
case R.id.navigation_pills:
return loadFragment(new PillsFragment());
case R.id.navigation_appointment:
return loadFragment(new AppointmentFragment());
case R.id.navigation_account:
return loadFragment(new AccountFragment());
}
return false;
}
};
Now make a seperate class for each fragment and inflate the layout of the right fragment.
here is an example of how your HomeFragment-class has to look like this:
public final class HomeFragment extends Fragment {
#Override
public View onCreate(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
return inflater.inflate(R.layout.<<your homefragment layout name>>, null);
}
}
I hope it's enough to help you out. I'm sorry if there are little mistakes in syntax, I'm used to code Android in Kotlin. But you will get the idea behind it.

NULL Pointer Exception Error Application Crashed After Clicking on Recycler List Item

I am working on an android application that is showing data in Recycle List View Holder. When I Click on List Item in Recycler View Holder the application crashes.
public class UserRecyclerAdapterSavedUsers extends RecyclerView.Adapter<UserRecyclerAdapterSavedUsers.UserViewHolder> {
private List<User> listUsers;
Context mContext;
ItemClickListenerLongPressed itemClickListenerLongPressed;
public UserRecyclerAdapterSavedUsers(List<User> listUsers) {
this.listUsers = listUsers;
}
#Override
public UserViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.item_user_recycler_second, parent, false);
return new UserViewHolder(itemView);
}
#Override
public void onBindViewHolder(UserViewHolder holder, int position) {
holder.textViewID.setText(listUsers.get(position).getUserid());
holder.textViewName.setText(listUsers.get(position).getName());
holder.textViewPassword.setText(listUsers.get(position).getPassword());
holder.textViewRole.setText(listUsers.get(position).getRole());
}
public void setItemClickListenerLongPressed(ItemClickListenerLongPressed itemClickListenerLongPressed){
this.itemClickListenerLongPressed=itemClickListenerLongPressed;
}
#Override
public int getItemCount() {
Log.v(UserRecyclerAdapterSavedUsers.class.getSimpleName(),""+listUsers.size());
return listUsers.size();
}
/**
* ViewHolder class
*/
public class UserViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
//public AppCompatTextView ID;
public AppCompatTextView textViewID;
public AppCompatTextView textViewName;
public AppCompatTextView textViewPassword;
public AppCompatTextView textViewRole;
public UserViewHolder(View view) {
super(view);
textViewID = (AppCompatTextView) view.findViewById(R.id.textViewID);
textViewName = (AppCompatTextView) view.findViewById(R.id.textViewName);
textViewPassword = (AppCompatTextView) view.findViewById(R.id.textViewPassword);
textViewRole = (AppCompatTextView) view.findViewById(R.id.textViewRole);
}
#Override
public void onClick(View v) {
if (itemClickListenerLongPressed != null) itemClickListenerLongPressed.onClick(v, getAdapterPosition());
Toast.makeText(mContext, "USMAN", Toast.LENGTH_SHORT).show();
}
}
}
Here is the users List activity
public class UsersListActivity extends AppCompatActivity implements ItemClickListenerLongPressed{
AppCompatActivity activity = UsersListActivity.this;
AppCompatTextView textViewName;
RecyclerView mRecyclerView;
AppCompatButton textViewButtonNewUser;
UserRecyclerAdapterSavedUsers userRecyclerAdapterSavedUsers;
List<User> listUsers;
DatabaseHelper databaseHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_record_updated_list);
mRecyclerView= (RecyclerView) findViewById(R.id.recyclerViewUsers);
mRecyclerView.setAdapter(userRecyclerAdapterSavedUsers);
userRecyclerAdapterSavedUsers.setItemClickListenerLongPressed(this);
initViews();
initObjects();
}
#Override
public void onBackPressed() {
super.onBackPressed();
startActivity(new Intent(UsersListActivity.this,AdminMain.class));
finish();
}
#Override
protected void onRestart() {
super.onRestart();
}
/**
* This method is to initialize views
*/
private void initViews() {
textViewName = (AppCompatTextView) findViewById(R.id.textViewName);
textViewButtonNewUser = (AppCompatButton) findViewById(R.id.btnaddnew);
mRecyclerView = (RecyclerView) findViewById(R.id.recyclerViewUsers);
textViewButtonNewUser.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(UsersListActivity.this,UserRecordSaveActivity.class));
}
});
}
/**
* This method is to initialize objects to be used
*/
private void initObjects() {
listUsers = new ArrayList<>();
userRecyclerAdapterSavedUsers = new UserRecyclerAdapterSavedUsers(listUsers);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
mRecyclerView.setLayoutManager(mLayoutManager);
mRecyclerView.setItemAnimator(new DefaultItemAnimator());
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setAdapter(userRecyclerAdapterSavedUsers);
databaseHelper = new DatabaseHelper(activity);
String emailFromIntent = getIntent().getStringExtra("USERS");
textViewName.setText(emailFromIntent);
getDataFromSQLite();
}
/**
* This method is to fetch all user records from SQLite
*/
private void getDataFromSQLite() {
// AsyncTask is used that SQLite operation not blocks the UI Thread.
new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... params) {
listUsers.clear();
listUsers.addAll(databaseHelper.getAllUser());
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
userRecyclerAdapterSavedUsers.notifyDataSetChanged();
}
}.execute();
}
#Override
public void onClick(View view, int position) {
}
}
When I clicked on the List Item it crashed and the error was caused by Toast. As I remove the toast the Error goes because of using a try catch item not clicked.
Here is the image of Error.
After Removing try catch It again shows error but this time the error is shown on AlertDialog. Builder. Here is the image of error without try catch.
Image after removing try and catch
ERROR BEFORE REMOVING TOAST OVER ON CLICK
Image after adding toast logcat Error
Image After Adding Toast
The error is now on users list activity
Image after eidting of code
The actual data in list when removing the click listener
Actual data in list by removing the click listener
Here is my recycler layout file
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
card_view:cardCornerRadius="4dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/Indigo"
android:orientation="vertical"
android:padding="16dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<android.support.v7.widget.AppCompatTextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="2"
android:text="User ID"
android:textColor="#color/colorTextHint" />
<android.support.v7.widget.AppCompatTextView
android:id="#+id/textViewID"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="User ID"
android:textColor="#android:color/darker_gray" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:orientation="horizontal">
<android.support.v7.widget.AppCompatTextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="2"
android:text="Name"
android:textColor="#color/colorTextHint" />
<android.support.v7.widget.AppCompatTextView
android:id="#+id/textViewName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Name"
android:textColor="#android:color/darker_gray" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:orientation="horizontal">
<android.support.v7.widget.AppCompatTextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="2"
android:text="#string/hint_password"
android:textColor="#color/colorTextHint" />
<android.support.v7.widget.AppCompatTextView
android:id="#+id/textViewPassword"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="#string/hint_password"
android:textColor="#android:color/darker_gray" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:orientation="horizontal">
<android.support.v7.widget.AppCompatTextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="2"
android:text="Role"
android:textColor="#color/colorTextHint" />
<android.support.v7.widget.AppCompatTextView
android:id="#+id/textViewRole"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Role"
android:textColor="#android:color/darker_gray" />
</LinearLayout>
</LinearLayout>
Here is the Image of Logcat
Logcat Image at Updating Data
Here is the IMEIRecord Save activity Adapter like user record..
public class IMEIRecyclerAdapter extends RecyclerView.Adapter<IMEIRecyclerAdapter.ImeiViewHolder> {
private List<User> ListImei;
Context mContext;
ItemClickListenerLongPressed itemClickListenerLongPressed;
View itemView;
public IMEIRecyclerAdapter(List<User> ListImei) {
this.ListImei = ListImei;
}
#Override
public ImeiViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.item_user_recycler_imei, parent, false);
return new ImeiViewHolder(itemView);
}
#Override
public void onBindViewHolder(ImeiViewHolder holder, int position) {
final User user= ListImei.get(position);
holder.textViewImeiId.setText(ListImei.get(position).getImeiid());
holder.textViewImeiNo.setText(ListImei.get(position).getImei());
}
public void setItemClickListenerLongPressed(ItemClickListenerLongPressed itemClickListenerLongPressed) {
this.itemClickListenerLongPressed = itemClickListenerLongPressed;
}
#Override
public int getItemCount() {
Log.v(UsersRecyclerAdapter.class.getSimpleName(),""+ListImei.size());
return ListImei.size();
}
public void displayingAlertDialogimei() {
final User user= new User();
//displaying alert dialog box
AlertDialog.Builder builder = new AlertDialog.Builder(itemView.getContext());
builder.setTitle("Choose Option");
builder.setMessage("Update or Delete?");
builder.setPositiveButton("Update", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//go to update activity
goToUpdateActivity(user.getUserid());
dialog.cancel();
}
});
builder.setNeutralButton("Delete", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//go to update activity
dialog.cancel();
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
AlertDialog alert11 = builder.create();
alert11.show();
}
private void goToUpdateActivity(String userid) {
Intent goToUpdate = new Intent(mContext, RoughUser.class);
goToUpdate.putExtra("USER_ID", userid);
mContext.startActivity(goToUpdate);
}
public class ImeiViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
public AppCompatTextView textViewImeiId;
public AppCompatTextView textViewImeiNo;
LinearLayout layout;
public ImeiViewHolder(View view) {
super(view);
textViewImeiId = (AppCompatTextView) view.findViewById(R.id.textViewImeiId);
textViewImeiNo = (AppCompatTextView) view.findViewById(R.id.textViewImeiNo);
layout = (LinearLayout) view.findViewById(R.id.list_view_imei);
layout.setOnClickListener(this);
}
#Override
public void onClick(View v) {
displayingAlertDialogimei();
}
}
}
first add id to your parent LinearLayout as, android:id="#+id/list_view"
and then update adapter class
public class UserRecyclerAdapterSavedUsers extends RecyclerView.Adapter<UserRecyclerAdapterSavedUsers.UserViewHolder> {
private List<User> listUsers;
Context mContext;
ItemClickListenerLongPressed itemClickListenerLongPressed;
View itemView;
public UserRecyclerAdapterSavedUsers(List<User> listUsers) {
this.listUsers = listUsers;
}
#Override
public UserViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.item_user_recycler_second, parent, false);
return new UserViewHolder(itemView);
}
#Override
public void onBindViewHolder(UserViewHolder holder, int position) {
holder.textViewID.setText(listUsers.get(position).getUserid());
holder.textViewName.setText(listUsers.get(position).getName());
holder.textViewPassword.setText(listUsers.get(position).getPassword());
holder.textViewRole.setText(listUsers.get(position).getRole());
}
public void setItemClickListenerLongPressed(ItemClickListenerLongPressed itemClickListenerLongPressed){
this.itemClickListenerLongPressed=itemClickListenerLongPressed;
}
#Override
public int getItemCount() {
return listUsers.size();
}
private void displayingAlertDialog() {
//displaying alert dialog box
AlertDialog.Builder builder = new AlertDialog.Builder(itemView.getContext());
builder.setMessage("your toast message here...");
builder.setCancelable(true);
builder.setPositiveButton(
"Ok",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert11 = builder.create();
alert11.show();
}
/**
* ViewHolder class
*/
public class UserViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
//public AppCompatTextView ID;
public AppCompatTextView textViewID;
public AppCompatTextView textViewName;
public AppCompatTextView textViewPassword;
public AppCompatTextView textViewRole;
LinearLayout layout;
public UserViewHolder(View view) {
super(view);
textViewID = (AppCompatTextView) view.findViewById(R.id.textViewID);
textViewName = (AppCompatTextView) view.findViewById(R.id.textViewName);
textViewPassword = (AppCompatTextView) view.findViewById(R.id.textViewPassword);
textViewRole = (AppCompatTextView) view.findViewById(R.id.textViewRole);
layout = view.findViewById(R.id.list_view);
layout.setOnClickListener(this);
}
#Override
public void onClick(View v) {
displayingAlertDialog();
}
}
You have not declare mContext in your adapter class.
In Adapter class constructor may change like this.
public UserRecyclerAdapterSavedUsers(List<User> listUsers,Context context) {
this.mContext= context;
this.listUsers1 = listUsers;
user= new User();
}
and Recycle view Activity class you have to change
UserRecyclerAdapterSavedUsers myAdapter = new RecyclerViewAdapter(yourList,this);
Use the Recyclerview Item click like this click here
and then you can access the interface in your activity or fragment and then you can add whatever you need.
giving toast and populating AlertDialog inside the Adapteris not the proper way of coding

How to use button and recycleView together

I have a recycleView (see picture). You see there are 2 buttons too. Here's the layout file.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="80dp"
android:background="#color/white">
<de.hdodenhof.circleimageview.CircleImageView
android:layout_marginLeft="10dp"
android:id="#+id/main_picture"
android:layout_width="45dp"
android:layout_height="50dp"
android:src="#drawable/pfl_img"
android:layout_centerVertical="true"
android:layout_alignParentStart="true" />
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_toRightOf="#id/main_picture"
android:layout_marginRight="5dp"
android:layout_marginLeft="10dp"
android:id="#+id/relativeLayout2">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Edem Palonik"
android:textSize="17sp"
android:id="#+id/textName"
android:textColor="#color/black"
android:layout_above="#+id/textDescription"
android:layout_alignParentStart="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Profession and ..."
android:textColor="#color/black"
android:textSize="17sp"
android:id="#+id/textDescription"
android:layout_centerVertical="true"
android:layout_alignParentStart="true" />
<ImageView
android:layout_width="20dp"
android:layout_height="18dp"
android:layout_marginTop="2dp"
android:layout_below="#+id/textDescription"
android:id="#+id/historyIcon"
android:layout_alignParentStart="true" />
<TextView
android:layout_marginLeft="5dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/date"
android:textSize="14sp"
android:text="17/12/2017/13:46"
android:layout_marginTop="2dp"
android:layout_below="#+id/textDescription"
android:layout_toEndOf="#+id/historyIcon" />
</RelativeLayout>
<Button
android:id="#+id/call_button"
android:layout_width="32dp"
android:layout_height="32dp"
android:layout_marginRight="10dp"
android:background="#drawable/call_img"
android:layout_centerVertical="true"
android:layout_toStartOf="#+id/sms_button" />
<Button
android:id="#+id/sms_button"
android:layout_width="37dp"
android:layout_height="32dp"
android:background="#drawable/sms_img"
android:layout_alignTop="#+id/call_button"
android:layout_alignParentEnd="true" />
<View
android:layout_width="match_parent"
android:layout_height="0.8dp"
android:layout_alignParentBottom="true"
android:background="#color/gray" />
I know, I can use recyclerViewItemCLickListener, but I wanna click on last 2 buttons separately, so what do I need to do?
So I wanna click on last buttons separately, without clicking all line, I want only last buttons to be clickable.
Here's the java code.
public class ConnectionsFragment extends Fragment {
private View mainView;
private RecyclerView recyclerView;
private List<Connections_item> list;
private Button call, sms;
public ConnectionsFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
mainView = inflater.inflate(R.layout.connections_fragment, container, false);
recyclerView = (RecyclerView) mainView.findViewById(R.id.recycler_connection);
ConnectionsAdapter adapter = new ConnectionsAdapter(getActivity(), list);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
recyclerView.setAdapter(adapter);
init(mainView);
return mainView;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
list = new ArrayList<>();
list.add(new Connections_item(R.drawable.pfl_img, "Anun Azganun1", "Inch vor text", R.drawable.missed, "23/11/1998 00:00"));
list.add(new Connections_item(R.drawable.pfl_img, "Anun Azganun2", "Inch vor text", R.drawable.callagain, "24/11/1998 01:00"));
list.add(new Connections_item(R.drawable.pfl_img, "Anun Azganun3", "Inch vor text", R.drawable.missed, "25/11/1998 02:00"));
public void init(View v) {
call = (Button) v.findViewById(R.id.call_button);
sms = (Button) v.findViewById(R.id.sms_button);
// call.setOnClickListener(new View.OnClickListener() {
// #Override
// public void onClick(View view) {
// Toast.makeText(getActivity(), "Whom you wanna call?", Toast.LENGTH_SHORT).show();
// }
// });
// sms.setOnClickListener(new View.OnClickListener() {
// #Override
// public void onClick(View view) {
// Toast.makeText(getActivity(), "Whom you wanna send sms?", Toast.LENGTH_SHORT).show();
// }
// });
}
}
Here's the adapter code.
public class ConnectionsAdapter extends RecyclerView.Adapter<ConnectionsAdapter.MyViewHolder> {
Context context;
List<Connections_item> list = new ArrayList<>();
public ConnectionsAdapter(Context context, List<Connections_item> list) {
this.context = context;
this.list = list;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v;
v = LayoutInflater.from(context).inflate(R.layout.connections_view_item, parent, false);
MyViewHolder holder = new MyViewHolder(v);
return holder;
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
holder.mainImage.setImageResource(list.get(position).getMainImage());
holder.fullName.setText(list.get(position).getFullName());
holder.description.setText(list.get(position).getDescription());
holder.historyImage.setImageResource(list.get(position).getHistoryIcon());
holder.date.setText(list.get(position).getDate());
}
#Override
public int getItemCount() {
return list.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
ImageView mainImage, historyImage;
TextView fullName, description, date;
Button call, sms;
public MyViewHolder(View v) {
super(v);
mainImage = (ImageView) v.findViewById(R.id.main_picture);
historyImage = (ImageView) v.findViewById(R.id.historyIcon);
fullName = (TextView) v.findViewById(R.id.textName);
description = (TextView) v.findViewById(R.id.textDescription);
date = (TextView) v.findViewById(R.id.date);
call = (Button) v.findViewById(R.id.call_button);
sms = (Button) v.findViewById(R.id.sms_button);
}
}
}
Using interface you can achieve this
public class TestAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
Context mContext;
ArrayList<Data> mData;
OnButtonClickListeners onButtonClickListeners;
public TestAdapter(Context mContext, ArrayList<String> mData) {
this.mContext = mContext;
this.mData = mData;
}
public void setOnButtonClickListeners(OnButtonClickListeners listener){
this.onButtonClickListeners = listener;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
MyViewHolder vh;
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_layout, parent, false);
vh = new MyViewHolder(v);
return vh;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
//Bind holder here
}
#Override
public int getItemCount() {
return mData.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
#Bind(R.id.call_button)
Button btnCall;
#Bind(R.id.sms_button)
Button btnSms;
public MyViewHolder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
btnCall.setOnClickListener(this);
btnSms.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if(this.onButtonClickListeners!=null){
switch (v.getId()) {
case R.id.call_button:
onButtonClickListeners.onCallClick(getAdapterPosition());
break;
case R.id.sms_button:
onButtonClickListeners.onSmsClick(getAdapterPosition());
break;
}
}
}
}
public interface OnButtonClickListeners{
void onCallClick(int position);
void onSmsClick(int position);
}
}
Then After you can use the call to this interface from Activity and Fragment like below
private void setUpRecyclerView(){
mAdapter = new ProfileAdapter(mContext,new ArrayList<String>());
lm = new LinearLayoutManager(getActivity());
rvFeeds.setLayoutManager(lm);
rvFeeds.setAdapter(mAdapter);
mAdapter.setOnButtonClickListeners(new OnButtonClickListeners() {
#Override
public void onCallClick(int position) {
//To do your code here
}
#Override
public void onSmsClick(int position) {
//To do your code here
}
})
}
As adapter holds the recyclerView item and buttons are in the item
so all code related to button will be in the adapter only.
In adapter modify the code :
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
holder.mainImage.setImageResource(list.get(position).getMainImage());
holder.fullName.setText(list.get(position).getFullName());
holder.description.setText(list.get(position).getDescription());
holder.historyImage.setImageResource(list.get(position).getHistoryIcon());
holder.date.setText(list.get(position).getDate());
holder.call.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(getActivity(), "Whom you wanna call?", Toast.LENGTH_SHORT).show();
}
});
holder.sms.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(getActivity(), "Whom you wanna send sms?", }
});
}
In java file just remove call and sms button initialization and listners.
You can try to implement onClickListener to the buttons when you are creating the view in the ViewHolder for the recycler view. Then pass an interface with two methods for two buttons and implement the interface in where ever you require.
Like the example:
public class MyViewHolder extends RecyclerView.ViewHolder {
public MyViewHolder(View itemView, ButtonClickListener listner) {
super(itemView);
Button b1 = itemView.findViewById(...);
Button b2 = itemView.findViewById(...);
b1.setOnClickListener(view -> listener.onButton1Click());
b2.setOnClickListener(view -> listener.onButton2Click());
}
}
And now the interface
public interface ButtonClickListener {
void onButton1Click();
void onButton2Click();
}
Otherwise, if you are accustomed with bus you can use instead of using interface. It will make the code much cleaner.

Android Spinner Inside RecyclerView Get Current View When Selected

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

SherlockfragmentActivity and sherlockListFragment

I'm trying to make a drobdown navigation menu so i can move between my pages using SherlockFragmentActivity and SerlockListFragment
but every time i'm starting my app it's give this following error:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.download.manager/com.download.manager.Main}: java.lang.RuntimeException: Your content must have a ListView whose id attribute is android.R.id.list
this is SherlockFragmentActivity class
public class Main extends SherlockFragmentActivity implements OnNavigationListener{
private static final String KEY_MODELS="models";
private static final String KEY_POSITION="position";
private static final String[] labels= { "All", "Downloads","Completed","Later" };
private CharSequence[] models=new CharSequence[4];
private DownloadList frag=null;
private int lastPosition=-1;
ActionBar act;
ViewPager myviewpager;
int mSelectedPageIndex=1;
DownloadService downloadservice;
Intent serviceIntent ;
#Override
public void onCreate(Bundle state) {
super.onCreate(state);
frag=(DownloadList)getSupportFragmentManager().findFragmentById(android.R.id.content);
if (frag==null) {
frag=new DownloadList();
getSupportFragmentManager().beginTransaction().add(android.R.id.content, frag).commit();
}
if (state != null) {
models=state.getCharSequenceArray(KEY_MODELS);
}
if (downloadservice==null)
downloadservice= new DownloadService();
ArrayAdapter<String> nav=null;
act=getSupportActionBar();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH)
{
nav= new ArrayAdapter<String>( act.getThemedContext(),android.R.layout.simple_spinner_item,labels);
}
else
{
nav=new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,labels);
}
nav.setDropDownViewResource(android.R.layout.simple_list_item_1);
act.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
act.setDisplayShowTitleEnabled(false);
act.setHomeButtonEnabled(false);
act.setListNavigationCallbacks(nav, this);
if (state != null) {
act.setSelectedNavigationItem(state.getInt(KEY_POSITION));
}
serviceIntent= new Intent(Main.this,downloadservice.getClass());
if (startService(serviceIntent)==null)
startService(serviceIntent);
act.setTitle("");
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater infalter = getSupportMenuInflater();
infalter.inflate(R.menu.mymenu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId()==R.id.sub1)
{
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("Downlaod New File");
alert.setMessage("Enter URL");
final EditText input = new EditText(this);
alert.setView(input);
input.setText("http://205.196.123.184/ddpha7c5b8lg/616c36j0d1xbztf /Lecture+ppt+Ch2.ppt");
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String value = input.getText().toString();
Log.d("value",value);
}
});
alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
}
});
alert.show();
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
}
#Override
public boolean onNavigationItemSelected(int itemPosition, long itemId) {
lastPosition=itemPosition;
return false;
}
this is SherlockListFragment class
public class DownloadList extends SherlockListFragment {
int index=0;
Button downloadButton;
Button pauseButton;
Button resumeButton;
TextView textLink;
TextView progressbar;
DownloadService downloadservice= new DownloadService();
MyAdapter listadapter;
Intent serviceIntent ;
String state;
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
getActivity().setContentView(R.layout.downloadlist);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup
container,BundlesavedInstanceState) {
View rootView = inflater.inflate(R.layout.downloadlist, container, false);
return rootView;
}
int getIndex()
{
return index;
}
public class MyAdapter extends ArrayAdapter<NewDownload>
{
private final List<NewDownload> list;
private final Activity context;
Thread t;
public MyAdapter(Context context,List<NewDownload> list) {
super(context, R.layout.list_item, list);
this.context = (Activity) context;
this.list = list;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) getActivity().
getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View row = inflater.inflate(R.layout.list_item, null);
pauseButton = (Button) row.findViewById(R.id.btn1);
resumeButton = (Button) row.findViewById(R.id.btn2);
textLink = (TextView) row.findViewById(R.id.tv1);
progressbar = (TextView) row.findViewById(R.id.progressBar1);
textLink.setText(downloadservice.
downloads.get(position).getName());
progressbar.setBottom(downloadservice.
downloads.get(position).getDownloadedSize());
progressbar.setTop(downloadservice.
downloads.get(position).getTotalSize());
final int p = position;
final NewDownload r = list.get(p);
if (r.state=="downloading")
{
progressbar.setText("DownLoading...");
pauseButton.setEnabled(true);
resumeButton.setEnabled(false);
}
else if (r.state=="pause")
{
pauseButton.setEnabled(false);
resumeButton.setEnabled(true);
progressbar.setText(r.state);
}
pauseButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
downloadservice.pause(p);
setListAdapter(listadapter );
}
});
resumeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (getActivity().startService(serviceIntent)==null)
getActivity().startService(serviceIntent);
downloadservice.resume(p);
setListAdapter(listadapter );
}
});
return row;
}
}
this is downloadlist.xml
<ListView
android:id="#+id/list" xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
this is list_item.XML
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/tv1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="File Name" />
<TextView
android:id="#+id/progressBar1"
android:layout_width="306dp"
android:layout_height="wrap_content"
/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<Button
android:id="#+id/btn1"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="34dp"
android:layout_gravity="center_horizontal"
android:text="Pause" />
<Button
android:id="#+id/btn2"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="34dp"
android:layout_gravity="right"
android:text="Resume" />
</LinearLayout>
</LinearLayout>
So any one can tell me where is my mistake ?
This error:
Your content must have a ListView whose id attribute is android.R.id.list
means you must use:
<ListView
android:id="#android:id/list"
...
in download.xml.

Categories