I have a fragment contain dialog which has a recycler view, after user clicked one item from the reycler view dialog, I want to pass the data and send to the main recycler view in the fragment. How can I solved this ?
Below my Fragment
public class UjianFragment extends BaseFragment implements UjianContract.View{
#Inject
UjianContract.Presenter mPresenter;
#Inject
public UjianFragment(){
}
#Override
protected int getLayoutView() {
return R.layout.fragment_ujian;
}
#Override
protected void initView(Bundle state) {
mPresenter.takeView(this);
mPresenter.saveStartTime();
mPresenter.getNumber(idMatpel,idUjian);
LinearLayoutManager liN = new LinearLayoutManager(parentActivity(),LinearLayoutManager.HORIZONTAL,false);
rvNumber.setLayoutManager(liN);
rvNumber.setHasFixedSize(true);
rvNumber.setAdapter(numberAdapter);
LinearLayoutManager lin2 = new LinearLayoutManager(parentActivity());
rlSoal.setLayoutManager(lin2);
rlSoal.setHasFixedSize(true);
rlSoal.setAdapter(soalAdapter);
countDown();
soalAdapter.setOnClickListener(new SoalAdapter.OnClickListener() {
#Override
public void onClick(String gambar,String no) {
AlertDialog.Builder mBulider = new AlertDialog.Builder(getContext());
View mView = getLayoutInflater().inflate(R.layout.dialog_custom_layout,null);
PhotoView photoView = mView.findViewById(R.id.imageViewZoom);
Glide.with(getContext())
.load(gambar)
.into(photoView);
mBulider.setView(mView);
AlertDialog mDialog = mBulider.create();
mDialog.show();
}
#Override
public void onClickJawab(String id,String jawabanUser, boolean hasil) {
mPresenter.updateJawaban(id,jawabanUser,hasil);
}
#Override
public void onClickRefreshSoal(String jenis, String idSoal) {
if (jenis.equalsIgnoreCase("1")){
mPresenter.getRefreshSoalPG(idSoal, idUjian, idMatpel);
}else {
mPresenter.getRefrehSoalBS(idSoal, idUjian, idMatpel);
}
}
#Override
public void onClickRefreshJawaban(String idSoal) {
}
#Override
public void onClickJawabanJD() {
mPresenter.getJawabanJD();
Dialog dialog = new Dialog(parentActivity());
dialog.setContentView(R.layout.item_jawabanjd);
RecyclerView dialogRecycler = dialog.findViewById(R.id.rvJawabanMenjodohkan);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(parentActivity());
dialogRecycler.setLayoutManager(linearLayoutManager);
dialogRecycler.setHasFixedSize(true);
dialogRecycler.setAdapter(jawabanJDAdapter);
jawabanJDAdapter.setOnClickListener(new JawabanJDAdapter.OnClickListener() {
#Override
public void onClickJawaban(String jawabanJD) {
Toast.makeText(parentActivity(), "anda memilih " + jawabanJD, Toast.LENGTH_SHORT).show(); //I want to pass this jawabanJD to the adapter
}
});
dialog.show();
}
});
}
#Override
public void setSuccess(boolean isShow) {
lySuccess.setVisibility(isShow ? View.VISIBLE : View.GONE);
}
#Override
public void reload() {
mPresenter.getNumber(idUjian, idMatpel);
}
#Override
public void setToServer(String idUjian, String idMapel, String idSiswa, String start, String end, String valueTrue, String valueFalse, String score) {
mPresenter.submitUjian(idUjian, idMapel, idSiswa, start, end, valueTrue, valueFalse, score);
}
#Override
public void setJawabanJD(List<JawabanJDEntity> jawabanJDEntityList) {
jawabanJDAdapter.setGroupList(jawabanJDEntityList);
}
private void countDown() {
int time = Integer.parseInt(timer) * 60 * 1000;
countTimer = new CountDownTimer(time,1000){
#Override
public void onTick(long l) {
long min = l;
#SuppressLint("DefaultLocale") String hms = String.format("%02d:%02d:%02d", TimeUnit.MILLISECONDS.toHours(min), TimeUnit.MILLISECONDS.toMinutes(min) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(min)), TimeUnit.MILLISECONDS.toSeconds(min) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(min)));
tvTimer.setText(hms);
}
#Override
public void onFinish() {
rlSoal.setVisibility(View.GONE);
mPresenter.getDataToDb(idMatpel,idUjian, type, image, soal,matpel, ujian);
Toast.makeText(parentActivity(), "Waktu habis! Silahkan submit", Toast.LENGTH_SHORT).show();
}
};
countTimer.start();
}
#Override
public void setNumber(List<SoalEntity> number) {
numberAdapter.setGroupList(number);
soalAdapter.setGroupList(number);
}
}
and my adapter
public class SoalAdapter extends RecyclerView.Adapter<SoalAdapter.ItemVH> {
private int mSelectedItem = -1;
private RadioGroup lastCheckedRadio = null;
private OnClickListener onClickListener;
private final boolean[] mCheckedStateA;
private final boolean[] mCheckedStateB;
private final boolean[] mCheckedStateC;
private final boolean[] mCheckedStateD;
private int positionl = -1;
private OnRadioItemClicked onRadioItemClicked;
private ArrayList<ObjectListItem> objectListItems;
private
List<SoalEntity> soalBeanList;
private Context context;
#Inject
public SoalAdapter(Context context){
this.context = context;
soalBeanList = new ArrayList<>();
mCheckedStateA = new boolean[0];
mCheckedStateB = new boolean[0];
mCheckedStateC = new boolean[0];
mCheckedStateD = new boolean[0];
}
public void setOnClickListener(OnClickListener onClickListener) {
this.onClickListener = onClickListener;
}
public void setOnRadioItemClicked(OnRadioItemClicked onRadioItemClicked){
this.onRadioItemClicked = onRadioItemClicked;
}
#NonNull
#Override
public SoalAdapter.ItemVH onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View root = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_soal, parent, false);
return new SoalAdapter.ItemVH(root);
}
#Override
public void onBindViewHolder(#NonNull SoalAdapter.ItemVH holder, int position) {
holder.bind(soalBeanList.get(position));
}
#Override
public int getItemCount() {
return soalBeanList.size();
}
public void setGroupList(List<SoalEntity> soalBeanList1){
soalBeanList.clear();
soalBeanList.addAll(soalBeanList1);
notifyDataSetChanged();
}
public void addLast(SoalEntity soalBean){
soalBeanList.add(soalBean);
notifyDataSetChanged();
}
public class ItemVH extends RecyclerView.ViewHolder {
#BindView(R.id.tvItemSoalJawabanJD)
TextView tvItemSoalJawabanJD;
private boolean nilai = false;
ItemVH(#NonNull View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
}
void bind(SoalEntity soalBean) {
nomernya.setText(soalBean.getNoUrut());
if (soalBean.getJenisSoal().equalsIgnoreCase("1")){
rlAnswer.setVisibility(View.VISIBLE);
rlAnswerTf.setVisibility(View.GONE);
rlAnswerMatch.setVisibility(View.GONE);
}else if (soalBean.getJenisSoal().equalsIgnoreCase("2")){
rlAnswer.setVisibility(View.GONE);
rlAnswerTf.setVisibility(View.VISIBLE);
rlAnswerMatch.setVisibility(View.GONE);
} else if(soalBean.getJenisSoal().equalsIgnoreCase("3")) {
rlAnswer.setVisibility(View.GONE);
rlAnswerTf.setVisibility(View.GONE);
rlAnswerMatch.setVisibility(View.VISIBLE);
}
if (soalBean.getFlag().equalsIgnoreCase("0")){
rb_e.setVisibility(View.GONE);
jawabanE.setVisibility(View.GONE);
jawabanE_image.setVisibility(View.GONE);
}else if (soalBean.getFlag().equalsIgnoreCase("1")){
rb_e.setVisibility(View.VISIBLE);
jawabanE.setVisibility(View.VISIBLE);
jawabanE_image.setVisibility(View.VISIBLE);
}else if (soalBean.getFlag().equalsIgnoreCase("2")){
rb_d.setVisibility(View.GONE);
jawabanD.setVisibility(View.GONE);
jawabanD_image.setVisibility(View.GONE);
rb_e.setVisibility(View.GONE);
jawabanE.setVisibility(View.GONE);
jawabanE_image.setVisibility(View.GONE);
}else {
rb_d.setVisibility(View.VISIBLE);
jawabanD_image.setVisibility(View.VISIBLE);
jawabanD.setVisibility(View.VISIBLE);
rb_e.setVisibility(View.VISIBLE);
jawabanE.setVisibility(View.VISIBLE);
jawabanE_image.setVisibility(View.VISIBLE);
}
if (soalBean.getSoalGambar().isEmpty()||soalBean.getSoalGambar().
equalsIgnoreCase("null")||soalBean.getSoalGambar().equalsIgnoreCase("")){
lyNumber.setVisibility(View.GONE);
tvSoal.setText(soalBean.getSoalUjian());
tvSoal.setTextColor(Color.parseColor("#000000"));
imageSoal.setVisibility(View.GONE);
loadImage.setVisibility(View.GONE);
}else if(soalBean.getSoalUjian().isEmpty()||soalBean.getSoalUjian()
.equalsIgnoreCase("null")||soalBean.getSoalUjian().equalsIgnoreCase("")){
lyNumber.setVisibility(View.VISIBLE);
Glide.with(itemView.getContext())
.load(soalBean.getSoalGambar())
.skipMemoryCache(true)
.diskCacheStrategy(DiskCacheStrategy.NONE)
.error(R.drawable.ic_baseline_broken_image_24)
.priority(Priority.IMMEDIATE)
.listener(new RequestListener<Drawable>() {
#Override
public boolean onLoadFailed(#Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
loadImage.setVisibility(View.GONE);
return false;
}
#Override
public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
loadImage.setVisibility(View.GONE);
return false;
}
})
.into(imageSoal);
tvSoal.setVisibility(View.GONE);
}else {
lyNumber.setVisibility(View.VISIBLE);
tvSoal.setVisibility(View.VISIBLE);
tvSoal.setTextColor(Color.parseColor("#000000"));
imageSoal.setVisibility(View.VISIBLE);
tvSoal.setText(soalBean.getSoalUjian());
Glide.with(itemView.getContext())
.load(soalBean.getSoalGambar())
.skipMemoryCache(true)
.diskCacheStrategy(DiskCacheStrategy.NONE)
.error(R.drawable.ic_baseline_broken_image_24)
.priority(Priority.IMMEDIATE)
.listener(new RequestListener<Drawable>() {
#Override
public boolean onLoadFailed(#Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
loadImage.setVisibility(View.GONE);
return false;
}
#Override
public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
loadImage.setVisibility(View.GONE);
return false;
}
})
.into(imageSoal);
}
if (soalBean.getPilA_file().isEmpty()||soalBean.getPilA_file()
.equalsIgnoreCase("null")||soalBean.getPilA_file().equalsIgnoreCase("")){
jawabanA.setText(soalBean.getPilA());
jawabanA.setTextColor(Color.parseColor("#000000"));
jawabanA_image.setVisibility(View.GONE);
}else {
Glide.with(itemView.getContext())
.load(soalBean.getPilA_file())
.apply(RequestOptions.skipMemoryCacheOf(true))
.apply(RequestOptions.diskCacheStrategyOf(DiskCacheStrategy.NONE))
.listener(new RequestListener<Drawable>() {
#Override
public boolean onLoadFailed(#Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
loadImage.setVisibility(View.GONE);
return false;
}
#Override
public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
loadImage.setVisibility(View.GONE);
return false;
}
})
.into(jawabanA_image);
jawabanA.setVisibility(View.GONE);
}
if (soalBean.getPilB_file().isEmpty()||soalBean.getPilB_file()
.equalsIgnoreCase("null")||soalBean.getPilB_file().equalsIgnoreCase("")){
jawabanB.setText(soalBean.getPilB());
jawabanB.setTextColor(Color.parseColor("#000000"));
jawabanB_image.setVisibility(View.GONE);
}else {
Glide.with(itemView.getContext())
.load(soalBean.getPilB_file())
.apply(RequestOptions.skipMemoryCacheOf(true))
.apply(RequestOptions.diskCacheStrategyOf(DiskCacheStrategy.NONE))
.into(jawabanB_image);
jawabanB.setVisibility(View.GONE);
}
if (soalBean.getPilC_file().isEmpty()||soalBean.getPilC_file()
.equalsIgnoreCase("null")||soalBean.getPilC_file().equalsIgnoreCase("")){
jawabanC.setText(soalBean.getPilC());
jawabanC.setTextColor(Color.parseColor("#000000"));
jawabanC_image.setVisibility(View.GONE);
}else {
Glide.with(itemView.getContext())
.load(soalBean.getPilC_file())
.apply(RequestOptions.skipMemoryCacheOf(true))
.apply(RequestOptions.diskCacheStrategyOf(DiskCacheStrategy.NONE))
.into(jawabanC_image);
jawabanC.setVisibility(View.GONE);
}
if (soalBean.getPilD_file().isEmpty()||soalBean.getPilD_file()
.equalsIgnoreCase("null")||soalBean.getPilD_file().equalsIgnoreCase("")){
jawabanD.setText(soalBean.getPilD());
jawabanD.setTextColor(Color.parseColor("#000000"));
jawabanD_image.setVisibility(View.GONE);
}else {
Glide.with(itemView.getContext())
.load(soalBean.getPilD_file())
.apply(RequestOptions.skipMemoryCacheOf(true))
.apply(RequestOptions.diskCacheStrategyOf(DiskCacheStrategy.NONE))
.into(jawabanD_image);
jawabanD.setVisibility(View.GONE);
}
if (soalBean.getPilE_file().isEmpty()||soalBean.getPilE_file()
.equalsIgnoreCase("null")||soalBean.getPilE_file().equalsIgnoreCase("")){
jawabanE.setText(soalBean.getPilE());
jawabanE.setTextColor(Color.parseColor("#000000"));
jawabanE_image.setVisibility(View.GONE);
}else {
Glide.with(itemView.getContext())
.load(soalBean.getPilE_file())
.apply(RequestOptions.skipMemoryCacheOf(true))
.apply(RequestOptions.diskCacheStrategyOf(DiskCacheStrategy.NONE))
.into(jawabanE_image);
jawabanE.setVisibility(View.GONE);
}
if (soalBean.getJawab().equalsIgnoreCase("A")){
rb_a.setChecked(true);
rb_b.setChecked(false);
rb_c.setChecked(false);
rb_d.setChecked(false);
rb_e.setChecked(false);
}else if (soalBean.getJawab().equalsIgnoreCase("B")){
rb_a.setChecked(false);
rb_b.setChecked(true);
rb_c.setChecked(false);
rb_d.setChecked(false);
rb_e.setChecked(false);
}else if (soalBean.getJawab().equalsIgnoreCase("C")){
rb_a.setChecked(false);
rb_b.setChecked(false);
rb_c.setChecked(true);
rb_d.setChecked(false);
rb_e.setChecked(false);
}else if (soalBean.getJawab().equalsIgnoreCase("D")){
rb_a.setChecked(false);
rb_b.setChecked(false);
rb_c.setChecked(false);
rb_d.setChecked(true);
rb_e.setChecked(false);
}else if (soalBean.getJawab().equalsIgnoreCase("E")){
rb_a.setChecked(false);
rb_b.setChecked(false);
rb_c.setChecked(false);
rb_d.setChecked(false);
rb_e.setChecked(true);
}else if (soalBean.getJawab().equalsIgnoreCase("0")){
rbTrue.setChecked(true);
rbFalse.setChecked(false);
}else if (soalBean.getJawab().equalsIgnoreCase("1")){
rbTrue.setChecked(false);
rbFalse.setChecked(true);
}
rb_a.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if (b){
if (compoundButton.getId() == R.id.rb_pilih_a){
rb_b.setChecked(false);
rb_c.setChecked(false);
rb_d.setChecked(false);
rb_e.setChecked(false);
if(soalBean.getJawabanUjian().equalsIgnoreCase("A")){
nilai = true;
}else{
nilai = false;
}
if (onClickListener!=null){
onClickListener.onClickJawab(soalBean.getIdSoal(),"A",nilai);
}
}
}else {
}
}
});
rb_b.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if (b){
if (compoundButton.getId() == R.id.rb_pilih_b){
rb_a.setChecked(false);
rb_c.setChecked(false);
rb_d.setChecked(false);
rb_e.setChecked(false);
if(soalBean.getJawabanUjian().equalsIgnoreCase("B")){
nilai = true;
}else{
nilai = false;
}
if (onClickListener!=null){
onClickListener.onClickJawab(soalBean.getIdSoal(),"B",nilai);
}
}
}else {
}
}
});
rb_c.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if (b){
if (compoundButton.getId() == R.id.rb_pilih_c){
rb_a.setChecked(false);
rb_b.setChecked(false);
rb_d.setChecked(false);
rb_e.setChecked(false);
if(soalBean.getJawabanUjian().equalsIgnoreCase("C")){
nilai = true;
}else{
nilai = false;
}
if (onClickListener!=null){
onClickListener.onClickJawab(soalBean.getIdSoal(),"C",nilai);
}
}
}else {
}
}
});
rb_d.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if (b){
if (compoundButton.getId() == R.id.rb_pilih_d){
rb_a.setChecked(false);
rb_b.setChecked(false);
rb_c.setChecked(false);
rb_e.setChecked(false);
if(soalBean.getJawabanUjian().equalsIgnoreCase("D")){
nilai = true;
}else{
nilai = false;
}
if (onClickListener!=null){
onClickListener.onClickJawab(soalBean.getIdSoal(),"D",nilai);
}
}
}else {
}
}
});
rb_e.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if (b){
if (compoundButton.getId() == R.id.rb_pilih_e){
rb_a.setChecked(false);
rb_b.setChecked(false);
rb_c.setChecked(false);
rb_d.setChecked(false);
if (soalBean.getJawabanUjian().equalsIgnoreCase("E")){
nilai = true;
}else {
nilai = false;
}
if (onClickListener!=null){
onClickListener.onClickJawab(soalBean.getIdSoal(), "E", nilai);
}
}
}
}
});
rbTrue.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if (b){
if (compoundButton.getId() == R.id.rb_pilih_true){
rbFalse.setChecked(false);
if (soalBean.getJawabanUjian().equalsIgnoreCase("0")){
nilai = true;
}else {
nilai = false;
}
if (onClickListener!=null){
onClickListener.onClickJawab(soalBean.getIdSoal(), "0", nilai);
}
}
}
}
});
rbFalse.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if (b){
if (compoundButton.getId() == R.id.rb_pilih_false){
rbTrue.setChecked(false);
if (soalBean.getJawabanUjian().equalsIgnoreCase("1")){
nilai = true;
}else {
nilai = false;
}
if (onClickListener!=null){
onClickListener.onClickJawab(soalBean.getIdSoal(), "1", nilai);
}
}
}
}
});
imageSoal.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (onClickListener!=null){
onClickListener.onClick(soalBean.getSoalGambar(),soalBean.getNoUrut());
}
}
});
tvRefreshSoal.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (onClickListener!=null){
onClickListener.onClickRefreshSoal(soalBean.getJenisSoal(), soalBean.getIdSoal());
}
}
});
tvRefreshJawaban.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (onClickListener!=null){
onClickListener.onClickRefreshJawaban(soalBean.getIdSoal());
}
}
});
tvItemSoalJawabanJD.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (onClickListener!=null) {
onClickListener.onClickJawabanJD();
}
}
});
tvItemSoalJawabanJD.setText();//This is the data result from fragemnt
}
}
public interface OnClickListener{
void onClick(String gambar,String no);
void onClickJawab(String id,String jawabanUser,boolean hasil);
void onClickRefreshSoal(String jenis, String idSoal);
void onClickRefreshJawaban(String idSoal);
void onClickJawabanJD();
}
public interface OnRadioItemClicked{
void radioItemChecked(int itemPosition, int optNum);
}
Related
I am trying to get the latitude and longitude of the current online user and store it in a firebase database but it keeps returning null. I tried to log the longitude and latitude in logcat, it's not showing anything because I applied a null check to it but if I removed the null check, it returns an error that I am referencing a double location.getLatitude in a null object reference. I don't know what I did wrong. Here is the code
public class VendorMapsActivity extends FragmentActivity implements OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
com.google.android.gms.location.LocationListener {
private GoogleMap mMap;
private GoogleApiClient googleApiClient;
private Location lastLocation;
private LocationRequest locationRequest;
public static final int PERMISSION_FINE_LOCATION = 99;
private LatLng vendorLocationLatLng;
Marker customerDeliveredLocationMarker;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS,WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
setContentView(R.layout.activity_vendor_maps);
mAuth = FirebaseAuth.getInstance();
currentUser = mAuth.getCurrentUser();
vendorId = mAuth.getCurrentUser().getUid();
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
checkLocationPermission();
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
buildGoogleApiClient();
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
mMap.setMyLocationEnabled(true);
}
#Override
public void onConnected(#Nullable Bundle bundle) {
//update the location after one one second
locationRequest = new LocationRequest();
locationRequest.setInterval(1000);
locationRequest.setFastestInterval(1000);
locationRequest.setPriority(locationRequest.PRIORITY_HIGH_ACCURACY);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, locationRequest, this);
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
#Override
public void onLocationChanged(Location location) {
if (lastLocation !=null){
lastLocation = location;
Log.d("TAG","latitude is "+lastLocation.getLatitude());
Log.d("TAG","longitude is "+lastLocation.getLongitude());
if (getApplicationContext() !=null){
try {
lastLocation = location;
LatLng latLng = new LatLng(location.getLatitude(),location.getLongitude());
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(18));
//store the location of the current online vendor by using geofire to get the longitude and latitude of the vendor
String onlineVendorId = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference vendorAvailabilityRef = FirebaseDatabase.getInstance().getReference().child("Vendors Available");
GeoFire geoFireVendorAvailable = new GeoFire(vendorAvailabilityRef);
vendorWorkingRef = FirebaseDatabase.getInstance().getReference().child("Vendors Working");
GeoFire geoFireVendorWorking = new GeoFire(vendorWorkingRef);
switch (customerId){
case "":
geoFireVendorWorking.removeLocation(onlineVendorId, new GeoFire.CompletionListener() {
#Override
public void onComplete(String key, DatabaseError error) {
}
});
geoFireVendorAvailable.setLocation(vendorId, new GeoLocation(location.getLatitude(), location.getLongitude()), new GeoFire.CompletionListener() {
#Override
public void onComplete(String key, DatabaseError error) {
}
});
break;
default:
geoFireVendorAvailable.removeLocation(onlineVendorId, new GeoFire.CompletionListener() {
#Override
public void onComplete(String key, DatabaseError error) {
}
});
geoFireVendorWorking.setLocation(onlineVendorId, new GeoLocation(location.getLatitude(), location.getLongitude()), new GeoFire.CompletionListener() {
#Override
public void onComplete(String key, DatabaseError error) {
}
});
}
}catch (Exception ignored){}
}
}
}
protected synchronized void buildGoogleApiClient(){
googleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
googleApiClient.connect();
}
#Override
protected void onStop() {
super.onStop();
if (!currentVendorLogoutStatus){
disconnectTheVendor();
}
}
i am preparing textview seat numbers list by using recyclerview grid layout manager. i can select the multiple items in the recyclerview list by red color. now i want to keep this seat item selected as red color when on cliking on confirm seat button. when i reopen the recyclerview list it should show the seat selected red color and other seat item in normal color.
confirm seat button clickconfrim seat button click
SelectionAdapter
'''
public class SelectionAdapter extends RecyclerView.Adapter<SelectionAdapter.MygridViewHolder> {
private Context applicationContext;
private ArrayList<Seatnos> list, selected;
public SelectionAdapter(Context applicationContext, ArrayList<Seatnos> list) {
this.applicationContext = applicationContext;
this.list = list;
this.selected = new ArrayList<>();
}
#NonNull
#Override
public MygridViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater layoutInflater=LayoutInflater.from(parent.getContext());
View view=layoutInflater.inflate(R.layout.list_layout_selection,parent,false);
return new MygridViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull final MygridViewHolder holder, final int position) {
final Seatnos seatnos = list.get(position);
holder.textView.setText(String.valueOf(position));
holder.textView.setText(seatnos.getTextno());
holder.textView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (selected.contains(seatnos)) {
selected.remove(seatnos);
unhighlightView(holder);
} else {
selected.add(seatnos);
highlightView(holder);
}
}
});
if (selected.contains(seatnos))
highlightView(holder);
else
unhighlightView(holder);
}
private void highlightView(MygridViewHolder holder) {
holder.itemView.setBackgroundColor(ContextCompat.getColor(applicationContext, R.color.red));
}
private void unhighlightView(MygridViewHolder holder) {
holder.itemView.setBackgroundColor(ContextCompat.getColor(applicationContext, android.R.color.transparent));
}
#Override
public int getItemCount() {
return list.size();
}
class MygridViewHolder extends RecyclerView.ViewHolder {
TextView textView;
MygridViewHolder(#NonNull View itemView) {
super(itemView);
textView = (TextView) itemView.findViewById(R.id.textViewsA);
}
}
public void addAll(ArrayList<Seatnos> list) {
clearAll(false);
this.list = list;
notifyDataSetChanged();
}
public void clearAll(boolean isNotify) {
list.clear();
selected.clear();
if (isNotify) notifyDataSetChanged();
}
public void clearSelected() {
selected.clear();
notifyDataSetChanged();
}
public void selectAll() {
selected.clear();
selected.addAll(list);
notifyDataSetChanged();
}
public ArrayList<Seatnos> getSelected() {
return selected;
}
}
'''
SeatSelectionactivity.java
'''
public class SeatSelectionActivity extends AppCompatActivity {
RecyclerView recyclerView;
Activity activity = SeatSelectionActivity.this;
Button btnGetSelected,btnreset;
FirebaseDatabase database;
DatabaseReference ref;
SelectionAdapter selectionAdapter;
ArrayList<Seatnos> list;
Update update;
ChildEventListener mChildListner;
ValueEventListener mValueEventListner;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_seat_selection);
btnGetSelected = (Button) findViewById(R.id.btconfirm);
recyclerView=(RecyclerView) findViewById(R.id.viewseat);
list = new ArrayList<>();
String uid = getIntent().getStringExtra(UpdateAdapter.USER_KEY);
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("updates").child(uid);
selectionAdapter=new SelectionAdapter(this, list);
RecyclerView.LayoutManager layoutManager=new GridLayoutManager(this,4);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
mValueEventListner = new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
Update update =dataSnapshot.getValue(Update.class);
update.setUid(dataSnapshot.getKey());
int seat= Integer.parseInt(update.getSeat());
ArrayList<String> array = new ArrayList<String>(seat);
for(long i=0; i<seat; i++) {
array.add(String.valueOf(i));
Seatnos seatnos = new Seatnos();
seatnos.setTextno(""+(i+1));
if(i==0){
seatnos.setChecked(true);
}
list.add(seatnos);
}
recyclerView.setAdapter(selectionAdapter);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
};
databaseReference.addValueEventListener(mValueEventListner);
}
public void reset(View view) {
}
public void bookconfirm(View view) {
if (selectionAdapter.getSelected().size() > 0) {
//ArrayList<Integer> mlist = new ArrayList<>();
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < selectionAdapter.getSelected().size(); i++) {
stringBuilder.append(selectionAdapter.getSelected().get(i).getTextno());
stringBuilder.append("\n");
}
Toast.makeText(activity, String.format("Selected %d items", selectionAdapter.getSelected().size()), Toast.LENGTH_SHORT).show();
showToast(stringBuilder.toString().trim());
} else {
showToast("No Selection");
}
};
public void selectAll(View v) {
selectionAdapter.selectAll();
}
public void deselectAll(View v) {
selectionAdapter.clearSelected();
}
public void doAction(View v) {
Toast.makeText(activity, String.format("Selected %d items", selectionAdapter.getSelected().size()), Toast.LENGTH_SHORT).show();
}
private void showToast(String msg) {
Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
}
}
'''
model class
'''
public class Seatnos implements Serializable {
String textno;
String sid;
private boolean isChecked = false;
public Seatnos() {
}
public boolean isChecked() {
return isChecked;
}
public void setChecked(boolean checked) {
isChecked = checked;
}
public String getSid() {
return sid;
}
public void setSid(String sid) {
this.sid = sid;
}
public Seatnos(String textno) {
this.textno = textno;
}
public String getTextno() {
return textno;
}
public void setTextno(String textno) {
this.textno = textno;
}
}
'''
You would use shared preferences to save the state of the selected item:
Do this in onBindViewHolder:
#Override
public void onBindViewHolder(#NonNull final MygridViewHolder holder, final int position) {
final Seatnos seatnos = list.get(position);
holder.textView.setText(String.valueOf(position));
holder.textView.setText(seatnos.getTextno());
//read from preferences
SharedPreferences pref = getSharedPreferences("item", MODE_PRIVATE);
String state = pref.getString(String.valueOf(position)+"state", "default");
if(state.equals("selected")){
//selected
highlightView(holder);
}else{
//not selected
unhighlightView(holder);
}
//on click
holder.textView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (selected.contains(seatnos)) {
selected.remove(seatnos);
unhighlightView(holder);
//save state
SharedPreferences.Editor editor = getSharedPreferences("item", MODE_PRIVATE).edit();
editor.putString(String.valueOf(position)+"state", "not_selected");
editor.apply();
} else {
selected.add(seatnos);
highlightView(holder);
//save state
SharedPreferences.Editor editor = getSharedPreferences("item", MODE_PRIVATE).edit();
editor.putString(String.valueOf(position)+"state", "selected");
editor.apply();
}
}
});
......................
......................
......................
}
UPDATE:
Yes you should use the context passed to your adapter to access the shared prederences:
This:
getSharedPreferences("item", MODE_PRIVATE);
Becomes:
applicationContext.getSharedPreferences("item", MODE_PRIVATE);
This:
getSharedPreferences("item", MODE_PRIVATE).edit();
Becomes:
applicationContext.getSharedPreferences("item", MODE_PRIVATE).edit();
I'm using recycler view as a single child inside the swipe refresh layout. Initially, its not scrolling smoothly while loading data from webservice both upwards and downwards. But after first scroll, it scrolls smoothly. How to make it scroll smoothly at very first scroll itself.
private RecyclerView newsFeedList;
newsFeedList = (RecyclerView) view.findViewById(R.id.rv_feed_list);
newsFeedList.setHasFixedSize(true);
LinearLayoutManager llm = new LinearLayoutManager(getActivity());
llm.setOrientation(LinearLayoutManager.VERTICAL);
newsFeedList.setLayoutManager(llm);
newsFeedAdapter = new NewsFeedAdapter(getActivity(), new ArrayList<NewsFeedParser.NewsFeed>(), newsFeedList);
newsFeedList.setAdapter(newsFeedAdapter);
and updated recyclerview after getting response from web service by calling below method:
private void parseDataToNewsFeed(String response, boolean isLoadMore) {
Gson gson = new Gson();
NewsFeedParser newsFeedParser = gson.fromJson(response, NewsFeedParser.class);
if (newsFeedParser.data != null && newsFeedParser.data.size() > 0) {
if (isLoadMore) {
newsFeedAdapter.removeProgress(newsFeedAdapter.getItemCount());
newsFeedAdapter.addList(newsFeedParser.data);
} else {
currentPageCount = 1;
newsFeedAdapter.updateList(newsFeedParser.data);
}
} else {
newsFeedAdapter.updateList(newsFeedParser.data);
txtNoResult.setText(getString(R.string.no_clubs_socities_subscribed));
txtNoResult.setVisibility(View.VISIBLE);
}
}
Adaper class:
public class NewsFeedAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private final DisplayImageOptions options;
private Context context;
private ArrayList<NewsFeedParser.NewsFeed> itemList;
private int lastVisibleItem, totalItemCount, visibleThreshold = 2;
private boolean loading;
public OnLoadMoreListener onLoadMoreListener;
private OnItemClickListener itemClickListener;
// private ImageLoader mImageLoader;
private final int VIEW_ITEM = 1;
private final int VIEW_PROG = 0;
private long mLastClickTimeListViewItem = 0;
public NewsFeedAdapter(Context context, ArrayList<NewsFeedParser.NewsFeed> itemList, RecyclerView recyclerView) {
this.context = context;
this.itemList = itemList;
options = new DisplayImageOptions.Builder()
.showImageOnLoading(R.drawable.ic_default_news)
.showImageForEmptyUri(R.drawable.ic_default_news)
.showImageOnFail(R.drawable.ic_default_news)
.cacheInMemory(true)
.cacheOnDisk(true)
.considerExifParams(true)
.bitmapConfig(Bitmap.Config.RGB_565)
.build();
if (recyclerView.getLayoutManager() instanceof LinearLayoutManager) {
final LinearLayoutManager linearLayoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
totalItemCount = linearLayoutManager.getItemCount();
lastVisibleItem = linearLayoutManager.findLastVisibleItemPosition();
if (!loading && totalItemCount <= (lastVisibleItem + visibleThreshold)) {
if (onLoadMoreListener != null) {
onLoadMoreListener.onLoadMore();
}
loading = true;
}
}
});
}
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
RecyclerView.ViewHolder vh;
if (viewType == VIEW_ITEM) {
View itemView = LayoutInflater.from(context).inflate(R.layout.fragment_news_feed_trending_list_item, parent, false);
vh = new NewsFeedViewHolder(itemView);
} else {
View progView = LayoutInflater.from(context).inflate(R.layout.view_refresh_footer, parent, false);
vh = new ProgressViewHolder(progView);
}
return vh;
}
#Override
public int getItemViewType(int position) {
return itemList.get(position) != null ? VIEW_ITEM : VIEW_PROG;
}
#Override
public int getItemCount() {
return itemList.size();
}
#Override
public void onBindViewHolder(final RecyclerView.ViewHolder holder, final int position) {
if (holder instanceof NewsFeedViewHolder) {
final NewsFeedParser.NewsFeed singleItem = itemList.get(position);
((NewsFeedViewHolder) holder).txtNews.setText(Html.fromHtml(singleItem.title));
((NewsFeedViewHolder) holder).txtDays.setText(DateConversion.getStatusTiming(context, singleItem.modified));
((NewsFeedViewHolder) holder).imgNewsPhoto.setImageResource(R.drawable.ic_default_news);
if (singleItem.featured_image != null) {
if (singleItem.featured_image.attachment_meta != null) {
if (singleItem.featured_image.attachment_meta.sizes != null) {
if (singleItem.featured_image.attachment_meta.sizes.thumbnail != null) {
if (!TextUtils.isNullOrEmpty(singleItem.featured_image.attachment_meta.sizes.thumbnail.url)) {
ImageLoader.getInstance().displayImage(singleItem.featured_image.attachment_meta.sizes.thumbnail.url, ((NewsFeedViewHolder) holder).imgNewsPhoto, options);
} else {
if (!TextUtils.isNullOrEmpty(singleItem.featured_image.source)) {
ImageLoader.getInstance().displayImage(singleItem.featured_image.source, ((NewsFeedViewHolder) holder).imgNewsPhoto, options);
}
}
}
}
}
}
if (singleItem.read_status == 0) {
((NewsFeedViewHolder) holder).rlFeedItem.setBackgroundColor(ContextCompat.getColor(context, R.color.clr_news_feed_item_bg));
} else {
((NewsFeedViewHolder) holder).rlFeedItem.setBackgroundColor(ContextCompat.getColor(context, R.color.transparent));
}
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (SystemClock.elapsedRealtime() - mLastClickTimeListViewItem < 1000) {
return;
}
mLastClickTimeListViewItem = SystemClock.elapsedRealtime();
if (itemClickListener != null) {
itemClickListener.onItemClick(singleItem);
singleItem.read_status = 1;
notifyItemChanged(position);
}
}
});
} else {
((ProgressViewHolder) holder).progressBar.setLinearProgress(true);
}
}
public void addList(ArrayList<NewsFeedParser.NewsFeed> items) {
if (items == null) {
this.itemList.add(null);
} else {
for (NewsFeedParser.NewsFeed item : items) {
this.itemList.add(item);
}
}
notifyDataSetChanged();
}
public void updateList(ArrayList<NewsFeedParser.NewsFeed> items) {
if (items != null) {
this.itemList = items;
}
notifyDataSetChanged();
}
public void removeProgress(int itemCount) {
this.itemList.remove(itemCount - 1);
notifyItemRemoved(itemCount);
}
public static class NewsFeedViewHolder extends RecyclerView.ViewHolder {
USUTextView txtNews, txtDays;
ImageView imgNewsPhoto;
RelativeLayout rlFeedItem;
public NewsFeedViewHolder(View itemView) {
super(itemView);
txtNews = (USUTextView) itemView.findViewById(R.id.txt_news);
txtDays = (USUTextView) itemView.findViewById(R.id.txt_days);
imgNewsPhoto = (ImageView) itemView.findViewById(R.id.img_news_photo);
rlFeedItem = (RelativeLayout) itemView.findViewById(R.id.rl_feed_list_item);
}
}
public static class ProgressViewHolder extends RecyclerView.ViewHolder {
public ProgressWheel progressBar;
public ProgressViewHolder(View progView) {
super(progView);
progressBar = (ProgressWheel) progView.findViewById(R.id.progress_bar);
}
}
public void setLoaded() {
loading = false;
}
public void setOnLoadMoreListener(OnLoadMoreListener onLoadMoreListener) {
this.onLoadMoreListener = onLoadMoreListener;
}
public interface OnLoadMoreListener {
void onLoadMore();
}
public void setOnItemClickListener(OnItemClickListener recyclerClickListener) {
this.itemClickListener = recyclerClickListener;
}
public interface OnItemClickListener {
void onItemClick(NewsFeedParser.NewsFeed item);
}
}
Please suggest me any idea.....
I want to display a list in fragment. i am using a custom arraylist. it is giving me classcast exception. i searched for the soluo solvetion but it dosnt solve my problem. i am new to android so i have no idea how this.. can anyone help..
this is my Item class
public class Item {
public String item_name;
public String item_desc;
public String item_qty;
public Item(String item_name, String item_desc,String item_qty) {
super();
this.item_name = item_name;
this.item_desc = item_desc;
this.item_qty = item_qty;
}
public String getItem_name(){
return item_name;
}
public void setItem_name(String item_name)
{
this.item_name=item_name;
}
public String getItem_desc()
{
return item_desc;
}
public void setItem_desc(String item_desc)
{
this.item_desc=item_desc;
}
public String getItem_qty()
{
return item_qty;
}
public void setItem_qty(String item_qty) {
this.item_qty = item_qty;
}
}
this is my addstock fragment
public class AddStock extends Fragment {
EditText edit_item_name,edit_item_desc,edit_item_qty;
Button btn_save;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_add_stock, container, false);
edit_item_name = (EditText)rootView.findViewById(R.id.edittext_item_name);
edit_item_desc = (EditText) rootView.findViewById(R.id.editText_item_desc);
edit_item_qty = (EditText) rootView.findViewById(R.id.editText_item_qty);
btn_save = (Button) rootView.findViewById(R.id.button_Save);
MainActivity act=(MainActivity)this.getActivity();
final ArrayList stock = act.arrayList;
btn_save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String item_name=edit_item_name.getText().toString();
String item_desc=edit_item_desc.getText().toString();
String item_qty=edit_item_qty.getText().toString();
stock.add(item_name);
stock.add(item_desc);
stock.add(item_qty);
Toast.makeText(AddStock.this.getActivity(), "Saved", Toast.LENGTH_LONG).show();
}
});
return rootView;
}
}
this is my viewstock fragment
public class ViewStock extends Fragment {
public ViewStock() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootview= inflater.inflate(R.layout.fragment_view_stock, container, false);
ListView listview = (ListView)rootview.findViewById(R.id.list);
// Context mCtx = getActivity().getApplicationContext();
MainActivity act=(MainActivity)this.getActivity();
ItemAdapter adapter = new ItemAdapter(getActivity(),R.layout.list_item,act.arrayList);
listview.setAdapter(adapter);
return rootview;
}
}
this is my main activity
Public class MainActivity extends AppCompatActivity {
private Toolbar mToolbar;
private DrawerLayout mDrawerLayout;
NavigationView mNavigationView;
FrameLayout mContentFrame;
FragmentManager fragmentManager;
private static final String PREFERENCES_FILE = "mymaterialapp_settings";
private static final String PREF_USER_LEARNED_DRAWER = "navigation_drawer_learned";
private static final String STATE_SELECTED_POSITION = "selected_navigation_drawer_position";
private boolean mUserLearnedDrawer;
private boolean mFromSavedInstanceState;
private int mCurrentSelectedPosition;
public ArrayList<Item> arrayList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_nav_drawer);
setUpToolbar();
arrayList=new ArrayList<Item>();
mDrawerLayout = (DrawerLayout) findViewById(R.id.nav_drawer);
mUserLearnedDrawer = Boolean.valueOf(readSharedSetting(this, PREF_USER_LEARNED_DRAWER, "false"));
if (savedInstanceState != null) {
mCurrentSelectedPosition = savedInstanceState.getInt(STATE_SELECTED_POSITION);
mFromSavedInstanceState = true;
}
setUpNavDrawer();
mNavigationView = (NavigationView) findViewById(R.id.nav_view);
mContentFrame = (FrameLayout) findViewById(R.id.nav_contentframe);
mNavigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
Fragment newFragment;
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
menuItem.setChecked(true);
switch (menuItem.getItemId()) {
case R.id.navigation_item_1:
newFragment = new AddStock();
transaction.replace(R.id.nav_contentframe, newFragment);
transaction.addToBackStack(null);
transaction.commit();
mCurrentSelectedPosition = 0;
mDrawerLayout.closeDrawers();
return true;
case R.id.navigation_item_2:
newFragment = new ViewStock();
transaction.replace(R.id.nav_contentframe, newFragment);
transaction.addToBackStack(null);
transaction.commit();
mCurrentSelectedPosition = 1;
return true;
default:
return true;
}
}
});
//fragmentManager.beginTransaction().replace(R.id.nav_contentframe, fragment).commit();
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(STATE_SELECTED_POSITION, mCurrentSelectedPosition);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
mCurrentSelectedPosition = savedInstanceState.getInt(STATE_SELECTED_POSITION, 0);
Menu menu = mNavigationView.getMenu();
menu.getItem(mCurrentSelectedPosition).setChecked(true);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_settings:
return true;
}
return super.onOptionsItemSelected(item);
}
private void setUpToolbar() {
mToolbar = (Toolbar) findViewById(R.id.toolbar);
if (mToolbar != null) {
setSupportActionBar(mToolbar);
}
}
private void setUpNavDrawer() {
if (mToolbar != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
mToolbar.setNavigationIcon(R.drawable.ic_drawer);
mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mDrawerLayout.openDrawer(GravityCompat.START);
}
});
}
if (!mUserLearnedDrawer) {
mDrawerLayout.openDrawer(GravityCompat.START);
mUserLearnedDrawer = true;
saveSharedSetting(this, PREF_USER_LEARNED_DRAWER, "true");
}
}
public static void saveSharedSetting(Context ctx, String settingName, String settingValue) {
SharedPreferences sharedPref = ctx.getSharedPreferences(PREFERENCES_FILE, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString(settingName, settingValue);
editor.apply();
}
public static String readSharedSetting(Context ctx, String settingName, String defaultValue) {
SharedPreferences sharedPref = ctx.getSharedPreferences(PREFERENCES_FILE, Context.MODE_PRIVATE);
return sharedPref.getString(settingName, defaultValue);
}
}
this is my ItemAdapter
public class ItemAdapter extends ArrayAdapter<Item> {
Context context;
public ItemAdapter(Context context, int resourceId,
ArrayList<Item> items) {
super(context, resourceId, items);
this.context = context;
}
/* public int getCount() {
return items.size();
}
public Item getItem(int position) {
return items.get(position);
}
public long getItemId(int position) {
return position;
}
*/
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
Item rowItem = getItem(position);
LayoutInflater mInflater = (LayoutInflater) context
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
holder = new ViewHolder();
convertView = mInflater.inflate(R.layout.list_item, null);
holder.txtItemName = (TextView) convertView.findViewById(R.id.txt_item_name);
holder.txtItemDesc = (TextView) convertView.findViewById(R.id.txt_item_desc);
holder.txtItemQty = (TextView) convertView.findViewById(R.id.txt_item_qty);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.txtItemName.setText(rowItem.getItem_name());
holder.txtItemDesc.setText(rowItem.getItem_desc());
holder.txtItemQty.setText(rowItem.getItem_qty());
return convertView;
}
private class ViewHolder {
TextView txtItemName;
TextView txtItemDesc;
TextView txtItemQty;
}
}
this is the exception m getting
java.lang.ClassCastException: java.lang.String cannot be cast to com.example.owner.stock.Item
at com.example.owner.stock.ItemAdapter.getView(ItemAdapter.java:60)
at android.widget.AbsListView.obtainView(AbsListView.java:2344)
at android.widget.ListView.makeAndAddView(ListView.java:1864)
at android.widget.ListView.fillDown(ListView.java:698)
at android.widget.ListView.fillFromTop(ListView.java:759)
at android.widget.ListView.layoutChildren(ListView.java:1673)
at android.widget.AbsListView.onLayout(AbsListView.java:2148)
at android.view.View.layout(View.java:15614)
at android.view.ViewGroup.layout(ViewGroup.java:4968)
at android.widget.FrameLayout.layoutChildren(FrameLayout.java:573)
at android.widget.FrameLayout.onLayout(FrameLayout.java:508)
at android.view.View.layout(View.java:15614)
at android.view.ViewGroup.layout(ViewGroup.java:4968)
at android.widget.FrameLayout.layoutChildren(FrameLayout.java:573)
at android.widget.FrameLayout.onLayout(FrameLayout.java:508)
at android.view.View.layout(View.java:15614)
at android.view.ViewGroup.layout(ViewGroup.java:4968)
at android.widget.RelativeLayout.onLayout(RelativeLayout.java:1076)
at android.view.View.layout(View.java:15614)
at android.view.ViewGroup.layout(ViewGroup.java:4968)
at android.support.v4.widget.DrawerLayout.onLayout(DrawerLayout.java:907)
at android.view.View.layout(View.java:15614)
at android.view.ViewGroup.layout(ViewGroup.java:4968)
at android.widget.FrameLayout.layoutChildren(FrameLayout.java:573)
at android.widget.FrameLayout.onLayout(FrameLayout.java:508)
at android.view.View.layout(View.java:15614)
at android.view.ViewGroup.layout(ViewGroup.java:4968)
at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1703)
at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1557)
at android.widget.LinearLayout.onLayout(LinearLayout.java:1466)
at android.view.View.layout(View.java:15614)
at android.view.ViewGroup.layout(ViewGroup.java:4968)
at android.widget.FrameLayout.layoutChildren(FrameLayout.java:573)
at android.widget.FrameLayout.onLayout(FrameLayout.java:508)
at android.view.View.layout(View.java:15614)
at android.view.ViewGroup.layout(ViewGroup.java:4968)
at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1703)
at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1557)
at android.widget.LinearLayout.onLayout(LinearLayout.java:1466)
at android.view.View.layout(View.java:15614)
at android.view.ViewGroup.layout(ViewGroup.java:4968)
at android.widget.FrameLayout.layoutChildren(FrameLayout.java:573)
at android.widget.FrameLayout.onLayout(FrameLayout.java:508)
at android.view.View.layout(View.java:15614)
at android.view.ViewGroup.layout(ViewGroup.java:4968)
at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:2102)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1859)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1077)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5884)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:767)
at android.view.Choreographer.doCallbacks(Choreographer.java:580)
at android.view.Choreographer.doFrame(Choreographer.java:550)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:753)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5312)
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:901)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:696)
07-22 23:34:00.334 20992-20992/? E/AndroidRuntime﹕ FATAL EXCEPTION: main
You are adding String objects to a list that is typed to take Item objects.
Instead of:
stock.add(someString);
stock.add(someString);
stock.add(someString);
Do
stock.add(new Item(someString, someString, someString));
I designed my service as it will make an alarm when user will go to a certain location.
But it crashes when it go to the certain making the alarm.
public class CheckDestinationService extends Service {
Calendar calender;
double late,longe;
int dis;
String loc;
private LocationManager mLocationManager = null;
private static final int LOCATION_INTERVAL = 0;
private static final float LOCATION_DISTANCE = 0;
private class LocationListener implements android.location.LocationListener {
Location mLastLocation;
public LocationListener(String provider) {
mLastLocation = new Location(provider);
}
public void onLocationChanged(Location location) {
mLastLocation.set(location);
final double currlat;
final double currlong;
float[] DistanceArray = new float[1];
currlat = location.getLatitude();
currlong = location.getLongitude();
android.location.Location.distanceBetween(currlat,currlong,late,longe,DistanceArray);
float Distance = DistanceArray[0];
//Toast.makeText(getApplicationContext(), "asdf "+String.valueOf(Distance), Toast.LENGTH_SHORT).show();
Log.d("asdfasdas", String.valueOf(currlat)+","+String.valueOf(currlong)+" "+String.valueOf(Distance));
if (Distance<=dis && Distance!=0 && dis!=0)
{
dis = 0;
Intent intent = new Intent(getBaseContext(), AlarmReceiver.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Toast.makeText(getApplicationContext(), "Reached "+String.valueOf(Distance), Toast.LENGTH_SHORT).show();
PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(),0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager am = (AlarmManager)getSystemService(Activity.ALARM_SERVICE);
am.set(AlarmManager.RTC_WAKEUP, calender.getTimeInMillis(),pendingIntent);
//stopSelf();
}
/*final Handler handler = new Handler();
Runnable r = new Runnable() {
public void run() {
// TODO Auto-generated method stub
Intent intent = null;
intent.putExtra("lat", currlat);
intent.putExtra("long", currlong);
intent.putExtra("dis", dis);
intent.putExtra("loc", loc);
Toast.makeText(getApplicationContext(), "Sending", Toast.LENGTH_SHORT).show();
sendBroadcast(intent);
handler.postDelayed(this, 1000);
}
};
handler.postDelayed(r, 1000);*/
}
public void onProviderDisabled(String provider) {
}
public void onProviderEnabled(String provider) {
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
LocationListener[] mLocationListeners = new LocationListener[] {
new LocationListener(LocationManager.GPS_PROVIDER),
new LocationListener(LocationManager.NETWORK_PROVIDER)
};
#Override
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
late = intent.getDoubleExtra("lat", 0);
longe = intent.getDoubleExtra("long", 0);
dis = intent.getIntExtra("dis", 0);
loc = intent.getStringExtra("loc");
Toast.makeText(getApplicationContext(), "Destination Set to: "+loc+
" and Minimum Distance: "+
String.valueOf(dis) , Toast.LENGTH_SHORT).show();
return START_STICKY;
}
#Override
public void onCreate() {
initializeLocationManager();
try {
mLocationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, LOCATION_INTERVAL, LOCATION_DISTANCE,
mLocationListeners[1]);
} catch (java.lang.SecurityException ex) {
} catch (IllegalArgumentException ex) {
}
try {
mLocationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, LOCATION_INTERVAL, LOCATION_DISTANCE,
mLocationListeners[0]);
} catch (java.lang.SecurityException ex) {
} catch (IllegalArgumentException ex) {
}
}
#Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(getApplicationContext(), "Service Destroyed", Toast.LENGTH_SHORT).show();
if (mLocationManager != null) {
for (int i = 0; i < mLocationListeners.length; i++) {
try {
mLocationManager.removeUpdates(mLocationListeners[i]);
} catch (Exception ex) {
}
}
}
}
private void initializeLocationManager() {
if (mLocationManager == null) {
mLocationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
}
}
}
and my AlarmReceiver class is
public class AlarmReceiver extends Activity {
private MediaPlayer mMediaPlayer;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.alarmreceiver);
Button stopAlarm = (Button) findViewById(R.id.stopAlarm);
stopAlarm.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View arg0, MotionEvent arg1) {
stopService(new Intent(AlarmReceiver.this, CheckDestinationService.class));
mMediaPlayer.stop();
finish();
return false;
}
});
playSound(this, getAlarmUri());
}
private void playSound(Context context, Uri alert) {
mMediaPlayer = new MediaPlayer();
try {
mMediaPlayer.setDataSource(context, alert);
final AudioManager audioManager = (AudioManager) context
.getSystemService(Context.AUDIO_SERVICE);
if (audioManager.getStreamVolume(AudioManager.STREAM_ALARM) != 0) {
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_ALARM);
mMediaPlayer.prepare();
mMediaPlayer.start();
}
} catch (IOException e) {
System.out.println("OOPS");
}
}
//Get an alarm sound. Try for an alarm. If none set, try notification,
//Otherwise, ringtone.
private Uri getAlarmUri() {
Uri alert = RingtoneManager
.getDefaultUri(RingtoneManager.TYPE_ALARM);
if (alert == null) {
alert = RingtoneManager
.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
if (alert == null) {
alert = RingtoneManager
.getDefaultUri(RingtoneManager.TYPE_RINGTONE);
}
}
return alert;
}
#Override
public void onBackPressed() {
//MainActivity.iMinDistance = 0;
stopService(new Intent(AlarmReceiver.this, CheckDestinationService.class));
mMediaPlayer.stop();
finish();
}
}
I tested AlarmReceiver class from other activites and it worked properly
but it not working from the service.
please help!!
initalize Calendar
calender = Calendar.getInstance()