I have a list of music with a favorite icon, when the user clicks on this icon I want to change the color of the icon as the action to enjoy.
In this framework I have an Activity, a listView in this Activity, an Adapter class that does the inflate of the layout_list.html.xml and it is in this layout that ImageView is ic_favorite_border, that when the user clicks the ImageView (only in the same ImageView and not the whole line because the whole line has another action) I will change the image to R.drawable.ic_favorite.
As the code now, when I click on the ImageView gives a null pointer exception error because it does not resemble the layout component with the Activity because it has another layout.
I'm trying to perform this action within actibity, I do not know if it should be there or in the adapter:
MocidadeActivity.class
public class MocidadeActivity extends AppCompatActivity {
//ATRIBUTOS
private ImageView imLike;
private ListView listView;
private ArrayList<Hinos> arrayList;
private ArrayAdapter adapter;
private DatabaseReference reference;
private ValueEventListener valueEventListener;
private Boolean acaoCurtir;
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mocidade);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
//DEFININDO A TRANSIÇÃO DE ENTRADA DA ACTIVITY
if (Build.VERSION.SDK_INT >= 22){
Slide s = new Slide();
s.setDuration(1000);
getWindow().setEnterTransition(s);
}
//Tentando instanciar o imageview
imLike = findViewById(R.id.img_like_lista_hinos);
//Montando a lista de exibição dos hinos
listView = (ListView) findViewById(R.id.lv_hinos);
arrayList = new ArrayList<>();
adapter = new HinosAdapter(MocidadeActivity.this, arrayList);
listView.setAdapter(adapter);
//*************** FIREBASE INICIO ************************/
reference = ConfiguracaoFirebase.getFirebaseReference().child("MOCIDADE")
.child("HINOS");
reference.orderByKey();
valueEventListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
arrayList.clear();
//Listando os hinos
for (DataSnapshot data: dataSnapshot.getChildren()){
Hinos hinos = data.getValue(Hinos.class);
arrayList.add(hinos);
}
adapter.notifyDataSetChanged();
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
};
//*************** FIREBASE FIM ************************/
/**************** COMPONENTES DA TELA ********************/
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, final int position, long l) {
if (acaoCurtir == false){
try{
Hinos hinos = arrayList.get(position);
//salvando no shared para ser utilizado depois
SharedPreferencias preferences = new SharedPreferencias(MocidadeActivity.this);
preferences.salvarHinoPreferences(hinos.getNumero(), hinos.getTitulo(), hinos.getCantor(), hinos.getUrl());
Intent letraA = new Intent(MocidadeActivity.this, LetraHinosActivity.class);
startActivity(letraA);
} catch (Exception e){
e.printStackTrace();
}
}
}
});
}
/******************************* METODOS *********************************/
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_mocidade, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.mn_add_hino:
if (Atalhos.verificarRegente(getApplicationContext()) == true) {
AdicionarHinoFragment hinoFragment = new AdicionarHinoFragment();
hinoFragment.show(MocidadeActivity.this.getSupportFragmentManager(), "Alert Adicionar Hino");
} else {
Atalhos.acessoNegado(MocidadeActivity.this);
}
break;
}
return super.onOptionsItemSelected(item);
}
public void favoritarHino(View view){
Log.d("CURTIR", "Acessou esse metodo");
int pos = listView.getPositionForView(view);
acaoCurtir = true;
Toast.makeText(this, "Clicou no curtir", Toast.LENGTH_SHORT).show();
imLike.setImageResource(R.drawable.ic_favorite);
}
@Override
protected void onStart() {
super.onStart();
reference.addValueEventListener(valueEventListener);
acaoCurtir = false;
}
@Override
protected void onStop() {
super.onStop();
reference.removeEventListener(valueEventListener);
acaoCurtir = false;
}
HinosAdapter.class
public class HinosAdapter extends ArrayAdapter<Hinos>{
//ATRIBUTOS
Context context;
private ArrayList<Hinos> arrayList;
public HinosAdapter(@NonNull Context c, ArrayList<Hinos> objects) {
super(c, 0, objects);
this.context = c;
this.arrayList = objects;
}
@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
View view = null;
//Validando e criando a lista de hinos
if (arrayList != null){
LayoutInflater inflater = (LayoutInflater) context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
//montando a view a partir do XML
view = inflater.inflate(R.layout.lista_hinos, parent, false);
//Recuperando os elementos para exibição
TextView tvNumero = view.findViewById(R.id.tv_num_hino);
TextView tvTitulo = view.findViewById(R.id.tv_titulo_hino);
TextView tvCantor = view.findViewById(R.id.tv_cantor_hino);
final ImageView imLike = view.findViewById(R.id.img_like_lista_hinos);
Hinos hinos = arrayList.get(position);
tvNumero.setText(hinos.getNumero());
tvCantor.setText(hinos.getCantor());
tvTitulo.setText(hinos.getTitulo());
imLike.setImageResource(R.drawable.ic_favorite_border);
/*imLike.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
}
});*/
}
return view;
}
}
MocidadeActivity.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="@style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="@style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<ListView
android:id="@+id/lv_hinos"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
children_list.xml
<?xml version="1.0" encoding="utf-8"?>
<TextView
android:id="@+id/tv_num_hino"
android:layout_width="50dp"
android:layout_height="wrap_content"
android:text="33"
android:textSize="@dimen/numero_hino"
android:layout_marginLeft="16dp"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:layout_marginTop="6dp" />
<TextView
android:id="@+id/tv_titulo_hino"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Extraordinário"
android:textSize="@dimen/nome_hino"
app:layout_constraintTop_toTopOf="parent"
android:layout_marginTop="6dp"
app:layout_constraintLeft_toRightOf="@+id/tv_num_hino"
android:layout_marginLeft="24dp" />
<TextView
android:id="@+id/tv_cantor_hino"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Jota A"
android:textSize="@dimen/cantor"
android:textStyle="italic"
android:layout_marginTop="8dp"
app:layout_constraintTop_toBottomOf="@+id/tv_titulo_hino"
app:layout_constraintLeft_toRightOf="@+id/tv_num_hino"
android:layout_marginLeft="24dp" />
<ImageView
android:id="@+id/img_like_lista_hinos"
android:layout_width="25dp"
android:layout_height="25dp"
android:layout_marginRight="36dp"
android:layout_marginTop="24dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:onClick="favoritarHino"/>
</android.support.constraint.ConstraintLayout>