I am trying to make a music application. So far I have been able to list the songs from a user's device and display them in a list. However, if a song is clicked to open the PlayerActivity, the activity crashes. Could someone assist me in playing the selected song from the song list? Improvements on the code would be highly appreciated.
The code below, MediaGalleryActivity.java gets the songs and passes them to specific intents:
package com.newton.hooked;
import android.content.ContentUris;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;
import com.google.android.material.tabs.TabLayout;
import androidx.viewpager.widget.ViewPager;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Parcel;
import android.os.Parcelable;
import android.provider.MediaStore;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import com.newton.hooked.ui.main.SectionsPagerAdapter;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class MediaGalleryActivity extends AppCompatActivity {
public static final String SONGS_KEY = "SONGS";
public static final String ARTISTS_KEY = "ARTISTS";
public static final String ALBUMS_KEY = "ALBUMS";
ArrayList<String> songList = new ArrayList<>();
ArrayList<String> artistList = new ArrayList<>();
ArrayList<String> albumList = new ArrayList<>();
String[] song = new String[]{
MediaStore.Audio.Media._ID,
MediaStore.Audio.Media.TITLE,
MediaStore.Audio.Media.ARTIST,
MediaStore.Audio.Media.ALBUM,
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_media_gallery);
SectionsPagerAdapter sectionsPagerAdapter = new SectionsPagerAdapter(this, getSupportFragmentManager());
ViewPager viewPager = findViewById(R.id.view_pager);
viewPager.setAdapter(sectionsPagerAdapter);
TabLayout tabs = findViewById(R.id.tabs);
int defaultValue = 0;
int page = getIntent().getIntExtra("Tab ID",defaultValue);
viewPager.setCurrentItem(page);
tabs.setupWithViewPager(viewPager);
Cursor audioCursor = getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,song,null,null,null);
ArrayList<AudioModel> audios = new ArrayList<>();
if(audioCursor != null){
if(audioCursor.moveToFirst()){
do{
int idColumn = audioCursor.getColumnIndexOrThrow(MediaStore.Audio.Media._ID);
int titleColumn = audioCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.TITLE);
int artistColumn = audioCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ARTIST);
int albumColumn = audioCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM);
String thisTitle = audioCursor.getString(titleColumn);
String thisArtist = audioCursor.getString(artistColumn);
String thisAlbum = audioCursor.getString(albumColumn);
songList.add(thisTitle);
artistList.add(thisArtist);
albumList.add(thisAlbum);
} while (audioCursor.moveToNext());
}
}
audioCursor.close();
if(!songList.isEmpty()){
getIntent().putExtra(SONGS_KEY, songList);
} else {
getIntent().putExtra(SONGS_KEY,"No songs found");
}
if (!artistList.isEmpty()){
getIntent().putExtra(ARTISTS_KEY,artistList);
} else {
getIntent().putExtra(ARTISTS_KEY,"No artists found");
}
if (!albumList.isEmpty()){
getIntent().putExtra(ALBUMS_KEY,albumList);
} else {
getIntent().putExtra(ALBUMS_KEY,"No albums found");
}
}
}
The code below, SongsTab.java, gets songList extra and displays the items in a ListView
package com.newton.hooked.ui.main;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import androidx.fragment.app.Fragment;
import com.newton.hooked.MediaGalleryActivity;
import com.newton.hooked.PlayerActivity;
import com.newton.hooked.R;
import java.util.ArrayList;
import java.util.Objects;
public class SongsTab extends Fragment {
public static final String SONG_POSITION = "POSITION";
private ListView songList;
#Override
public View onCreateView(
LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.songs_tab, container, false);
songList = view.findViewById(R.id.song_list);
TextView message = view.findViewById(R.id.song_message);
Intent intent = Objects.requireNonNull(getActivity()).getIntent();
final ArrayList<String> songs = intent.getStringArrayListExtra(MediaGalleryActivity.SONGS_KEY);
if (!songs.isEmpty()){
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<>(Objects.requireNonNull(getContext()),R.layout.display_layout_2,R.id.txt_name,songs);
songList.setAdapter(arrayAdapter);
songList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
startActivity(new Intent(getActivity(), PlayerActivity.class)
.putExtra("SONGLIST",songs)
.putExtra(SONG_POSITION,position)
.putExtra("SONG_ID",id));
}
});
} else {
songList.setVisibility(View.INVISIBLE);
message.setVisibility(View.VISIBLE);
}
return view;
}
}
The code below, PlayerActivity.java, is supposed to play a selected song:
package com.newton.hooked;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.ContentUris;
import android.content.Intent;
import android.graphics.PorterDuff;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.SeekBar;
import android.widget.TextView;
import com.newton.hooked.ui.main.SongsTab;
import java.io.File;
import java.util.ArrayList;
public class PlayerActivity extends AppCompatActivity {
Button btn_next, btn_previous, btn_pause;
TextView songTextLabel;
SeekBar songSeekBar;
String sName;
MediaPlayer myMediaPlayer = new MediaPlayer();
int position = 0;
ArrayList<String> mySongs = new ArrayList<>();
Thread updateSeekBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_player);
btn_next = findViewById(R.id.next);
btn_pause = findViewById(R.id.pause);
btn_previous = findViewById(R.id.previous);
songTextLabel = findViewById(R.id.song_label);
songSeekBar = findViewById(R.id.seek_bar);
getSupportActionBar().setTitle("Now Playing...");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
updateSeekBar = new Thread(){
#Override
public void run() {
int totalDuration = myMediaPlayer.getDuration();
int currentPosition = 0;
while (currentPosition<totalDuration){
try {
sleep(500);
currentPosition= myMediaPlayer.getCurrentPosition();
songSeekBar.setProgress(currentPosition);
} catch (InterruptedException e){
e.printStackTrace();
}
}
}
};
if(myMediaPlayer!=null){
myMediaPlayer.stop();
myMediaPlayer.release();
}
Intent i = getIntent();
mySongs = i.getStringArrayListExtra("SONGLIST");
position = i.getIntExtra(SongsTab.SONG_POSITION, 0);
String songName= i.getStringExtra("songName");
long songID = i.getIntExtra("SONG_ID",0);
songTextLabel.setText(songName);
songTextLabel.setSelected(true);
Uri u = ContentUris.withAppendedId(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,songID);
myMediaPlayer = MediaPlayer.create(PlayerActivity.this,u);
myMediaPlayer.start();
songSeekBar.setMax(myMediaPlayer.getDuration());
updateSeekBar.start();
songSeekBar.getProgressDrawable().setColorFilter(getResources().getColor(R.color.black), PorterDuff.Mode.MULTIPLY);
songSeekBar.getThumb().setColorFilter(getResources().getColor(R.color.white), PorterDuff.Mode.SRC_IN);
songSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
myMediaPlayer.seekTo(seekBar.getProgress());
}
});
btn_pause.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
songSeekBar.setMax(myMediaPlayer.getDuration());
if(myMediaPlayer.isPlaying()){
btn_pause.setBackgroundResource(R.drawable.icon_play);
myMediaPlayer.pause();
} else {
btn_pause.setBackgroundResource(R.drawable.icon_pause);
myMediaPlayer.start();
}
}
});
btn_next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
myMediaPlayer.stop();
myMediaPlayer.release();
position = ((position +1)%mySongs.size());
Uri u = Uri.parse(mySongs.get(position).toString());
myMediaPlayer = MediaPlayer.create(getApplicationContext(), u);
sName = mySongs.get(position).toString();
songTextLabel.setText(sName);
myMediaPlayer.start();
}
});
btn_previous.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
myMediaPlayer.stop();
myMediaPlayer.release();
position = ((position -1)%mySongs.size()-1);
Uri u = Uri.parse(mySongs.get(position).toString());
myMediaPlayer = MediaPlayer.create(getApplicationContext(), u);
sName = mySongs.get(position).toString();
songTextLabel.setText(sName);
myMediaPlayer.start();
}
});
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
if(item.getItemId() == android.R.id.home){
onBackPressed();
}
return super.onOptionsItemSelected(item);
}
}
When I run the app, I encounter the error below:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.newton.hooked, PID: 2396
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.newton.hooked/com.newton.hooked.PlayerActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.media.MediaPlayer.start()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2505)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2577)
at android.app.ActivityThread.access$1000(ActivityThread.java:164)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1462)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:160)
at android.app.ActivityThread.main(ActivityThread.java:5541)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:964)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:759)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.media.MediaPlayer.start()' on a null object reference
at com.newton.hooked.PlayerActivity.onCreate(PlayerActivity.java:90)
at android.app.Activity.performCreate(Activity.java:6093)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2458)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2577)
at android.app.ActivityThread.access$1000(ActivityThread.java:164)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1462)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:160)
at android.app.ActivityThread.main(ActivityThread.java:5541)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:964)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:759)
Assistance would be much appreciated.
Related
The problem is that the progress bar only starts when the data has been processed. And I want it to run before processing the data, right after pressing the search button. What am I doing wrong?
whole fragment code
package com.app.comicslibrary.MenuFragments;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.os.Bundle;
import androidx.annotation.RequiresApi;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;
import android.os.StrictMode;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.app.comicslibrary.Jsoup.ParseBookInfo;
import com.app.comicslibrary.MainActivity;
import com.app.comicslibrary.MenuFragments.ListActions.AddPosition;
import com.app.comicslibrary.MenuFragments.ListActions.ModelCollectView;
import com.app.comicslibrary.MenuFragments.SearchMenu.SearchListAdapter;
import com.app.comicslibrary.R;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
public class SecondFragment extends Fragment {
ArrayList<ModelCollectView> listParseComics;
ArrayList<ModelCollectView> selectedComics;
SearchListAdapter searchArrayAdapter;
private ProgressBar loadingBar;
private Context context;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_second, container, false);
EditText searchLine = (EditText) view.findViewById(R.id.searchLine);
Button searchButton = (Button) view.findViewById(R.id.searchButton);
ListView searchList = (ListView) view.findViewById(R.id.listViewSearch);
Button saveSearchButton = (Button) view.findViewById(R.id.buttonSaveSearch);
loadingBar = (ProgressBar)view.findViewById(R.id.loadingProgressBar);
listParseComics = new ArrayList<>();
//search and display result list
searchButton.setOnClickListener(new View.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.N)
#Override
public void onClick(View v){
String textSearch = searchLine.getText().toString();
if(textSearch.isEmpty() || textSearch.length() <= 3){
Toast.makeText(getContext(), "Введите более 3 символов в строку поиска", Toast.LENGTH_SHORT).show();
return;
}
setLoadingProgressBarVisible();
ParseBookInfo getInfo = new ParseBookInfo(getContext());
try{
int SDK_INT = android.os.Build.VERSION.SDK_INT;
if (SDK_INT > 8)
{
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
listParseComics = getInfo.searchComicsInfo(textSearch, 1);//change numberpage later
searchArrayAdapter = new SearchListAdapter(container.getContext(), listParseComics);
searchList.setAdapter(searchArrayAdapter);
}
}catch(IOException e){
Log.d("PARSEERROR", "Search comics is fail");
}
}
});
//select position and call add menu
selectedComics = new ArrayList<>();
saveSearchButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(listParseComics == null || searchArrayAdapter == null){
Toast.makeText(getContext(), "Нет данных для добавления", Toast.LENGTH_SHORT).show();
return;
}
boolean []statusItems = searchArrayAdapter.getChecked();
Intent intent = new Intent(getActivity(), AddPosition.class);
for (int i = 0; i < statusItems.length; i++) {
if(statusItems[i]){
ModelCollectView selectedItem = listParseComics.get(i);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
selectedItem.getImage().compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] bytes = stream.toByteArray();
intent.putExtra("bytesImages" + i, bytes);
selectedItem.setImage(null);
selectedComics.add(selectedItem);
}
}
intent.putParcelableArrayListExtra("selectedItemsInSearch", selectedComics);
startActivity(intent);
}
});
return view;
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
this.context = context;
}
public void setLoadingProgressBarVisible(){
((MainActivity)context).runOnUiThread(new Runnable() {
public void run() {
Log.d("UI thread", "I am the UI thread");
loadingBar.setVisibility(View.VISIBLE);
}
});
}
}
The text of the log is displayed immediately, but the progress bar does not appear (function setLoadingProgressBarVisible())
I want to get total price in Activity from Price and Quantity in Adapter, it's mean like qty * price = total_price.
Here is my Adapter for handling the list of Items Activity:
package com.example.aulaherbalfinal.Adapter;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.example.aulaherbalfinal.Model.DataModel;
import com.example.aulaherbalfinal.R;
import java.text.NumberFormat;
import java.util.List;
import java.util.Locale;
public class AdapterDataPembelian extends RecyclerView.Adapter<AdapterDataPembelian.HolderDataPembelian>{
private Context ctx;
private List<DataModel> listDataPembelian;
private int count;
public AdapterDataPembelian(Context ctx, List<DataModel> listDataPembelian) {
this.ctx = ctx;
this.listDataPembelian = listDataPembelian;
}
#NonNull
#Override
public HolderDataPembelian onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View layout = LayoutInflater.from(parent.getContext()).inflate(R.layout.card_item_pembelian, parent, false);
HolderDataPembelian holder = new HolderDataPembelian(layout);
return holder;
}
#Override
public void onBindViewHolder(#NonNull HolderDataPembelian holder, int position) {
DataModel dm = listDataPembelian.get(position);
holder.tvId.setText(String.valueOf(dm.getId()));
holder.tvBarang.setText(dm.getBarang());
holder.tvStok.setText("Stok : "+String.valueOf(dm.getStok()));
holder.tvHarga.setText(formatRupiah(Double.parseDouble(String.valueOf(dm.getHarga()))));
holder.jmlBarang.setText(String.valueOf(dm.getQuantity()));
//holder.totalHarga.setText(String.valueOf(dm.getTotalHarga()));
Intent intent = new Intent("custom-message");
holder.btnRemove.setOnClickListener(v -> {
minusCartItem(holder,listDataPembelian.get(position));
});
holder.btnAdd.setOnClickListener(v -> {
plusCartItem(holder,listDataPembelian.get(position));
});
}
private void plusCartItem(HolderDataPembelian holder, DataModel dataModel) {
dataModel.setQuantity(dataModel.getQuantity()+1);
//dataModel.setTotalHarga(Integer.parseInt(String.valueOf(dataModel.getQuantity()*Double.parseDouble(String.valueOf(dataModel.getHarga())))));
holder.jmlBarang.setText(new StringBuilder().append(dataModel.getQuantity()));
}
private void minusCartItem(HolderDataPembelian holder, DataModel dataModel) {
if (dataModel.getQuantity() > 0){
dataModel.setQuantity(dataModel.getQuantity()-1);
//dataModel.setTotalHarga(Integer.parseInt(String.valueOf(dataModel.getQuantity()*Double.parseDouble(String.valueOf(dataModel.getHarga())))));
holder.jmlBarang.setText(new StringBuilder().append(dataModel.getQuantity()));
} else {
holder.jmlBarang.setText("0");
}
}
#Override
public int getItemCount() {
return listDataPembelian.size();
}
public class HolderDataPembelian extends RecyclerView.ViewHolder {
TextView tvId, tvBarang, tvStok, tvHarga;
Button btnAdd, btnRemove;
TextView jmlBarang, totalHarga;
public HolderDataPembelian(#NonNull View itemView) {
super(itemView);
tvId = itemView.findViewById(R.id.tv_id);
tvBarang = itemView.findViewById(R.id.tv_barang);
tvStok = itemView.findViewById(R.id.tv_stok);
tvHarga = itemView.findViewById(R.id.tv_harga);
btnAdd = itemView.findViewById(R.id.btn_add);
btnRemove = itemView.findViewById(R.id.btn_remove);
jmlBarang = itemView.findViewById(R.id.jml_barang);
totalHarga = itemView.findViewById(R.id.total_harga);
}
}
private String formatRupiah(Double number){
Locale localeID = new Locale("IND", "ID");
NumberFormat numberFormat = NumberFormat.getCurrencyInstance(localeID);
String formatRupiah = numberFormat.format(number);
String[] split = formatRupiah.split(",");
int length = split[0].length();
return split[0].substring(0,2)+". "+split[0].substring(2,length);
}
public int getTotalPrice(){
int totalPrice = 0;
for (int i=0 i<listDataPembelian.size(); i++){
}
}
}
And here is my Activity
package com.example.aulaherbalfinal.Activity;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.cardview.widget.CardView;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.example.aulaherbalfinal.API.APIRequestData;
import com.example.aulaherbalfinal.API.RetroServer;
import com.example.aulaherbalfinal.Adapter.AdapterDataPembelian;
import com.example.aulaherbalfinal.Model.DataModel;
import com.example.aulaherbalfinal.Model.ResponseModel;
import com.example.aulaherbalfinal.R;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import java.util.ArrayList;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class PembelianActivity extends AppCompatActivity {
private RecyclerView rvData;
private RecyclerView.Adapter adData;
private RecyclerView.LayoutManager lmData;
private List<DataModel> listDataPembelian = new ArrayList<>();
private SwipeRefreshLayout srlData;
private ProgressBar pbData;
private TextView totalHarga;
private EditText jmlBarang;
#SuppressLint("ClickableViewAccessibility")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pembelian);
rvData = findViewById(R.id.rv_data);
lmData = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
rvData.setLayoutManager(lmData);
srlData = findViewById(R.id.srl_data);
pbData = findViewById(R.id.pb_data);
totalHarga = findViewById(R.id.total_harga);
jmlBarang = findViewById(R.id.jml_barang);
totalHarga = findViewById(R.id.total_harga);
//retrieveData();
CardView cvTotal = findViewById(R.id.cv_total);
rvData.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_MOVE){
cvTotal.setVisibility(View.INVISIBLE);
}
if (event.getAction() == MotionEvent.ACTION_UP){
cvTotal.setVisibility(View.VISIBLE);
}
return false;
}
});
BottomNavigationView bottom_navigation = findViewById(R.id.bottom_navigation);
bottom_navigation.setItemIconTintList(null);
bottom_navigation.setSelectedItemId(R.id.navigation_pembelian);
ImageView profile =findViewById(R.id.profile);
profile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(PembelianActivity.this, ProfileActivity.class);
startActivity(intent);
finish();
}
});
bottom_navigation.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch ( (item.getItemId())){
case R.id.navigation_stok:
startActivity(new Intent(getApplicationContext(), MainActivity.class));
overridePendingTransition(0, 0);
return true;
case R.id.navigation_pembelian:
return true;
case R.id.navigation_penjualan:
startActivity(new Intent(getApplicationContext(), PenjualanActivity.class));
overridePendingTransition(0, 0);
return true;
}
return false;
}
});
srlData.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
srlData.setRefreshing(true);
retrieveData();
srlData.setRefreshing(false);
}
});
}
#Override
protected void onResume() {
super.onResume();
retrieveData();
}
public void retrieveData(){
pbData.setVisibility(View.VISIBLE);
APIRequestData ardData = RetroServer.konekRetrofit().create(APIRequestData.class);
Call<ResponseModel> tampildata = ardData.ardRetrieveData();
tampildata.enqueue(new Callback<ResponseModel>() {
#Override
public void onResponse(Call<ResponseModel> call, Response<ResponseModel> response) {
int kode = response.body().getKode();
String pesan = response.body().getPesan();
//Toast.makeText(MainActivity.this, "Kode : "+kode+" | Pesan : "+pesan, Toast.LENGTH_SHORT).show();
listDataPembelian = response.body().getData();
adData = new AdapterDataPembelian(PembelianActivity.this, listDataPembelian);
rvData.setAdapter(adData);
adData.notifyDataSetChanged();
pbData.setVisibility(View.INVISIBLE);
}
#Override
public void onFailure(Call<ResponseModel> call, Throwable t) {
Toast.makeText(PembelianActivity.this, "Gagal Menghubungi Server", Toast.LENGTH_SHORT).show();
pbData.setVisibility(View.INVISIBLE);
}
});
}
}
Here is my app
I would do something like this:
Create an Interface for your activity to implement:
public interface CallbackIF {
double tally(double amount, int quantity)
}
public class PembelianActivity extends AppCompatActivity implements CallbackIF {
#Override
public double tally(double amount, int quantity) {
return amount * quantity;
}
}
Then when you initialize your recyclerview adapter pass in the interface like so:
adData = new AdapterDataPembelian(PembelianActivity.this, listDataPembelian, PembelianActivity.this);
And change your constructor for the data adapter to be
private CallbackIF callback;
public AdapterDataPembelian(Context ctx, List<DataModel> listDataPembelian, CallbackIF callback) {
this.ctx = ctx;
this.listDataPembelian = listDataPembelian;
this.callback = callback;
}
Then in your onClicklistener for your list / wherever you want to trigger a tally just call
double value = callback.tally(amount, quantity);
If you have any questions please ask
I try to passing data from cardview when clicked to DetailFragment, in this case I try to use interface in my adapter, but I get an error a null object reference in mOnItemClickListener.onClick(i).
I try to passing data from cardview when clicked to DetailFragment, in this case I try to use interface in my adapter.
I want to passing data to DetailMoviesFragment Class.
this is my CardviewMovieAdapter Class
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import java.util.ArrayList;
public class CardviewMovieAdapter extends RecyclerView.Adapter<CardviewMovieAdapter.CardViewViewHolder> {
private ArrayList<Movie> listMovie;
Context context;
OnItemClickListener mOnItemClickListener;
public void setListMovie(ArrayList<Movie> listMovie) {
this.listMovie = listMovie;
}
public ArrayList<Movie> getListMovie() {
return listMovie;
}
public interface OnItemClickListener {
void onClick(int position);
}
public void setOnItemClickListener(final OnItemClickListener mItemClickListener) {
this.mOnItemClickListener = mItemClickListener;
}
public CardviewMovieAdapter(ArrayList<Movie> listMovie, Context context) {
this.listMovie = listMovie;
this.context = context;
}
#NonNull
#Override
public CardviewMovieAdapter.CardViewViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.list_movie, viewGroup,false);
return new CardViewViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull final CardviewMovieAdapter.CardViewViewHolder cardViewViewHolder, final int i) {
final Movie movie = listMovie.get(i);
Glide.with(cardViewViewHolder.itemView.getContext())
.load(movie.getImageMovie())
.apply(new RequestOptions().override(350, 550))
.into(cardViewViewHolder.imgPhoto);
cardViewViewHolder.tvTitle.setText(movie.getTitleMovie());
cardViewViewHolder.tvDesc.setText(movie.getDescription());
cardViewViewHolder.btnDetail.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(cardViewViewHolder.itemView.getContext(), "Detail "+
listMovie.get(cardViewViewHolder.getAdapterPosition()).getTitleMovie(), Toast.LENGTH_SHORT).show();
}
});
cardViewViewHolder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(cardViewViewHolder.itemView.getContext(), "Kamu Memilih "+movie.getTitleMovie(), Toast.LENGTH_SHORT).show();
mOnItemClickListener.onClick(i);
}
});
// cardViewViewHolder.itemView.setOnClickListener(new View.OnClickListener() {
// #Override
// public void onClick(View v) {
// Toast.makeText(cardViewViewHolder.itemView.getContext(), "Kamu Memilih "+movie.getTitleMovie(), Toast.LENGTH_SHORT).show();
// }
// });
}
#Override
public int getItemCount() {
return listMovie.size();
}
public class CardViewViewHolder extends RecyclerView.ViewHolder {
ImageView imgPhoto;
TextView tvTitle, tvDesc;
Button btnDetail;
public CardViewViewHolder(#NonNull View itemView) {
super(itemView);
imgPhoto = itemView.findViewById(R.id.img_item_photo);
tvTitle = itemView.findViewById(R.id.tv_title);
tvDesc = itemView.findViewById(R.id.tv_desc);
btnDetail = itemView.findViewById(R.id.btn_detail);
}
}
}
This is my MoviesFragment Class
import android.content.Intent;
import android.content.res.TypedArray;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.widget.CardView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ListView;
import java.util.ArrayList;
/**
* A simple {#link Fragment} subclass.
*/
public class MoviesFragment extends Fragment implements View.OnClickListener{
private RecyclerView rvMovie;
private String[] dataMovieTitle;
private String[] dataDescription;
private TypedArray dataPhoto;
private ArrayList<Movie> movies;
Button btnDetail;
private CardviewMovieAdapter adapter;
View view;
final static String KEY = "KEY";
public MoviesFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
view = inflater.inflate(R.layout.fragment_movies, container, false);
//adapter = new CardviewMovieAdapter(movies,getContext());
rvMovie = view.findViewById(R.id.rv_movies);
prepare();
addItem();
showRecyclerCardView();
adapter = new CardviewMovieAdapter(movies, getContext());
adapter.setOnItemClickListener(new CardviewMovieAdapter.OnItemClickListener() {
#Override
public void onClick(int position) {
final Movie movie = movies.get(position);
DetailMoviesFragment detailMoviesFragment = new DetailMoviesFragment();
// Bundle mBundle = new Bundle();
// mBundle.putString(detailMoviesFragment.EXTRA_TITLE, movie.getTitleMovie());
// mBundle.putString(detailMoviesFragment.EXTRA_DESCRIPTION, movie.getDescription());
// mBundle.putInt(detailMoviesFragment.EXTRA_PHOTO, movie.getImageMovie());
// detailMoviesFragment.setArguments(mBundle);
MoviesFragment.newInstance(movie.getTitleMovie(), movie.getDescription(), movie.getImageMovie());
FragmentManager mFragmentManager = getFragmentManager();
if (mFragmentManager!= null) {
FragmentTransaction mFragmentTransaction = mFragmentManager.beginTransaction();
mFragmentTransaction.replace(R.id.containterFragment, detailMoviesFragment, DetailMoviesFragment.class.getSimpleName());
mFragmentTransaction.addToBackStack(null);
mFragmentTransaction.commit();
}
}
});
return view;
}
public static MoviesFragment newInstance(String title, String desc, int image) {
MoviesFragment moviesFragment = new MoviesFragment();
Bundle args = new Bundle();
args.putInt("image", image);
args.putString("title", title);
args.putString("desc", desc);
moviesFragment.setArguments(args);
return moviesFragment;
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
private void showRecyclerCardView(){
rvMovie.setLayoutManager(new LinearLayoutManager(getActivity()));
CardviewMovieAdapter adapter = new CardviewMovieAdapter(movies,getActivity());
rvMovie.setAdapter(adapter);
}
private void prepare() {
dataMovieTitle = getResources().getStringArray(R.array.data_movie_name);
dataDescription = getResources().getStringArray(R.array.data_desc_movie);
dataPhoto = getResources().obtainTypedArray(R.array.data_photo_movie);
}
private void addItem(){
movies = new ArrayList<>();
for (int i=0; i < dataMovieTitle.length; i++){
Movie movie = new Movie();
movie.setImageMovie(dataPhoto.getResourceId(i, -1));
movie.setTitleMovie(dataMovieTitle[i]);
movie.setDescription(dataDescription[i]);
movies.add(movie);
}
}
#Override
public void onClick(View v) {
if(v.getId() == R.id.card_view){
}
}
}
and this is DetailMoviesActivity Class
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import com.squareup.picasso.Picasso;
public class DetailMovieActivity extends AppCompatActivity {
Movie movie;
TextView tvTitle, tvDesc;
ImageView ivMovie;
Button btnDetail;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail_movie);
initView();
}
private void initView() {
movie = (Movie) getIntent().getSerializableExtra("informasi");
String judul = movie.getTitleMovie();
String desc = movie.getDescription();
int img = movie.getImageMovie();
tvTitle.setText(judul);
tvDesc.setText(desc);
Picasso.get().load(img).into(ivMovie);
}
}
You can try with delete the setOnItemClickListener and call intent from cardViewViewHolder.itemView.setOnClickListener
I am developing attendance system and i have a listview with students name i want to programatically check or uncheck the radio buttons in the listview when the scanned qr matchs the student name I tried to do it in the ontextchengeListner method of txtresult but the text is changing many time even in reading a single qr
This are my java classes
CustomAdapter.java
package com.attendance.olana.qr_scanner;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CompoundButton;
import android.widget.RadioButton;
import android.widget.TextView;
import java.util.ArrayList;
/**
* Created by olana on 23/03/2018.
*/
public class CustomAdapter extends BaseAdapter {
Context context;
String[] questionsList;
public static String message;
LayoutInflater inflter;
public static TextView question ;
public static RadioButton yes,no ;
public static ArrayList<String> selectedAnswers;
public CustomAdapter(Context applicationContext, String[] questionsList) {
this.context = context;
this.questionsList = questionsList;
// initialize arraylist and add static string for all the questions
selectedAnswers = new ArrayList<>();
for (int i = 0; i < questionsList.length; i++) {
selectedAnswers.add("Not Attempted");
}
inflter = (LayoutInflater.from(applicationContext));
}
#Override
public int getCount() {
return questionsList.length;
}
#Override
public Object getItem(int i) {
return null;
}
#Override
public long getItemId(int i) {
return 0;
}
#Override
public View getView(final int i, View view, ViewGroup viewGroup) {
view = inflter.inflate(R.layout.main, null);
// get the reference of TextView and Button's
question = (TextView) view.findViewById(R.id.question);
yes = (RadioButton) view.findViewById(R.id.yes);
no = (RadioButton) view.findViewById(R.id.no);
// perform setOnCheckedChangeListener event on yes button
yes.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// set Yes values in ArrayList if RadioButton is checked
if (isChecked)
selectedAnswers.set(i, "Present");
}
});
// perform setOnCheckedChangeListener event on no button
no.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// set No values in ArrayList if RadioButton is checked
if (isChecked)
selectedAnswers.set(i, "Absent");
}
});
// set the value in TextView
question.setText(questionsList[i]);
return view;
}
}
list.java
package com.attendance.olana.qr_scanner;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.Toast;
/**
* Created by olana on 23/03/2018.
*/
public class list extends AppCompatActivity {
ListView simpleList;
public static String[] questions;
Button submit,scan;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list);
scan =(Button)findViewById(R.id.scan);
// get the string array from string.xml file
questions = getResources().getStringArray(R.array.student);
// get the reference of ListView and Button
simpleList = (ListView) findViewById(R.id.simpleListView);
submit = (Button) findViewById(R.id.submit);
// set the adapter to fill the data in the ListView
CustomAdapter customAdapter = new CustomAdapter(getApplicationContext(), questions);
simpleList.setAdapter(customAdapter);
scan.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i;
i = new Intent(list.this,MainActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivity(i);
}
});
// perform setOnClickListerner event on Button
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String message = "";
// get the value of selected answers from custom adapter
for (int i = 0; i < CustomAdapter.selectedAnswers.size(); i++) {
message = message + "\n" + (i + 1) + " " + CustomAdapter.selectedAnswers.get(i);
}
// display the message on screen with the help of Toast.
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show();
}
});
}
}
MainActivity.java
package com.attendance.olana.qr_scanner;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Vibrator;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.util.SparseArray;
import android.view.Menu;
import android.view.MenuItem;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.vision.CameraSource;
import com.google.android.gms.vision.Detector;
import com.google.android.gms.vision.barcode.Barcode;
import com.google.android.gms.vision.barcode.BarcodeDetector;
import java.io.IOException;
import java.util.jar.Manifest;
public class MainActivity extends AppCompatActivity {
BarcodeDetector barcodeDetector;
SurfaceView camerapreview;
CameraSource cameraSource;
TextView txtresult;
String message;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button finish = (Button) findViewById(R.id.finish);
//Button scan = (Button) findViewById(R.id.scan);
finish.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show();
}
});
camerapreview = (SurfaceView) findViewById(R.id.camerapreview);
txtresult = (TextView) findViewById(R.id.txtresult);
barcodeDetector = new BarcodeDetector.Builder(this)
.setBarcodeFormats(Barcode.QR_CODE)
.build();
cameraSource = new CameraSource
.Builder(this, barcodeDetector)
.setRequestedPreviewSize(640, 480)
.build();
//add event
camerapreview.getHolder().addCallback(new SurfaceHolder.Callback() {
#Override
public void surfaceCreated(SurfaceHolder holder) {
try {
cameraSource.start(camerapreview.getHolder());
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
cameraSource.stop();
}
});
barcodeDetector.setProcessor(new Detector.Processor<Barcode>() {
#Override
public void release() {
try {
cameraSource.start(camerapreview.getHolder());
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void receiveDetections(Detector.Detections<Barcode> detections) {
final SparseArray<Barcode> qrcodes = detections.getDetectedItems();
if (qrcodes.size() != 0) {
txtresult.post(new Runnable() {
#Override
public void run() {
//create vibration
Vibrator vibrator = (Vibrator) getApplicationContext().getSystemService(Context.VIBRATOR_SERVICE);
vibrator.vibrate(100);
txtresult.setText(qrcodes.valueAt(0).displayValue);
//barcodeDetector.release();
}
});
}
}
});
}
}
Please tell me where i can implement these the programatically checking or unchecking the radio button when the name in the listview matchs the scanned qr please help me
Why is this app is not working properly when I click on the each item of the recycle view Toast of the position of the item appears but when I click each item(cardview) to open a new activity app crash. I don't know what is wrong.
GalleryFragment.java
package com.example.kiran.cr7;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.CardView;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.Toast;
import java.util.ArrayList;
/** * A simple {#link Fragment} subclass. */ public class GalleryFragment extends Fragment implements Adapter.OnCardClickListner {
public GalleryFragment() {
// Required empty public constructor
}
private RecyclerView mrecycleview;
private CardView mcardview;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_gallery, container, false);
mrecycleview = (RecyclerView)view.findViewById(R.id.recycle_view);
mcardview = (CardView)view.findViewById(R.id.card_view);
//improve performance
mrecycleview.setHasFixedSize(true);
LinearLayoutManager manager = new LinearLayoutManager(view.getContext());
mrecycleview.setLayoutManager(manager);
ArrayList<Item> itemlist = dummies();
//set adapter // Adapter adapter = new Adapter(view.getContext(),itemlist); // mrecycleview.setAdapter(adapter); // adapter.setOnCardClickListner(this);
Adapter adapter = new Adapter(view.getContext(),itemlist);
mrecycleview.setAdapter(adapter);
adapter.setOnCardClickListner(this);
return view;
}
private ArrayList<Item> dummies() {
ArrayList<Item> list = new ArrayList<>();
for (int i = 0; i < 6; i++) {
if (i == 0) {
Item item = new Item();
item.id = i;
item.text = "RonaldoPhoto" + (i);
item.img = "http://wallpapercave.com/wp/sIggTrG.jpg";
list.add(item);
} else if (i == 1) {
Item item = new Item();
item.id = i;
item.text = "RonaldoPhoto" + (i);
item.img = "http://i2.wp.com/www.footballwood.com/wp-content/uploads/2015/01/Ronaldo-Best-Wallpapers.jpg";
list.add(item);
} else if (i == 2) {
Item item = new Item();
item.id = i;
item.text = "RonaldoPhoto" + (i);
item.img = "http://www.magazinefuse.com/wp-content/uploads/2015/09/7-i476725-1024x640.jpg";
list.add(item);
} else if (i == 3) {
Item item = new Item();
item.id = i;
item.text = "RonaldoPhoto" + (i);
item.img = "https://i.ytimg.com/vi/SwHv6xGGBBQ/maxresdefault.jpg";
list.add(item);
}else if (i == 4) {
Item item = new Item();
item.id = i;
item.text = "RonaldoPhoto" + (i);
item.img = "https://i.ytimg.com/vi/WrCfkR4Qcns/maxresdefault.jpg";
list.add(item);
}
else if (i == 5) {
Item item = new Item();
item.id = i;
item.text = "RonaldoPhoto" + (i);
item.img = "http://images.latinpost.com/data/images/full/101477/cristiano-ronaldo-real-madrid.jpg";
list.add(item);
}
}
return list;
}
#Override
public void OnCardClicked(View view, int position) {
Log.d("OnClick", "Card Position" + position);
Toast.makeText(getContext(),"click"+position,Toast.LENGTH_SHORT).show();
Intent in= new Intent(view.getContext(),Detail.class);
in.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(in);
} }
Adapter.java
package com.example.kiran.cr7;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v7.widget.CardView;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
public class Adapter extends RecyclerView.Adapter<Adapter.ViewHolder>{
private RecyclerView mRecyclerView;
private Context context;
private ArrayList<Item> itemlist;
OnCardClickListner onCardClickListner;
public Adapter(Context context, ArrayList<Item> itemlist){
this.context = context;
this.itemlist = itemlist;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View view = inflater.from(parent.getContext()).inflate(R.layout.cardview,parent,false);
mRecyclerView = (RecyclerView) view.findViewById(R.id.recycle_view);
ViewHolder viewholder = new ViewHolder(view);
return viewholder;
}
//bind views with data
#Override
public void onBindViewHolder(ViewHolder holder, final int position) {
final Item item = itemlist.get(position);
//get element form your dataset at this position
//replace the contents of the view with that element
Picasso.with(context)
.load(item.img)
.placeholder(R.drawable.fern)
.error(android.R.drawable.stat_notify_error)
.into(holder.cardimage);
holder.cardtext.setText(item.text);
holder.card_view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onCardClickListner.OnCardClicked(v,position);
Intent in = new Intent(v.getContext(), Detail.class);
in.putExtra("item",item);
in.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//context.startActivity(in);
}
});
}
#Override
public int getItemCount() {
if(itemlist != null){
return itemlist.size();
}
return 0;
}
//provide the reference to the views for each data item
//ViewHolder class
//since it is static it uses only single memory so protect memory leak : a design pattern for android
public static class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
public CardView card_view;
public TextView cardtext;
public ImageView cardimage;
//connects which view belongs to which layout
public ViewHolder(View itemView) {
super(itemView);
card_view = (CardView)itemView.findViewById(R.id.card_view);
cardtext = (TextView)itemView.findViewById(R.id.cardtext);
cardimage = (ImageView)itemView.findViewById(R.id.cardimage);
}
#Override
public void onClick(View view) {
}
}
public interface OnCardClickListner {
void OnCardClicked(View view, int position);
}
public void setOnCardClickListner(OnCardClickListner onCardClickListner) {
this.onCardClickListner = onCardClickListner;
}
}
Detail
package com.example.kiran.cr7;
import android.app.DownloadManager; import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.Uri; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.widget.ImageView; import android.widget.Toast;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
public class Detail extends AppCompatActivity implements Adapter.OnCardClickListner {
private ImageView detailimage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
detailimage = (ImageView)findViewById(R.id.detailimage);
}
#Override
public void OnCardClicked(View view, int position) {
Log.d("OnClick", "Card Position" + position);
if(getIntent().getSerializableExtra("item") != null){
Item i = (Item)getIntent().getSerializableExtra("item");
Picasso.with(this)
.load(i.img)
.placeholder(R.drawable.fern)
.error(android.R.drawable.stat_notify_error)
.into(detailimage);
}
} }
You don't need to use OnCardClicked in detail.java activity. Use serializable to send data from one activity from another. Use OnCardClicked.onBindViewHolder to send data from one activity to another.
package com.example.kiran.cr7;
import android.app.DownloadManager;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
import com.squareup.picasso.Picasso;
public class Test extends Activity {
private ImageView detailimage;
private Button download;
DownloadManager downloadManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
download = (Button) findViewById(R.id.Download);
detailimage = (ImageView) findViewById(R.id.detailimage);
final Animation animAlpha = AnimationUtils.loadAnimation(this,R.anim.anim_alpha);
if (getIntent().getSerializableExtra("item") != null) {
final Item i = (Item) getIntent().getSerializableExtra("item");
Picasso.with(this)
.load(i.img)
.resize(500,600)
.placeholder(R.drawable.fern)
.error(android.R.drawable.stat_notify_error)
.into(detailimage);
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
//Toast.makeText(Test.this, "Network Connection available", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(Test.this, "No Network Connection", Toast.LENGTH_LONG).show();
}
download.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
view.startAnimation(animAlpha);
downloadManager =(DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
Uri uri = Uri.parse(i.img);
DownloadManager.Request request = new DownloadManager.Request(uri);
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
Long reference = downloadManager.enqueue(request);
}
});
}
}
}