This is my code
package com.packages.digifarm.ui.dashboard;
import android.content.Intent;
import android.os.Bundle;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.cardview.widget.CardView;
import androidx.fragment.app.Fragment;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.packages.digifarm.KelembabanTanahAnalisisActivity;
import com.packages.digifarm.KelembabanUdaraAnalisisActivity;
import com.packages.digifarm.LevelKetinggianAirAnalisisActivity;
import com.packages.digifarm.R;
import com.packages.digifarm.SuhuAnalisisActivity;
public class DashboardFragment extends Fragment {
TextView tv_water_level_value, tv_temperature_value, tv_moisture_value, tv_humidity_value;
TextView tv_water_level_stats, tv_temperature_stats, tv_moisture_stats, tv_humidity_stats, tv_weather_stats;
ImageView ic_water, ic_weather_stats;
TextView tv_btn_show_detail_water_level, tv_btn_show_detail_soil_moisture, tv_btn_show_detail_temperature, tv_btn_show_detail_humidity;
CardView water_indicator;
ViewGroup.LayoutParams layoutParams;
DatabaseReference Reference;
String water_level_value, temperature_value, moisture_value, humidity_value, light_value;
#Override
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_dashboard, container, false);
tv_water_level_value = view.findViewById(R.id.tv_water_level_value);
tv_temperature_value = view.findViewById(R.id.tv_temperature_value);
tv_moisture_value = view.findViewById(R.id.tv_moisture_value);
tv_humidity_value = view.findViewById(R.id.tv_humidity_value);
tv_water_level_stats = view.findViewById(R.id.tv_water_level_stats);
tv_temperature_stats = view.findViewById(R.id.tv_temperature_stats);
tv_moisture_stats = view.findViewById(R.id.tv_moisture_stats);
tv_humidity_stats = view.findViewById(R.id.tv_humidity_stats);
tv_weather_stats = view.findViewById(R.id.tv_weather_stats);
water_indicator = view.findViewById(R.id.water_indicator);
ic_water = view.findViewById(R.id.ic_water);
ic_weather_stats = view.findViewById(R.id.ic_weather_stats);
Reference = FirebaseDatabase.getInstance().getReference("Current Data");
Reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
water_level_value = snapshot.child("Level Ketinggian Air").getValue().toString();
temperature_value = snapshot.child("Suhu").getValue().toString();
moisture_value = snapshot.child("Kelembaban Tanah").getValue().toString();
humidity_value = snapshot.child("Kelembaban Udara").getValue().toString();
light_value = snapshot.child("Cahaya").getValue().toString();
tv_water_level_value.setText(water_level_value + "%");
tv_temperature_value.setText(temperature_value + "°C");
tv_moisture_value.setText(moisture_value + "%");
tv_humidity_value.setText(humidity_value + "%");
layoutParams = (ViewGroup.LayoutParams)water_indicator.getLayoutParams();
layoutParams.height = Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, Integer.parseInt(water_level_value), getResources().getDisplayMetrics()));
water_indicator.setLayoutParams(layoutParams);
if(Integer.parseInt(water_level_value) < 30){
tv_water_level_value.setTextColor(getResources().getColor(R.color.red_danger));
tv_water_level_stats.setText("Tersisa Sedikit");
tv_water_level_stats.setTextColor(getResources().getColor(R.color.red_danger));
water_indicator.setCardBackgroundColor(getResources().getColor(R.color.red_danger));
ic_water.setImageResource(R.drawable.ic_water_red);
}
else if(Integer.parseInt(water_level_value) >= 30 && Integer.parseInt(water_level_value) <= 50){
tv_water_level_value.setTextColor(getResources().getColor(R.color.yellow_warning));
tv_water_level_stats.setText("Cukup Banyak");
tv_water_level_stats.setTextColor(getResources().getColor(R.color.yellow_warning));
water_indicator.setCardBackgroundColor(getResources().getColor(R.color.yellow_warning));
ic_water.setImageResource(R.drawable.ic_water_yellow);
}
else if(Integer.parseInt(water_level_value) > 50 && Integer.parseInt(water_level_value) <= 75){
tv_water_level_value.setTextColor(getResources().getColor(R.color.teal_200));
tv_water_level_stats.setText("Lumayan Banyak");
tv_water_level_stats.setTextColor(getResources().getColor(R.color.teal_200));
water_indicator.setCardBackgroundColor(getResources().getColor(R.color.teal_200));
ic_water.setImageResource(R.drawable.ic_water_blue);
}
else if(Integer.parseInt(water_level_value) > 75){
tv_water_level_value.setTextColor(getResources().getColor(R.color.teal_200));
tv_water_level_stats.setText("Lumayan Banyak");
tv_water_level_stats.setTextColor(getResources().getColor(R.color.teal_200));
water_indicator.setCardBackgroundColor(getResources().getColor(R.color.teal_200));
ic_water.setImageResource(R.drawable.ic_water_blue);
}
if(Integer.parseInt(temperature_value) < 26){
tv_temperature_value.setTextColor(getResources().getColor(R.color.teal_200));
tv_temperature_stats.setText("Dingin");
tv_temperature_stats.setTextColor(getResources().getColor(R.color.teal_200));
}
else if(Integer.parseInt(temperature_value) >= 26 && Integer.parseInt(temperature_value) <= 34){
tv_temperature_value.setTextColor(getResources().getColor(R.color.secondary_green));
tv_temperature_stats.setText("Normal");
tv_temperature_stats.setTextColor(getResources().getColor(R.color.secondary_green));
}
else if(Integer.parseInt(temperature_value) > 34){
tv_temperature_value.setTextColor(getResources().getColor(R.color.red_danger));
tv_temperature_stats.setText("Panas");
tv_temperature_stats.setTextColor(getResources().getColor(R.color.red_danger));
}
if(Integer.parseInt(humidity_value) < 20){
tv_humidity_value.setTextColor(getResources().getColor(R.color.red_danger));
tv_humidity_stats.setText("Kering");
tv_humidity_stats.setTextColor(getResources().getColor(R.color.red_danger));
}
else if(Integer.parseInt(humidity_value) >= 20 && Integer.parseInt(humidity_value) <= 40){
tv_humidity_value.setTextColor(getResources().getColor(R.color.yellow_warning));
tv_humidity_stats.setText("Kering");
tv_humidity_stats.setTextColor(getResources().getColor(R.color.yellow_warning));
}
else if(Integer.parseInt(humidity_value) > 40 && Integer.parseInt(humidity_value) <= 70){
tv_humidity_value.setTextColor(getResources().getColor(R.color.secondary_green));
tv_humidity_stats.setText("Normal");
tv_humidity_stats.setTextColor(getResources().getColor(R.color.secondary_green));
}
else if(Integer.parseInt(humidity_value) > 70){
tv_humidity_value.setTextColor(getResources().getColor(R.color.teal_200));
tv_humidity_stats.setText("Lembab");
tv_humidity_stats.setTextColor(getResources().getColor(R.color.teal_200));
}
if(Integer.parseInt(moisture_value) < 20){
tv_moisture_value.setTextColor(getResources().getColor(R.color.red_danger));
tv_moisture_stats.setText("Kering");
tv_moisture_stats.setTextColor(getResources().getColor(R.color.red_danger));
}
else if(Integer.parseInt(moisture_value) >= 20 && Integer.parseInt(moisture_value) <= 40){
tv_moisture_value.setTextColor(getResources().getColor(R.color.yellow_warning));
tv_moisture_stats.setText("Kering");
tv_moisture_stats.setTextColor(getResources().getColor(R.color.yellow_warning));
}
else if(Integer.parseInt(moisture_value) > 40 && Integer.parseInt(moisture_value) <= 70){
tv_moisture_value.setTextColor(getResources().getColor(R.color.secondary_green));
tv_moisture_stats.setText("Normal");
tv_moisture_stats.setTextColor(getResources().getColor(R.color.secondary_green));
}
else if(Integer.parseInt(moisture_value) > 70){
tv_moisture_value.setTextColor(getResources().getColor(R.color.teal_200));
tv_moisture_stats.setText("Lembab");
tv_moisture_stats.setTextColor(getResources().getColor(R.color.teal_200));
}
if(Integer.parseInt(light_value) < 100){
ic_weather_stats.setImageResource(R.drawable.ic_cuaca_cerah_berawan);
tv_weather_stats.setText("Cerah Berawan");
tv_weather_stats.setTextColor(getResources().getColor(R.color.yellow_warning));
}
else if(Integer.parseInt(light_value) >= 100){
ic_weather_stats.setImageResource(R.drawable.ic_cuaca_cerah);
tv_weather_stats.setText("Cerah");
tv_weather_stats.setTextColor(getResources().getColor(R.color.yellow_warning));
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
tv_btn_show_detail_water_level = view.findViewById(R.id.tv_btn_show_detail_water_level);
tv_btn_show_detail_water_level.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(getActivity().getApplicationContext(), LevelKetinggianAirAnalisisActivity.class);
startActivity(i);
}
});
tv_btn_show_detail_soil_moisture = view.findViewById(R.id.tv_btn_show_detail_soil_moisture);
tv_btn_show_detail_soil_moisture.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent k = new Intent(getActivity().getApplicationContext(), KelembabanTanahAnalisisActivity.class);
startActivity(k);
}
});
tv_btn_show_detail_humidity = view.findViewById(R.id.tv_btn_show_detail_humidity);
tv_btn_show_detail_humidity.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent h = new Intent(getActivity().getApplicationContext(), KelembabanUdaraAnalisisActivity.class);
startActivity(h);
}
});
tv_btn_show_detail_temperature = view.findViewById(R.id.tv_btn_show_detail_temperature);
tv_btn_show_detail_temperature.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent_data = new Intent(getActivity().getApplicationContext(), SuhuAnalisisActivity.class);
startActivity(intent_data);
}
});
// Inflate the layout for this fragment
return view;
}
#Override
public void onResume() {
super.onResume();
TextView txt_adds1 = getActivity().findViewById(R.id.txt_adds1);
TextView txt_adds2 = getActivity().findViewById(R.id.txt_adds2);
ImageView imgview_bg_appbar = getActivity().findViewById(R.id.imgview_bg_appbar);
imgview_bg_appbar.setImageResource(R.drawable.bg_appbar_dashboard);
txt_adds1.setText("Berkebun kini lebih mudah dengan");
txt_adds2.setText("digiFarm");
txt_adds2.setTextSize(TypedValue.COMPLEX_UNIT_PT, 12);
}
}
I have an error like this
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.packages.digifarm, PID: 22408
java.lang.IllegalStateException: Fragment DashboardFragment{3b25dc9} (18f94298-cd27-4447-9c7e-59cb2f952f50) not attached to a context.
at androidx.fragment.app.Fragment.requireContext(Fragment.java:900)
at androidx.fragment.app.Fragment.getResources(Fragment.java:964)
at com.packages.digifarm.ui.dashboard.DashboardFragment$1.onDataChange(DashboardFragment.java:82)
at com.google.firebase.database.core.ValueEventRegistration.fireEvent(ValueEventRegistration.java:75)
at com.google.firebase.database.core.view.DataEvent.fire(DataEvent.java:63)
at com.google.firebase.database.core.view.EventRaiser$1.run(EventRaiser.java:55)
at android.os.Handler.handleCallback(Handler.java:883)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:237)
at android.app.ActivityThread.main(ActivityThread.java:7948)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1075)
Related
I'm doing a Simple Media Recorder/Player App and the recording part is successfully done. But now I'm having problems with the media player's part. Let me tell you the issues:
When I try to play a media file with the Media Player it says a preparing error like this:
java.io.IOException: Prepare failed.: status=0x1
How can I solve this problem?
My Three Classes:
-RecordFragment.java:
import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.media.MediaRecorder;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.core.content.ContextCompat;
import androidx.core.content.res.ResourcesCompat;
import androidx.fragment.app.Fragment;
import android.os.Environment;
import android.os.SystemClock;
import android.provider.Settings;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Chronometer;
import android.widget.TextView;
import android.widget.Toast;
import com.airbnb.lottie.LottieAnimationView;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.venomapps.voicerecorder.R;
import com.venomapps.voicerecorder.Utils.Constants;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
public class RecordFragment extends Fragment {
private TextView textViewInformation;
private FloatingActionButton floatingActionButtonStartRecording;
private FloatingActionButton floatingActionButtonFinishRecording;
private FloatingActionButton floatingActionButtonCancelRecording;
private int recordingStatus = 0;
private String fileName = "";
private Context context;
String[] permissions = {Manifest.permission.RECORD_AUDIO, Manifest.permission.WRITE_EXTERNAL_STORAGE};
private MediaRecorder mediaRecorder;
private String outPutFilePath;
private Chronometer chronometerRecord;
private boolean running;
private long pauseOffset;
private LottieAnimationView lottieAnimationViewVoice;
public RecordFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_record, container, false);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
context = getActivity();
bindUI(view);
setListeners();
}
private void bindUI(View view) {
textViewInformation = view.findViewById(R.id.textViewInformation);
floatingActionButtonStartRecording = view.findViewById(R.id.floatingActionButtonStartRecording);
floatingActionButtonFinishRecording = view.findViewById(R.id.floatingActionButtonFinishRecording);
floatingActionButtonCancelRecording = view.findViewById(R.id.floatingActionButtonCancelRecording);
chronometerRecord = view.findViewById(R.id.chronometerRecord);
lottieAnimationViewVoice = view.findViewById(R.id.lottieAnimationViewVoice);
}
private void setListeners() {
floatingActionButtonStartRecording.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (ContextCompat.checkSelfPermission(context,
Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(context,
Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED) {
switch (recordingStatus) {
case 0:
startRecording();
break;
case 1:
if (Build.VERSION.SDK_INT >= 24) {
pauseRecording();
} else {
finishRecording();
}
break;
case 2:
resumeRecording();
case 3:
break;
}
} else {
askPermissions();
}
}
});
floatingActionButtonFinishRecording.setOnClickListener(new View.OnClickListener() {
#SuppressLint("SetTextI18n")
#Override
public void onClick(View view) {
if (recordingStatus == 1 || recordingStatus == 2) {
finishRecording();
} else {
Toast.makeText(getActivity(), getString(R.string.not_recording), Toast.LENGTH_SHORT).show();
}
}
});
floatingActionButtonCancelRecording.setOnClickListener(new View.OnClickListener() {
#SuppressLint("SetTextI18n")
#Override
public void onClick(View view) {
if (recordingStatus == 1 || recordingStatus == 2) {
cancelRecording();
} else {
Toast.makeText(getActivity(), getString(R.string.not_recording), Toast.LENGTH_SHORT).show();
}
}
});
chronometerRecord.setOnChronometerTickListener(new Chronometer.OnChronometerTickListener() {
#Override
public void onChronometerTick(Chronometer chronometer) {
long time = SystemClock.elapsedRealtime() - chronometer.getBase();
int h = (int) (time / 3600000);
int m = (int) (time - h * 3600000) / 60000;
int s = (int) (time - h * 3600000 - m * 60000) / 1000;
String t = (h < 10 ? "0" + h : h) + ":" + (m < 10 ? "0" + m : m) + ":" + (s < 10 ? "0" + s : s);
chronometer.setText(t);
}
});
}
#SuppressLint("SetTextI18n")
private void startRecording() {
String basePath = Environment.getExternalStorageDirectory().toString();
String date = getCurrentDateFormatted();
String myDirectory = "Voice Recorder";
fileName = getString(R.string.recording_file) + date;
fileName = fileName.replace(" ", "");
fileName = fileName.replace("|", "");
fileName = fileName + ".mp3";
outPutFilePath = basePath + File.separator + myDirectory + File.separator + fileName;
String filePath = basePath + File.separator + myDirectory;
File newFolder = new File(filePath);
if (!newFolder.exists()) {
boolean createFolder = newFolder.mkdirs();
if (createFolder) {
Log.d("VOICE_RECORDER", "Created folder successfully!");
}
}
recordingStatus = 1;
mediaRecorder = new MediaRecorder();
if (Build.VERSION.SDK_INT >= 24) {
floatingActionButtonStartRecording.setImageDrawable(ResourcesCompat.getDrawable(getResources(), R.drawable.ic_pause_orange, null));
} else {
floatingActionButtonStartRecording.setImageDrawable(ResourcesCompat.getDrawable(getResources(), R.drawable.ic_stop_red, null));
}
textViewInformation.setText(getString(R.string.recording));
lottieAnimationViewVoice.playAnimation();
lottieAnimationViewVoice.setVisibility(View.VISIBLE);
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
mediaRecorder.setOutputFile(outPutFilePath);
mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
mediaRecorder.setAudioEncodingBitRate(16 * 44100);
mediaRecorder.setAudioSamplingRate(44100);
try {
mediaRecorder.prepare();
mediaRecorder.start();
if (!running) {
chronometerRecord.setVisibility(View.VISIBLE);
chronometerRecord.setBase(SystemClock.elapsedRealtime());
chronometerRecord.start();
running = true;
}
} catch (Exception e) {
e.printStackTrace();
}
}
private void pauseRecording() {
if (Build.VERSION.SDK_INT >= 24) {
mediaRecorder.pause();
}
if (running) {
chronometerRecord.stop();
pauseOffset = SystemClock.elapsedRealtime() - chronometerRecord.getBase();
running = false;
}
lottieAnimationViewVoice.cancelAnimation();
lottieAnimationViewVoice.setFrame(0);
lottieAnimationViewVoice.setVisibility(View.INVISIBLE);
recordingStatus = 2;
floatingActionButtonStartRecording.setImageDrawable(ResourcesCompat.getDrawable(getResources(), R.drawable.ic_play_green, null));
textViewInformation.setText(getString(R.string.tap_to_resume));
Toast.makeText(context, getString(R.string.paused), Toast.LENGTH_SHORT).show();
}
private void resumeRecording() {
if (Build.VERSION.SDK_INT >= 24) {
mediaRecorder.resume();
}
chronometerRecord.setBase(SystemClock.elapsedRealtime() - pauseOffset);
chronometerRecord.start();
lottieAnimationViewVoice.playAnimation();
lottieAnimationViewVoice.setVisibility(View.VISIBLE);
recordingStatus = 1;
floatingActionButtonStartRecording.setImageDrawable(ResourcesCompat.getDrawable(getResources(), R.drawable.ic_pause_orange, null));
textViewInformation.setText(getString(R.string.recording));
Toast.makeText(context, getString(R.string.resume), Toast.LENGTH_SHORT).show();
}
#SuppressLint("SetTextI18n")
private void finishRecording() {
chronometerRecord.setVisibility(View.INVISIBLE);
chronometerRecord.stop();
chronometerRecord.setBase(SystemClock.elapsedRealtime());
pauseOffset = 0;
mediaRecorder.stop();
mediaRecorder = null;
recordingStatus = 3;
floatingActionButtonStartRecording.setImageDrawable(ResourcesCompat.getDrawable(getResources(), R.drawable.ic_app, null));
Toast.makeText(context, getString(R.string.saved) + " " + fileName, Toast.LENGTH_LONG).show();
textViewInformation.setText(getString(R.string.tap_to_record));
lottieAnimationViewVoice.cancelAnimation();
lottieAnimationViewVoice.setFrame(0);
lottieAnimationViewVoice.setVisibility(View.INVISIBLE);
recordingStatus = 0;
}
#SuppressLint("SetTextI18n")
private void cancelRecording() {
chronometerRecord.setVisibility(View.INVISIBLE);
chronometerRecord.stop();
chronometerRecord.setBase(SystemClock.elapsedRealtime());
pauseOffset = 0;
try {
mediaRecorder.stop();
} catch (RuntimeException e) {
e.printStackTrace();
mediaRecorder = null;
mediaRecorder = new MediaRecorder();
} finally {
if (mediaRecorder != null) {
mediaRecorder = null;
}
}
File file = new File(outPutFilePath);
if (file.exists()) {
boolean deleted = file.delete();
if (deleted) {
Log.d("Voice Recorder", "Deleted file successfully!");
}
}
recordingStatus = 3;
floatingActionButtonStartRecording.setImageDrawable(ResourcesCompat.getDrawable(getResources(), R.drawable.ic_app, null));
Toast.makeText(context, getString(R.string.cancelled) + " " + fileName, Toast.LENGTH_LONG).show();
textViewInformation.setText(getString(R.string.tap_to_record));
lottieAnimationViewVoice.cancelAnimation();
lottieAnimationViewVoice.setFrame(0);
lottieAnimationViewVoice.setVisibility(View.INVISIBLE);
recordingStatus = 0;
}
private String getCurrentDateFormatted() {
return new SimpleDateFormat("dd-MM-yy|hh:mm:ss", Locale.getDefault()).format(new Date());
}
private void askPermissions() {
if (ContextCompat.checkSelfPermission(context,
Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(context,
Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {
assert getParentFragment() != null;
requestPermissions(permissions, Constants.RECORD_AUDIO_AND_WRITE_EXTERNAL_STORAGE_PERMISSION_REQUEST_CODE);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull final String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (ContextCompat.checkSelfPermission(context,
Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(context,
Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(context, getString(R.string.permission_granted), Toast.LENGTH_SHORT).show();
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setMessage(getString(R.string.no_read_permission))
.setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
if (ContextCompat.checkSelfPermission(context,
Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(context,
Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(permissions, Constants.RECORD_AUDIO_AND_WRITE_EXTERNAL_STORAGE_PERMISSION_REQUEST_CODE);
}
}
}).setNegativeButton(getString(R.string.go_to_settings), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent();
intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
Uri uri = Uri.fromParts("package", "com.venomapps.voicerecorder", null);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
intent.setData(uri);
context.startActivity(intent);
requireActivity().finish();
}
});
builder.create();
builder.show();
}
}
}
PlaylistFragment.java:
import android.content.Context;
import android.media.AudioAttributes;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.os.Environment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.google.android.material.bottomsheet.BottomSheetBehavior;
import com.venomapps.voicerecorder.Adapters.PlaylistAdapter;
import com.venomapps.voicerecorder.R;
import java.io.File;
import java.io.IOException;
public class PlaylistFragment extends Fragment implements PlaylistAdapter.onItemListClick {
private BottomSheetBehavior bottomSheetBehavior;
private RecyclerView recyclerViewPlaylist;
private File[] files;
private PlaylistAdapter playlistAdapter;
private MediaPlayer mediaPlayer = null;
private boolean isPlaying = false;
private File fileToPlay;
public PlaylistFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getFiles();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_playlist_item_list, container, false);
// Set the adapter
if (view instanceof RecyclerView) {
Context context = view.getContext();
RecyclerView recyclerView = (RecyclerView) view;
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(context);
recyclerView.setLayoutManager(linearLayoutManager);
}
return view;
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
bindUI(view);
setListeners();
setAdapter();
}
private void bindUI(View view) {
ConstraintLayout constraintLayoutMediaPlayer = view.findViewById(R.id.constraintLayoutMediaPlayer);
bottomSheetBehavior = BottomSheetBehavior.from(constraintLayoutMediaPlayer);
recyclerViewPlaylist = view.findViewById(R.id.recyclerViewPlaylist);
}
private void setListeners() {
bottomSheetBehavior.addBottomSheetCallback(new BottomSheetBehavior.BottomSheetCallback() {
#Override
public void onStateChanged(#NonNull View bottomSheet, int newState) {
if (newState == BottomSheetBehavior.STATE_HIDDEN) {
bottomSheetBehavior.setState(BottomSheetBehavior.STATE_COLLAPSED);
}
}
#Override
public void onSlide(#NonNull View bottomSheet, float slideOffset) {
}
});
}
private void getFiles() {
String path = Environment.getExternalStorageDirectory().toString() + File.separator + "Voice Recorder";
File directory = new File(path);
files = directory.listFiles();
}
private void setAdapter() {
playlistAdapter = new PlaylistAdapter(files, this);
recyclerViewPlaylist.setHasFixedSize(true);
recyclerViewPlaylist.setLayoutManager(new LinearLayoutManager(getContext()));
recyclerViewPlaylist.setAdapter(playlistAdapter);
}
#Override
public void onClickListener(File file, int position) throws IOException {
if(isPlaying){
stopAudio();
playAudio(fileToPlay);
}else{
fileToPlay = file;
playAudio(fileToPlay);
}
}
private void playAudio(File fileToPlay) {
mediaPlayer = new MediaPlayer();
try {
mediaPlayer.setDataSource(fileToPlay.getAbsolutePath());
mediaPlayer.prepare();
mediaPlayer.start();
}catch (Exception e){
e.printStackTrace();
}
isPlaying = true;
}
private void stopAudio(){
isPlaying = false;
}
}
-PlaylistAdapter.java:
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.venomapps.voicerecorder.Utils.TimeAgo;
import com.venomapps.voicerecorder.R;
import java.io.File;
import java.io.IOException;
public class PlaylistAdapter extends RecyclerView.Adapter<PlaylistAdapter.PlaylistViewHolder> {
private static File[] files;
private TimeAgo timeAgo;
private Context context;
private static onItemListClick onItemListClick;
public PlaylistAdapter(File[] files, onItemListClick onItemListClick) {
PlaylistAdapter.files = files;
PlaylistAdapter.onItemListClick = onItemListClick;
}
#NonNull
#Override
public PlaylistViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.fragment_playlist_item, parent, false);
context = parent.getContext();
timeAgo = new TimeAgo();
return new PlaylistViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull PlaylistViewHolder holder, int position) {
holder.textViewPlaylistFileName.setText(files[position].getName());
holder.textViewPlaylistStats.setText(timeAgo.getTimeAgo(files[position].lastModified(), context));
if(position == getItemCount() - 1){
holder.playlistSeparator.setVisibility(View.INVISIBLE);
}
}
#Override
public int getItemCount() {
return files.length;
}
public static class PlaylistViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private final TextView textViewPlaylistFileName;
private final TextView textViewPlaylistStats;
private final View playlistSeparator;
private final FloatingActionButton floatingActionButtonPlaylistPlay;
private final ImageButton imageButtonPlaylistItem;
public PlaylistViewHolder(#NonNull View itemView) {
super(itemView);
textViewPlaylistFileName = itemView.findViewById(R.id.textViewPlaylistFileName);
textViewPlaylistStats = itemView.findViewById(R.id.textViewPlaylistStats);
playlistSeparator = itemView.findViewById(R.id.playlistSeparator);
floatingActionButtonPlaylistPlay = itemView.findViewById(R.id.floatingActionButtonPlaylistPlay);
imageButtonPlaylistItem = itemView.findViewById(R.id.imageButtonPlaylistItem);
floatingActionButtonPlaylistPlay.setOnClickListener(this);
}
#Override
public void onClick(View v) {
try {
onItemListClick.onClickListener(files[getAdapterPosition()], getAdapterPosition());
} catch (IOException e) {
e.printStackTrace();
}
}
}
public interface onItemListClick{
void onClickListener(File file, int position) throws IOException;
}
}
Firstly, I suggest you to post full error log, and only the code which create the problem (and not your entire project ...)
There is 3 possibilities which can create your problem :
File problem (path or file not exist).
Wrong format (or not supported one).
Not permission. Do file.setReadable(true); to fix this
More informations here : https://stackoverflow.com/a/11977292/10952503
I made a recycler view to show and choose Instagram posts, in recycler view adapter I handled onclick to show user if items are selected or not and handling sum of chosen posts ... but there is problem when insta post in adapter become more than 12 when i scroll in page some chosen items are shown as not chosen, and some posts that are not choosed they look like you choosed them !!! can any one help me ?
here is my adapter:
package com.example.pinstagram.adaptor;
import android.content.Context;
import android.os.Build;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.example.pinstagram.R;
import com.example.pinstagram.classes.BuyBasketFlow;
import com.example.pinstagram.classes.InstaPosts;
import com.example.pinstagram.classes.SellingItems;
import com.example.pinstagram.viewHolders.InstaPostsRecyclerViewHolders;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
import java.util.List;
public class InstaPostsRecyclerViewAdapter extends RecyclerView.Adapter<InstaPostsRecyclerViewHolders> {
private List<InstaPosts> instaList;
private List<InstaPosts> selectedPosts;
LinearLayout linearLayout;
private Context context;
TextView numberTextView,eachPostPriceTxt,totalPriceTxt;
BuyBasketFlow buyBasketFlow;
SellingItems sellingItems;
public InstaPostsRecyclerViewAdapter(Context context, List<InstaPosts> itemList,List<InstaPosts> selectedPosts,LinearLayout linearLayout,TextView[] textViews) {
this.instaList = itemList;
this.context = context;
this.selectedPosts = selectedPosts;
this.linearLayout = linearLayout;
numberTextView = textViews[0];
eachPostPriceTxt = textViews [1];
buyBasketFlow = new BuyBasketFlow();
sellingItems = new SellingItems();
selectedPosts.clear();
for(int i = 0; i < instaList.size();i++){
instaList.get(i).setSelected(false);
}
linearLayout.setVisibility(View.GONE);
}
#NonNull
#Override
public InstaPostsRecyclerViewHolders onCreateViewHolder(ViewGroup parent, int viewType) {
View layoutView = LayoutInflater.from(parent.getContext()).inflate(R.layout.isnta_posts_listview, null);
InstaPostsRecyclerViewHolders crcv = new InstaPostsRecyclerViewHolders(layoutView);
return crcv;
}
#Override
public void onBindViewHolder(#NonNull final InstaPostsRecyclerViewHolders holder, final int position) {
holder.cardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.i("Log3", " item number: " + position + " is clicked");
instaList.get(position).setSelected(!instaList.get(position).isSelected());
if(buyBasketFlow.getType().compareTo("like")==0) {
if (instaList.get(position).isCanBeSelect()) {
selectingPhase(holder,position);
} else {
Toast.makeText(context, R.string.just_select_photo, Toast.LENGTH_SHORT).show();
Log.i("Log1", instaList.get(position).getTypename());
}
}else if(buyBasketFlow.getType().compareTo("view")==0){
if (instaList.get(position).isViewCanBeSelected()) {
selectingPhase(holder,position);
} else {
Toast.makeText(context, R.string.just_select_video, Toast.LENGTH_SHORT).show();
Log.i("Log1", instaList.get(position).getTypename());
}
}else if(buyBasketFlow.getType().compareTo("comment")==0){
if (instaList.get(position).isViewCanBeSelected()||instaList.get(position).isCanBeSelect()) {
selectingPhase(holder,position);
} else {
Toast.makeText(context, R.string.just_select_video, Toast.LENGTH_SHORT).show();
Log.i("Log1", instaList.get(position).getTypename());
}
}
}
});
Picasso.get().load(instaList.get(position).getThumbnail_url()).into(holder.instaImage);
}
public List<InstaPosts> getSelectedPosts(){
return selectedPosts;
}
#Override
public int getItemCount() {
return this.instaList.size();
}
private void selectingPhase(InstaPostsRecyclerViewHolders holder,int position){
if (instaList.get(position).isSelected()) {
selectedPosts.add(instaList.get(position));
buyBasketFlow.setPostsArrays(selectedPosts);
for (InstaPosts selected : selectedPosts) {
Log.e("Log1", selected.toString());
}
holder.radioBtn.setImageDrawable(context.getDrawable(R.drawable.radio_button_checked));
holder.cardView.setStrokeWidth(10);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
holder.cardView.setStrokeColor(context.getColor(R.color.colorPrimary));
}
} else {
selectedPosts.remove(instaList.get(position));
buyBasketFlow.setPostsArrays(selectedPosts);
for (InstaPosts selected : selectedPosts) {
Log.e("Log1", selected.toString());
}
holder.cardView.setStrokeWidth(0);
holder.radioBtn.setImageDrawable(context.getDrawable(R.drawable.radio_button_unchecked));
}
if (selectedPosts.size() < 1) {
linearLayout.setVisibility(View.GONE);
Log.i("Log1", "layout must become invisible");
} else {
Log.i("Log1", "layout must become visible");
linearLayout.setVisibility(View.VISIBLE);
sellingItems = buyBasketFlow.getSellingItem();
numberTextView.setText("" + selectedPosts.size());
Log.i("Log1", "" + Integer.parseInt(sellingItems.getPrice()));
String text = "قیمت هر پست" + sellingItems.getPrice() + " تومان ";
String sum = Integer.toString((selectedPosts.size() * Integer.parseInt(sellingItems.getPrice())));
text = text + "و قیمت مجموع " + sum + " تومان ";
eachPostPriceTxt.setText(text);
}
}
}
You need to set selected state on onBindViewHolder every time.
In onBindViewHolder:
InstaPosts instaPosts = instaList.get(position);
holder.cardView.setStrokeWidth(instaPosts.isSelected() ? 10 : 0);
holder.radioBtn.setImageDrawable(context.getDrawable(instaPosts.isSelected() ? R.drawable.radio_button_checked : R.drawable.radio_button_unchecked));
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 2 years ago.
package com.example.agriflex.ui.fooddetail;
import android.content.DialogInterface;
import android.icu.util.IslamicCalendar;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RatingBar;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;
import androidx.recyclerview.widget.RecyclerView;
import com.andremion.counterfab.CounterFab;
import com.bumptech.glide.Glide;
import com.cepheuen.elegantnumberbutton.view.ElegantNumberButton;
import com.example.agriflex.Common.Common;
import com.example.agriflex.Model.CommentModel;
import com.example.agriflex.Model.FoodModel;
import com.example.agriflex.Model.SizeModel;
import com.example.agriflex.R;
import com.example.agriflex.ui.comments.CommentFragment;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ServerValue;
import com.google.firebase.database.ValueEventListener;
import java.util.HashMap;
import java.util.Map;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import dmax.dialog.SpotsDialog;
public class FoodDetailFragment extends Fragment {
private FoodDetailViewModel foodDetailViewModel;
private Unbinder unbinder;
private android.app.AlertDialog waitingDialog;
#BindView(R.id.img_food)
ImageView img_food;
#BindView(R.id.btnCart)
CounterFab btnCart;
#BindView(R.id.btn_rating)
FloatingActionButton btn_rating;
#BindView(R.id.food_name)
TextView food_name;
#BindView(R.id.food_description)
TextView food_description;
#BindView(R.id.food_price)
TextView food_price;
#BindView(R.id.number_button)
ElegantNumberButton numberButton;
#BindView(R.id.ratingBar)
RatingBar ratingBar;
#BindView(R.id.btnShowComment)
Button btnShowComment;
#BindView(R.id.rdi_group_size)
RadioGroup rdi_group_size;
#OnClick(R.id.btn_rating)
void onRatingButtonClick() {
showDialogRating();
}
#OnClick(R.id.btnShowComment)
void onShowCommentButtonClick() {
CommentFragment commentFragment = CommentFragment.getInstance();
commentFragment.show(getActivity().getSupportFragmentManager(), "CommentFragment");
}
private void showDialogRating() {
androidx.appcompat.app.AlertDialog.Builder builder = new androidx.appcompat.app.AlertDialog.Builder(getContext());
builder.setTitle("Rating Food");
builder.setMessage("Please fill Information");
View itemView = LayoutInflater.from(getContext()).inflate(R.layout.layout_rating, null);
RatingBar ratingBar = (RatingBar) itemView.findViewById(R.id.rating_bar);
EditText edt_comment = (EditText) itemView.findViewById(R.id.edt_comment);
builder.setView(itemView);
builder.setNegativeButton("CANCEL", (dialogInterface, i) -> {
dialogInterface.dismiss();
});
builder.setPositiveButton("OK", (dialogInterface, i) -> {
CommentModel commentModel = new CommentModel();
commentModel.setName(Common.currentUser.getName());
commentModel.setUid(Common.currentUser.getUid());
commentModel.setComment(edt_comment.getText().toString());
commentModel.setRatingValue(ratingBar.getRating());
Map<String, Object> serverTimeStamp = new HashMap<>();
serverTimeStamp.put("timeStamp", ServerValue.TIMESTAMP);
commentModel.setCommentTimeStamp(serverTimeStamp);
foodDetailViewModel.setCommentModel(commentModel);
});
AlertDialog dialog = builder.create();
dialog.show();
}
public View onCreateView(#NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
foodDetailViewModel =
ViewModelProviders.of(this).get(FoodDetailViewModel.class);
View root = inflater.inflate(R.layout.fragment_food_detail, container, false);
unbinder = ButterKnife.bind(this, root);
initViews();
foodDetailViewModel.getMutableLiveDataFood().observe(this, foodModel -> {
displayInfo(foodModel);
});
foodDetailViewModel.getMutableLiveDataComment().observe(this, commentModel -> {
submitRatingToFirebase(commentModel);
});
return root;
}
private void initViews() {
waitingDialog = new SpotsDialog.Builder().setCancelable(false).setContext(getContext()).build();
}
private void submitRatingToFirebase(CommentModel commentModel) {
waitingDialog.show();
//First , we will submit to Comments ref
FirebaseDatabase.getInstance()
.getReference(Common.COMMENT_REF)
.child(Common.selectedFood.getId())
.push()
.setValue(commentModel)
.addOnCompleteListener(task -> {
if (task.isSuccessful()) {
//After submit to CommentRef , we will update value aveger in food
addRatingToFood(commentModel.getRatingValue());
}
waitingDialog.dismiss();
});
}
private void addRatingToFood(float ratingValue) {
FirebaseDatabase.getInstance()
.getReference(Common.CATEGORY_REF)
.child(Common.CategorySelected.getMenu_id()) // Select Category
.child("foods") // select array list 'foods' of this category
.child(Common.selectedFood.getKey()) // Because food item is array list so key is index of arraylist
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
FoodModel foodModel = dataSnapshot.getValue(FoodModel.class);
foodModel.setKey(Common.selectedFood.getKey()); //Don't forget set it
//Apply rating
if (foodModel.getRatingValue() == null)
foodModel.setRatingValue(0d); // d = D lower case
if (foodModel.getRatingCount() == null)
foodModel.setRatingCount(0l); // l = L lower case, not 1 (number 1)
double sumRating = foodModel.getRatingValue() + ratingValue;
long ratingCount = foodModel.getRatingCount() + 1;
double result = sumRating / ratingCount;
Map<String, Object> updateData = new HashMap<>();
updateData.put("ratingValue", result);
updateData.put("ratingCount", ratingCount);
//update data in variable
foodModel.setRatingValue(result);
foodModel.setRatingCount(ratingCount);
dataSnapshot.getRef()
.updateChildren(updateData)
.addOnCompleteListener(task -> {
waitingDialog.dismiss();
if (task.isSuccessful()) {
Toast.makeText(getContext(), "Thank you !", Toast.LENGTH_SHORT).show();
Common.selectedFood = foodModel;
foodDetailViewModel.setFoodModel(foodModel); // Call refresh
}
});
} else
waitingDialog.dismiss();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
waitingDialog.dismiss();
Toast.makeText(getContext(), "" + databaseError.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
private void displayInfo(FoodModel foodModel) {
Glide.with(getContext()).load(foodModel.getImage()).into(img_food);
food_name.setText(new StringBuilder(foodModel.getName()));
food_description.setText(new StringBuilder(foodModel.getDescription()));
food_price.setText(new StringBuilder(foodModel.getPrice().toString()));
if (foodModel.getRatingValue() != null)
ratingBar.setRating(foodModel.getRatingValue().floatValue());
((AppCompatActivity)getActivity())
.getSupportActionBar()
.setTitle(Common.selectedFood.getName());
//Size
for (SizeModel sizeModel: Common.selectedFood.getSizeModel())
{
RadioButton radioButton = new RadioButton(getContext());
radioButton.setOnCheckedChangeListener((buttonView, isChecked) -> {
if (isChecked)
Common.selectedFood.setUserSelectedSize(sizeModel);
calculateTotalPrice(); //Update Price
});
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(0,
LinearLayout.LayoutParams.MATCH_PARENT,
1.0f);
radioButton.setLayoutParams(params);
radioButton.setText(sizeModel.getName());
radioButton.setTag(sizeModel.getPrice());
rdi_group_size.addView(radioButton);
}
if (rdi_group_size.getChildCount() > 0) {
RadioButton radioButton = (RadioButton) rdi_group_size.getChildAt(0);
radioButton.setChecked(true); //Default First Select
}
calculateTotalPrice();
}
private void calculateTotalPrice () {
double totalPrice = Double.parseDouble(Common.selectedFood.getPrice().toString()), displayPrice = 0.0;
//Size
totalPrice += Double.parseDouble(Common.selectedFood.getUserSelectedSize().getPrice().toString());
displayPrice = totalPrice * (Integer.parseInt(numberButton.getNumber()));
displayPrice = Math.round(displayPrice * 100.0 / 100.0);
food_price.setText(new StringBuilder("").append(Common.formatPrice(displayPrice)).toString());
}
}
----------
## Heading ##
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.agriflex, PID: 5673
java.lang.NullPointerException: Attempt to invoke interface method 'java.util.Iterator java.util.List.iterator()' on a null object reference
at com.example.agriflex.ui.fooddetail.FoodDetailFragment.displayInfo(FoodDetailFragment.java:236)
at com.example.agriflex.ui.fooddetail.FoodDetailFragment.lambda$onCreateView$2$FoodDetailFragment(FoodDetailFragment.java:135)
at com.example.agriflex.ui.fooddetail.-$$Lambda$FoodDetailFragment$qUbisKr6hIzCwm4MXSIKgBZ3EXA.onChanged(Unknown Source:4)
at androidx.lifecycle.LiveData.considerNotify(LiveData.java:113)
at androidx.lifecycle.LiveData.dispatchingValue(LiveData.java:126)
at androidx.lifecycle.LiveData$ObserverWrapper.activeStateChanged(LiveData.java:424)
at androidx.lifecycle.LiveData$LifecycleBoundObserver.onStateChanged(LiveData.java:376)
at androidx.lifecycle.LifecycleRegistry$ObserverWithState.dispatchEvent(LifecycleRegistry.java:361)
at androidx.lifecycle.LifecycleRegistry.forwardPass(LifecycleRegistry.java:300)
at androidx.lifecycle.LifecycleRegistry.sync(LifecycleRegistry.java:339)
at androidx.lifecycle.LifecycleRegistry.moveToState(LifecycleRegistry.java:145)
at androidx.lifecycle.LifecycleRegistry.handleLifecycleEvent(LifecycleRegistry.java:131)
at androidx.fragment.app.Fragment.performStart(Fragment.java:2637)
at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManagerImpl.java:915)
at androidx.fragment.app.FragmentManagerImpl.addAddedFragments(FragmentManagerImpl.java:2100)
at androidx.fragment.app.FragmentManagerImpl.executeOpsTogether(FragmentManagerImpl.java:1874)
at androidx.fragment.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManagerImpl.java:1830)
at androidx.fragment.app.FragmentManagerImpl.execPendingActions(FragmentManagerImpl.java:1727)
at androidx.fragment.app.FragmentManagerImpl$2.run(FragmentManagerImpl.java:150)
at android.os.Handler.handleCallback(Handler.java:790)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
I/zygote: Do full code cache collection, code=495KB, data=334KB
After code cache collection, code=484KB, data=293KB
Replace your displayInfo method with
private void displayInfo(FoodModel foodModel) {
Glide.with(getContext()).load(foodModel.getImage()).into(img_food);
food_name.setText(new StringBuilder(foodModel.getName()));
food_description.setText(new StringBuilder(foodModel.getDescription()));
food_price.setText(new StringBuilder(foodModel.getPrice().toString()));
if (foodModel.getRatingValue() != null)
ratingBar.setRating(foodModel.getRatingValue().floatValue());
((AppCompatActivity)getActivity())
.getSupportActionBar()
.setTitle(Common.selectedFood.getName());
//Size
//Add NULL check for your object and your code wont throw the exception
if(null!=Common.selectedFood && null!=Common.selectedFood.getSizeModel()) {
for (SizeModel sizeModel : Common.selectedFood.getSizeModel()) {
RadioButton radioButton = new RadioButton(getContext());
radioButton.setOnCheckedChangeListener((buttonView, isChecked) -> {
if (isChecked)
Common.selectedFood.setUserSelectedSize(sizeModel);
calculateTotalPrice(); //Update Price
});
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(0,
LinearLayout.LayoutParams.MATCH_PARENT,
1.0f);
radioButton.setLayoutParams(params);
radioButton.setText(sizeModel.getName());
radioButton.setTag(sizeModel.getPrice());
rdi_group_size.addView(radioButton);
}
}
if (rdi_group_size.getChildCount() > 0) {
RadioButton radioButton = (RadioButton) rdi_group_size.getChildAt(0);
radioButton.setChecked(true); //Default First Select
}
calculateTotalPrice();
}
I have just added null checks before the list iteration.
It seems that your "foodModel" is null:
foodDetailViewModel.getMutableLiveDataFood().observe(this, foodModel -> {
displayInfo(foodModel);
});
Before displaying info you need to check if is not null :
foodDetailViewModel.getMutableLiveDataFood().observe(this, foodModel -> {
if( foodModel != null )
displayInfo(foodModel);
});
Otherwhise you need to check your "getMutableLiveDataFood()" method returns null data
I have one recycle list view .In this I have one button .on click list view item button shows.On button click I hit one api to perform action .After performing action ,at the bottom of list automatically one item get repeat. when ever I perform api hit action same time items add at the bottom of list .Like as I perform api hit action 4 times then every time one-one item get add at the bottom of list . Please provide me solution to resolve this.
Below I'm providing code of my adapter class :-
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.NetworkResponse;
import com.android.volley.Request;
import com.android.volley.VolleyError;
import com.dockedinDoctor.app.R;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import pojo.AvailableTimeSlots;
import pojo.GetBlockedTimings;
import pojo.GetDoctorScheduleDetail;
import utils.Common;
import utils.ItemClickListener;
import utils.NetworkManager;
import utils.NetworkResponseListenerJSONObject;
import utils.SessionManager;
import utils.ShowMessage;
import static utils.Common.createProgressDialog;
public class MyScheduleAdapter extends RecyclerView.Adapter<MyScheduleAdapter.ViewHolder> {
private static final String TAG = "MyScheduleTwoAdapter";
private ArrayList<GetDoctorScheduleDetail> getDoctorScheduleDetails;
private ArrayList<GetBlockedTimings> getBlockedTimingses = new ArrayList<>();
private ArrayList<AvailableTimeSlots> availableTimeSlotses = new ArrayList<>();
Context context;
private LayoutInflater inflater = null;
private int mSelectedItemPosition = -1;
Activity parentActivity;
ProgressDialog pd;
int fk_time_id;
int fk_schedule_id;
int fkscheduleid;
int getFk_schedule_id;
int block_time_slot_id;
int time_slot_id;
String DateofSlot;
String BlockDateOfSlot;
int blockid;
SessionManager manager = new SessionManager();
int Doc_Id;
ArrayList<Integer> compare= new ArrayList<Integer>();
ArrayList<Integer> compare_fk= new ArrayList<Integer>();
public MyScheduleAdapter(Context context, ArrayList<GetDoctorScheduleDetail> getDoctorScheduleDetails) {
this.context = context;
this.getDoctorScheduleDetails = getDoctorScheduleDetails;
inflater = LayoutInflater.from(context);
// setHasStableIds(true);
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.row_item_get_doctor_schedule, parent, false);
MyScheduleAdapter.ViewHolder holder = new MyScheduleAdapter.ViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(final ViewHolder holder, int position) {
final GetDoctorScheduleDetail pojo = getDoctorScheduleDetails.get(position);
fkscheduleid = pojo.getScheduleId();
DateofSlot = pojo.getDateOfSlot();
try {
Doc_Id = manager.getPreferencesInt(context, "DocId");
Log.e(TAG, "DOCID" + Doc_Id);
holder.bindDataWithViewHolder(pojo, position);
//getting data from availavle timeslots
holder.tv_time_of_slot.setText(pojo.getAvailableTimeSlots().get(position).getTimeOfSlot());
time_slot_id = pojo.getAvailableTimeSlots().get(position).getTimeSlotId();
//want to ge
block_time_slot_id = pojo.getGetBlockedTimings().get(position).getFkTimeId();
BlockDateOfSlot = pojo.getGetBlockedTimings().get(position).getBlockDateOfSlot();
blockid = pojo.getGetBlockedTimings().get(position).getBlockId();
Log.e(TAG, "values_blockk" + time_slot_id +" "+ block_time_slot_id);
compare.add(time_slot_id);//compare is an arraylist using to save Availablearray-->timeslot id
compare_fk.add(block_time_slot_id);//compare_fk is an arraylist using to save getblocktimeid-->fktime id
Log.e(TAG, "compare" + compare);
Log.e(TAG, "compare_fk" + compare_fk);
/*erlier I was using this*/
/*ArrayList<Integer> x = compare;
ArrayList<Integer> y = compare_fk;
for (int i = 0; i < x.size(); i++) {
Integer xval = y.get(i);
for (int j = 0; j < y.size(); j++) {
if (xval.equals(x.get(j))) {
Toast.makeText(context,"same_list"+y.get(j),Toast.LENGTH_SHORT).show();
holder.tv_time_of_slot.setTextColor(Color.RED);
}
}
}*/
int array1Size = compare.size();
int array2Size = compare_fk.size();
if (compare.size() > compare_fk.size()) {
int k = 0;
for (int i = 0; i < compare_fk.size(); i++) {
if (((Integer)compare.get(i)).equals((Integer)compare_fk.get(i))) {
System.out.println((Integer)compare_fk.get(i));
Log.e("values_adapter", String.valueOf(((Integer)compare_fk.get(i))));
}
k = i;
}
}
else {
int k = 0;
for (int i = 0; i < compare.size(); i++) {
if (((Integer)compare.get(i)).equals((Integer) compare_fk.get(i))) {
System.out.println((Integer) compare.get(i));
Log.e("values_adapter11",String.valueOf(((Integer)compare.get(i))));
}
k = i;
}
}
if (time_slot_id == block_time_slot_id)
{
holder.tv_time_of_slot.setTextColor(Color.RED);
}
if (!(pojo.getGetBlockedTimings().get(position).getBlockDateOfSlot().equals("")))
{
holder.tv_d.setText(pojo.getGetBlockedTimings().get(position).getBlockDateOfSlot());
holder.tv_b.setText(pojo.getGetBlockedTimings().get(position).getBlockId());
}
} catch (Exception e) {
e.printStackTrace();
e.getMessage();
}
// //iterate on the general list
// for (int i = 0; i < availableTimeSlotses.size(); i++) {
// int timeSlotId = availableTimeSlotses.get(i).getTimeSlotId();
// if (getFk_time_id == timeSlotId) {
//
// holder.tv_time_of_slot.setText(pojo.getDateOfSlot());
// }
// }
// block api
holder.btn_block.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final Dialog lDialog = new Dialog(context);
lDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
lDialog.setCancelable(false);
lDialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
lDialog.getWindow().setDimAmount(.7f);
lDialog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_BLUR_BEHIND);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {
lDialog.getWindow().setElevation(4);
}
lDialog.setContentView(R.layout.popup_no_yes);
TextView tv_titiel = (TextView) lDialog.findViewById(R.id.tv_titiel);
TextView textMsg = (TextView) lDialog.findViewById(R.id.popup_msgs);
Button btnno = (Button) lDialog.findViewById(R.id.popup_no_btn);
Button btnyes = (Button) lDialog.findViewById(R.id.popup_yes_btn);
btnno.setTransformationMethod(null);
btnyes.setTransformationMethod(null);
tv_titiel.setText("Schedule");
textMsg.setText("Are you sure you want to block this slot?");
btnno.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
lDialog.dismiss();
}
});
btnyes.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
LocalBroadcastManager.getInstance(context).sendBroadcast(new Intent("notification_fragment"));
slotBlockingApi(fkscheduleid, time_slot_id);
lDialog.dismiss();
}
});
lDialog.show();
}
});
}
#Override
public int getItemCount() {
return getDoctorScheduleDetails.size();
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public int getItemViewType(int position) {
return position;
}
public void slotBlockingApi(int _fk_schedule_id, int _fk_time_id) {
isOnline();
pd = createProgressDialog(context);
pd.show();
final String requestBody = "'{\"fkScheduledId\":\"" + _fk_schedule_id +
"\",\"fkTimeId\":\"" + _fk_time_id +
"\",\"DoctorId\":\"" + Doc_Id +
"\"}'";
Log.e(TAG, "requset body of slotBlockingApi : " + requestBody);
NetworkManager.getInstance(context).makeNetworkRequestForJSON(
Request.Method.POST,
Common.BASE_URL + "/PostDoctorCheckForAppointmentBeforeSlotBlocking",
null,
requestBody,
null,
new NetworkResponseListenerJSONObject() {
#Override
public void onDataReceived(Object data) {
pd.dismiss();
Log.e(TAG, "response of slotBlockingApi : " + data.toString());
try {
JSONObject jsonObject = new JSONObject(data.toString());
JSONObject ResponseJsonObject1 = jsonObject.getJSONObject("Response");
int ResponseCode = ResponseJsonObject1.getInt("ResponseCode");
String ResponseText = ResponseJsonObject1.getString("ResponseText");
// JSONObject jsonObjectDetail = jsonObject.getJSONObject("Detail");
// Log.e(TAG, "jsonObjectDetail : " + jsonObjectDetail);
// int doc_id = jsonObjectDetail.getInt("DocId");
// if (ResponseText == "No Appointment" || ResponseText.equals("No Appointment") || ResponseText.equalsIgnoreCase("No Appointment")) {
if (ResponseText == "No Appointment" || ResponseText.equals("No Appointment") || ResponseText.equalsIgnoreCase("No Appointment")) {
// if (ResponseText =="No Appointment" || ResponseText.equals("No Appointment")) {
pd = createProgressDialog(context);
pd.show();
final String requestBody = "'{\"utcTimeOffset\":\"" + "330" +
"\",\"BlockedScheduledDate\":\"" + DateofSlot +
"\",\"fkScheduledId\":\"" + fkscheduleid +
"\",\"fkTimeId\":\"" + time_slot_id +
"\"}'";
Log.e(TAG, "requset body of slotBlocking: " + requestBody);
NetworkManager.getInstance(context).makeNetworkRequestForJSON(
Request.Method.POST,
Common.BASE_URL + "/PostDoctorBlockTimeSlot",
null,
requestBody,
null,
new NetworkResponseListenerJSONObject() {
#Override
public void onDataReceived(Object data) {
pd.dismiss();
new ShowMessage(context, "Block Slot","Time slot blocked Successfully");
Log.e(TAG, "response of slotBlocking: " + data.toString());
}
#Override
public void onDataFailed(VolleyError error) {
pd.dismiss();
String json = null;
NetworkResponse response = error.networkResponse;
if (response != null && response.data != null) {
switch (response.statusCode) {
case 302:
Toast.makeText(context, "No Internet Connection Found.", Toast.LENGTH_SHORT).show();
break;
}
//Additional cases
}
}
});
} else {
final Dialog lDialog = new Dialog(context);
lDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
lDialog.setCancelable(false);
lDialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
lDialog.getWindow().setDimAmount(.7f);
lDialog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_BLUR_BEHIND);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {
lDialog.getWindow().setElevation(4);
}
lDialog.setContentView(R.layout.custom_popup);
TextView textTitle = (TextView) lDialog.findViewById(R.id.popup_title);
TextView textMsg = (TextView) lDialog.findViewById(R.id.popup_msg);
Button okButton = (Button) lDialog.findViewById(R.id.popup_ok_btn);
okButton.setTransformationMethod(null);
textTitle.setText("Schedule");
textMsg.setText("An appointment has been booked on this slot.");
okButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
lDialog.dismiss();
}
});
lDialog.show();
}
// else if (ResponseCode == 0 || ResponseCode == 2) {
// new ShowMessage(context, ResponseText);
// }
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onDataFailed(VolleyError error) {
pd.dismiss();
String json = null;
NetworkResponse response = error.networkResponse;
if (response != null && response.data != null) {
switch (response.statusCode) {
case 302:
Toast.makeText(context, "No Internet Connection Found.", Toast.LENGTH_SHORT).show();
break;
}
//Additional cases
}
}
});
}
public boolean isOnline() {
ConnectivityManager conMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = conMgr.getActiveNetworkInfo();
if (netInfo == null || !netInfo.isConnected() || !netInfo.isAvailable()) {
new ShowMessage(context, "Network error","Internet not available, Cross check your internet connectivity and try again");
}
return true;
}
/**
* VIEW HOLDER CLASS DEFINE HERE
*/
public class ViewHolder extends RecyclerView.ViewHolder {
#BindView(R.id.ll_row_item_get_doctor_schedule)
LinearLayout ll_row_item_get_doctor_schedule;
#BindView(R.id.tv_time_of_slot)
TextView tv_time_of_slot;
#BindView(R.id.btn_block)
Button btn_block;
#BindView(R.id.btn_unblock)
Button btn_unblock;
#BindView(R.id.tv_d)
TextView tv_d;
#BindView(R.id.tv_b)
TextView tv_b;
GetDoctorScheduleDetail doctorScheduleDetail = null;
ItemClickListener clickListener;
private ViewHolder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
ll_row_item_get_doctor_schedule.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Handling for background selection state changed
int previousSelectState = mSelectedItemPosition;
mSelectedItemPosition = getAdapterPosition();
//notify previous selected item
notifyItemChanged(previousSelectState);
//notify new selected Item
notifyItemChanged(mSelectedItemPosition);
//Your other handling in onclick
}
});
}
public void setClickListener(ItemClickListener itemClickListener) {
this.clickListener = itemClickListener;
}
#OnClick
public void onClickMethod(View v) {
clickListener.onClick(v, getPosition(), false);
}
public void bindDataWithViewHolder(GetDoctorScheduleDetail schedulePojo, int currentPosition) {
this.doctorScheduleDetail = schedulePojo;
//Handle selection state in object View.
if (currentPosition == mSelectedItemPosition) {
btn_block.setVisibility(View.VISIBLE);
} else {
btn_block.setVisibility(View.GONE);
}
//other View binding logics like setting text , loading image etc.
}
}
}
Phone number format and custom typepad dose not working
Hi friends i am a Android Developer. Today i have fetching a simple problem. Anybody please help me.
Here is my code below and:
package com.example.grab_n_go_android;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
/**
* Created by al-imranislam on 5/22/17.
*/
public class LoginActivity extends AppCompatActivity implements TextWatcher{
public EditText numberDisplayEditText, test2;
private TextView displayNumberLabel;
private int state = 0;
private String displayNumber = "";
private String passcodeDisplay = "";
private String passcode = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login_view);
numberDisplayEditText = (EditText) findViewById(R.id.numberInput);
test2 = (EditText) findViewById(R.id.numberInput);
displayNumberLabel = (TextView) findViewById(R.id.displayLabel);
numberDisplayEditText.addTextChangedListener(this);
Log.d("LoginActivity", "onCreate() was called");
}
//For Custom Keyboard
public void n0(View view){
test2.setText(test2.getText().insert(test2.getText().length(),"0"));
}
public void n1(View view){
test2.setText(test2.getText().insert(test2.getText().length(),"1"));
}
public void n2(View view){
test2.setText(test2.getText().insert(test2.getText().length(),"2"));
}
public void n3(View view){
test2.setText(test2.getText().insert(test2.getText().length(),"3"));
}
public void n4(View view){
test2.setText(test2.getText().insert(test2.getText().length(),"4"));
}
public void n5(View view){
test2.setText(test2.getText().insert(test2.getText().length(),"5"));
}
public void n6(View view){
test2.setText(test2.getText().insert(test2.getText().length(),"6"));
}
public void n7(View view){
test2.setText(test2.getText().insert(test2.getText().length(),"7"));
}
public void n8(View view){
test2.setText(test2.getText().insert(test2.getText().length(),"8"));
}
public void n9(View view){
test2.setText(test2.getText().insert(test2.getText().length(),"9"));
}
public void dele(View view){
test2.setText(test2.getText().delete(test2.getText().length() -1, test2.getText().length()));
}
public void cancel(View view){
test2.setText("");
Toast.makeText(getApplicationContext(),"Cancel Activity is Successfully", Toast.LENGTH_SHORT).show();
Intent i = new Intent(LoginActivity.this, MainActivity.class);
startActivity(i);
}
//For Custom Keyboard
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
Log.d("LoginActivity", "A character was typed in");
if (state == 0) {
numberDisplayEditText.removeTextChangedListener(this);
if (displayNumber.length() == 0) {
displayNumber = displayNumber + "(";
}
if (displayNumber.length() == 4) {
displayNumber = displayNumber + ")";
}
if (displayNumber.length() == 9) {
displayNumber = displayNumber + "-";
}
displayNumber = displayNumber + s.subSequence(count - 1, count);
numberDisplayEditText.setText(displayNumber);
if(displayNumber.length() >= 14) {
displayNumberLabel.setText("Enter Your Passcode");
numberDisplayEditText.setText("");
state = 1;
numberDisplayEditText.addTextChangedListener(this);
return;
}
numberDisplayEditText.addTextChangedListener(this);
return;
}
if (state == 1){
numberDisplayEditText.removeTextChangedListener(this);
if(passcode.length() == 4){
numberDisplayEditText.setText(passcodeDisplay);
numberDisplayEditText.addTextChangedListener(this);
return;
}
passcodeDisplay = passcodeDisplay + "*";
numberDisplayEditText.setText(passcodeDisplay);
passcode = passcode + s.subSequence(count - 1, count);
if(passcode.length() == 4){
Log.d("test", displayNumber + ":" + passcode);
Intent i = new Intent(getBaseContext(), SelfCheckoutViewActivity.class);
startActivity(i);
}
numberDisplayEditText.addTextChangedListener(this);
//return;
}
}
#Override
public void afterTextChanged(Editable s) {
}
}
Please see this Google drive link below. It's a very very simple android app.
https://drive.google.com/open?id=0B-yo9VvU7jyBeS01ek9VSXpYRzg
And This is the Simple Image: