How can I reduce the time for retrieving data from postgresql? - java

The code is working but it is taking 14-16 seconds to retrieve data of just 1 video from postgresql server. I think there might be a proper way of retrieving the data. Please help me with this.
Thank you.
FreeClassesAdapter.java
import android.app.Activity;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.android.volley.RequestQueue;
import com.athrved.masterclass.PlayerActivity;
import com.athrved.masterclass.R;
import com.squareup.picasso.Picasso;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
public class FreeclassesAdapter extends RecyclerView.Adapter<FreeclassesAdapter.FreeViewHolder> {
ArrayList<FreeHelperClass> featloc;
public static String a,b="FAILED TO LOAD";
public static String videoId1;
RequestQueue requestQueue;
private static String V_id1;
public FreeclassesAdapter(ArrayList<FreeHelperClass> featloc) {
this.featloc = featloc;
}
#NonNull
#Override
public FreeViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.free_class_card_design,parent,false);
FreeViewHolder freeViewHolder = new FreeViewHolder(view);
return freeViewHolder;
}
#Override
public void onBindViewHolder(#NonNull FreeViewHolder holder, int position) {
FreeHelperClass freeHelperClass = featloc.get(position);
holder.imagesmall1.setImageResource(freeHelperClass.getImagesmall1());
holder.imagesmall2.setImageResource(freeHelperClass.getImagesmall2());
holder.title.setText(freeHelperClass.getTitle());
holder.topic.setText(freeHelperClass.getTopic());
holder.author.setText(freeHelperClass.getAuthor());
Database db=new Database();
videoId1=V_id1;
if(position==0){
Picasso.get().load("https://img.youtube.com/vi/"+videoId1+"/maxresdefault.jpg").into(holder.imagebig);
}
if(position==1){
Picasso.get().load("https://img.youtube.com/vi/lrcqt4RelJ4/maxresdefault.jpg").into(holder.imagebig);
}
}
#Override
public int getItemCount() {
return featloc.size();
}
public static class FreeViewHolder extends RecyclerView.ViewHolder{
ImageView imagebig, imagesmall1,imagesmall2;
TextView topic, author;
TextView title;
Button bookmark, bookmark_border;
public FreeViewHolder(#NonNull final View itemView){
super(itemView);
imagebig=itemView.findViewById(R.id.freeimgbig);
imagesmall1=itemView.findViewById(R.id.freec1_image);
imagesmall2=itemView.findViewById(R.id.freec2_image);
bookmark=itemView.findViewById(R.id.bookmarkfree);
bookmark_border=itemView.findViewById(R.id.bookmarkfree_border);
title=itemView.findViewById(R.id.freec_title);
topic=itemView.findViewById(R.id.freec_topic);
author=itemView.findViewById(R.id.freec_author);
bookmark_border.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(getAdapterPosition()==0){
bookmark_border.setVisibility(View.GONE);
bookmark.setVisibility(View.VISIBLE);
}
if(getAdapterPosition()==1){
bookmark_border.setVisibility(View.GONE);
bookmark.setVisibility(View.VISIBLE);
}
}
});
bookmark.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(getAdapterPosition()==0){
bookmark_border.setVisibility(View.VISIBLE);
bookmark.setVisibility(View.GONE);
}
if(getAdapterPosition()==1){
bookmark_border.setVisibility(View.VISIBLE);
bookmark.setVisibility(View.GONE);
}
}
});
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
videoId1=V_id1;
if (getAdapterPosition() == 0) {
Intent intent = new Intent(itemView.getContext(), PlayerActivity.class);
intent.putExtra("VIDEOID", videoId1);
itemView.getContext().startActivity(intent);
Activity activity = (Activity) itemView.getContext();
activity.overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
}
if (getAdapterPosition() == 1) {
Intent intent = new Intent(itemView.getContext(), PlayerActivity.class);
intent.putExtra("VIDEOID", "lrcqt4RelJ4");
itemView.getContext().startActivity(intent);
Activity activity = (Activity) itemView.getContext();
activity.overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
}
}
});
}
}
private class Database {
private Connection connection;
private final String host = "ec2-54-158-232-223.compute-1.amazonaws.com";
private final String database = "ddgaguv61p4m63";
private final int port = 5432;
private final String user = "jfeitasqnyuanh";
private final String pass = "d60b43b4e9ea924c91deb754cf18a51d5948b7a7e58b4e4d0045487767174ad8";
private String url = "jdbc:postgresql://ec2-54-158-232-223.compute-1.amazonaws.com:5432/ddgaguv61p4m63?sslmode=require&user=jfeitasqnyuanh&password=d60b43b4e9ea924c91deb754cf18a51d5948b7a7e58b4e4d0045487767174ad8";
private boolean status;
public Database() {
this.url = String.format(this.url, this.host, this.port, this.database);
connect();
//this.disconnect();
System.out.println("connection status:" + status);
}
private void connect() {
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
try {
Class.forName("org.postgresql.Driver");
connection = DriverManager.getConnection(url, user, pass);
status = true;
getExtraConnection();
System.out.println("connected:" + status);
} catch (Exception e) {
status = false;
System.out.print(e.getMessage());
e.printStackTrace();
}
}
});
thread.start();
try {
thread.join();
} catch (Exception e) {
e.printStackTrace();
this.status = false;
}
}
public Connection getExtraConnection() {
Connection c = null;
Statement stmt = null;
try {
Class.forName("org.postgresql.Driver");
c = DriverManager.getConnection(url, user, pass);
c.setAutoCommit(false);
System.out.println("Opened database successfully");
stmt = c.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM videos WHERE access_count=1;");
while (rs.next()) {
V_id1 = rs.getString("video_id");
//
// System.out.println("NAME = " + Name);
// System.out.println("BIO = " + Bio);
// System.out.println("PHONE = " + Phone);
System.out.println();
}
rs.close();
stmt.close();
c.close();
} catch (Exception e) {
System.err.println(e.getClass().getName() + ": " + e.getMessage());
System.exit(0);
}
System.out.println("Records created successfully");
return c;
}
}
}
Code from the main activity where FreeClassesAdapter is used - UiUxActivity.java:
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.view.MenuItem;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.athrved.masterclass.FetchData;
import com.athrved.masterclass.R;
import java.util.ArrayList;
import java.util.List;
public class UiuxActivity extends AppCompatActivity {
TextView abcde;
TextView ak;
String tit;
String urlname,videoID,tita;
RecyclerView dataList2;
List<String> titles2;
List<Integer> images2;
ImgAdapter2 imgAdapter2;
RecyclerView popRecycler;
RecyclerView.Adapter adapter1;
RecyclerView freeRecycler;
RecyclerView.Adapter adapter2;
RecyclerView menRecycler;
RecyclerView.Adapter adapter3;
RecyclerView allFewRecycler;
RecyclerView.Adapter adapter4;
ArrayList<UiuxAllClasses> allCourseList=new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_uiux);
getSupportActionBar().setTitle("UI UX Design");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.greyy)));
// videoID="_vAmKNin0QM";
// urlname="https://noembed.com/embed?url=https://www.youtube.com/watch?v="+videoID;
// tita= respo(urlname);
popRecycler = findViewById(R.id.r1popclass);
featuredRecycler();
freeRecycler=findViewById(R.id.r1freeclass);
freeturedRecycler( tit);
menRecycler=findViewById(R.id.r3menclass);
mentoredRecycler();
allFewRecycler=findViewById(R.id.r4fewalllist);
allfewRecycler();
dataList2 = findViewById(R.id.dataList2);
abcde = findViewById(R.id.tvv1);
ak=findViewById(R.id.ak);
titles2 = new ArrayList<>();
images2 = new ArrayList<>();
titles2.add("Visual Design");
titles2.add("UX Design");
titles2.add("Motion Design");
titles2.add("Prototyping");
titles2.add("3D Design");
titles2.add("Webflow");
images2.add(R.drawable.visuald_logo);
images2.add(R.drawable.uiux_logo);
images2.add(R.drawable.motiond_logo);
images2.add(R.drawable.mach_logo);
images2.add(R.drawable.threed_logo);
images2.add(R.drawable.iot_logo);
imgAdapter2 = new ImgAdapter2(this,titles2,images2);
GridLayoutManager gridLayoutManager = new GridLayoutManager(this,2,GridLayoutManager.VERTICAL,false);
dataList2.setLayoutManager(gridLayoutManager);
dataList2.setAdapter(imgAdapter2);
}
private void featuredRecycler(){
FetchData fetchData = new FetchData();
fetchData.execute();
popRecycler.setHasFixedSize(true);
popRecycler.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
ArrayList<PopHelperClass> popLocatio = new ArrayList<>();
popLocatio.add(new PopHelperClass(R.drawable.secndone, R.drawable.ai_logo,0,"Color and Color Theory -\nFundamentals of Visual Design","VISUAL DESIGN","Goutham Naik","Um3BhY0oS2c"));
popLocatio.add(new PopHelperClass(R.drawable.firstone, R.drawable.ai_logo, R.drawable.motiond_logo,"Color and Color Theory -\nFundamentals of Visual Design","UX DESIGN"," Goutham Naik, S. M. Sudhanva Acharya","_vAmKNin0QM"));
adapter1=new PopclassesAdapter(popLocatio);
popRecycler.setAdapter(adapter1);
}
private void freeturedRecycler(String tita){
freeRecycler.setHasFixedSize(true);
freeRecycler.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
ArrayList<FreeHelperClass> freeLocatio = new ArrayList<>();
freeLocatio.add(new FreeHelperClass(R.drawable.ai_logo,0,"Top UX Design Interview Questions","VISUAL DESIGN","S M Sudhanva Acharya"));
freeLocatio.add(new FreeHelperClass(R.drawable.ai_logo,0,"White Space in Design","VISUAL DESIGN","Abhinav Chikkara"));
adapter2=new FreeclassesAdapter(freeLocatio);
freeRecycler.setAdapter(adapter2);
}
private void mentoredRecycler(){
menRecycler.setHasFixedSize(true);
menRecycler.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
ArrayList<MenHelperClass> menLocatio = new ArrayList<>();
menLocatio.add(new MenHelperClass(R.drawable.oneman,"Goutam Naik","CEO, AthrV-Ed"));
menLocatio.add(new MenHelperClass(R.drawable.twoman,"S M Sudhanva Acharya", "Product Designer, AthrV-Ed"));
menLocatio.add(new MenHelperClass(R.drawable.threeman,"Abhinav Chikkara", "Founder, 10kilogram"));
adapter2=new MenAdapter(menLocatio);
menRecycler.setAdapter(adapter2);
}
private void allfewRecycler(){
allFewRecycler.setHasFixedSize(true);
allFewRecycler.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
ArrayList<FewAllHelperClass> fewAllLocatio = new ArrayList<>();
fewAllLocatio.add(new FewAllHelperClass(R.drawable.webflow_l, R.drawable.ai_logo,"Playing with Grid-\nWeb Design Fundamentals","WEBFLOW","Goutham Naik"));
fewAllLocatio.add(new FewAllHelperClass(R.drawable.protopie_l, R.drawable.ai_logo,"Protopie for Prototyping","PROTOTYPING\n","Abhinav Chikkara"));
fewAllLocatio.add(new FewAllHelperClass(R.drawable.afepluslot_l, R.drawable.ai_logo,"Introduction to After Effects\nand Lottie Files","MOTION DESIGN","S.M Sudhanva Acharya"));
adapter4=new FewAllAdapter(fewAllLocatio);
allFewRecycler.setAdapter(adapter4);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
}
return super.onOptionsItemSelected(item);
}
}

Are you storing the video in your DB as a BLOB / CLOB.
What if you store the video in a different location, and save the address of the location in your DB. This way Db has to return a string, and UI / consumer can take care of rendering from the path.

Related

MediaPlayer error trying to play audio in Android app

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

Handle empty recycle viewr within fragments

I am trying to make an application where using Recycle View and Volley to get data from server and also I used Navigation drawer and fragments,Everything working fine except When no data on recycle-view I want to show a notice like "there is no data!"I searched over internet multiple times but haven't get a proper solution or I couldn't understand properly because I am totally beginner.
bellow is my java files
1.Adapter
package com.eworld.myapplication;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.squareup.picasso.Picasso;
import java.util.List;
public class ExchangesAdapter extends RecyclerView.Adapter<ExchangesViewHolder> {
private List<ExchangesSetterGetter>exchangeList;
private Context context;
public ExchangesAdapter(List<ExchangesSetterGetter> exchangeList, Context context) {
this.exchangeList = exchangeList;
this.context = context;
}
#NonNull
#Override
public ExchangesViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view=LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.cardlayout,viewGroup,false);
ExchangesViewHolder viewHolder=new ExchangesViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(#NonNull ExchangesViewHolder exchangesViewHolder, int i) {
String status="";
final ExchangesSetterGetter exchangesPosition=exchangeList.get(i);
if (exchangesPosition.getStatus().equals("1")) {
status = "Awaiting Confirmation";
} else if (exchangesPosition.getStatus().equals("2")) {
status = "Awaiting Payment";
} else if (exchangesPosition.getStatus().equals("3")) {
status = "Processing";
} else if (exchangesPosition.getStatus().equals("4")) {
status = "proceed";
} else if (exchangesPosition.getStatus().equals("5")) {
status = "Timeout";
} else if (exchangesPosition.getStatus().equals("6")) {
status = "Denied";
} else if (exchangesPosition.getStatus().equals("7")) {
status = "Canceled";
} else if (exchangesPosition.getStatus().equals("8")) {
status = "Unknown";
}
exchangesViewHolder.gatewayFrom.setText(exchangesPosition.getAmountFrom() + " " + exchangesPosition.getCurrencyFrom() + " " + exchangesPosition.getExchangeFrom());
exchangesViewHolder.gatewayTo.setText(exchangesPosition.getAmountTo() + " " + exchangesPosition.getCurrencyTo() + " " + exchangesPosition.getExchangeTo());
exchangesViewHolder.status.setText(status);
Picasso.get().load("https://eworld.ltd/" + exchangesPosition.getImgSend()).into(exchangesViewHolder.imgSendFrom);
Picasso.get().load("https://eworld.ltd/" + exchangesPosition.getImgReceived()).into(exchangesViewHolder.imgSendTo);
}
#Override
public int getItemCount() {
return exchangeList.size();
}
}
2.View Holder
package com.eworld.myapplication;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
public class ExchangesViewHolder extends RecyclerView.ViewHolder {
ImageView imgSendFrom,imgSendTo;
TextView gatewayFrom,gatewayTo,status;
public ExchangesViewHolder(#NonNull View itemView) {
super(itemView);
imgSendFrom=itemView.findViewById(R.id.img1);
imgSendTo=itemView.findViewById(R.id.img2);
gatewayFrom=itemView.findViewById(R.id.tv1);
gatewayTo=itemView.findViewById(R.id.tv2);
status=itemView.findViewById(R.id.tv3);
}
}
3.Getter and Setter(Data model)
package com.eworld.myapplication;
public class ExchangesSetterGetter {
private String exchangeFrom,exchangeTo,status,imgSend,imgReceived,currencyFrom,currencyTo,amountFrom,amountTo;
public ExchangesSetterGetter(String exchangeFrom, String exchangeTo, String status, String imgSend, String imgReceived, String currencyFrom, String currencyTo, String amountFrom, String amountTo) {
this.exchangeFrom = exchangeFrom;
this.exchangeTo = exchangeTo;
this.status = status;
this.imgSend = imgSend;
this.imgReceived = imgReceived;
this.currencyFrom = currencyFrom;
this.currencyTo = currencyTo;
this.amountFrom = amountFrom;
this.amountTo = amountTo;
}
public String getCurrencyFrom() {
return currencyFrom;
}
public void setCurrencyFrom(String currencyFrom) {
this.currencyFrom = currencyFrom;
}
public String getCurrencyTo() {
return currencyTo;
}
public void setCurrencyTo(String currencyTo) {
this.currencyTo = currencyTo;
}
public String getAmountFrom() {
return amountFrom;
}
public void setAmountFrom(String amountFrom) {
this.amountFrom = amountFrom;
}
public String getAmountTo() {
return amountTo;
}
public void setAmountTo(String amountTo) {
this.amountTo = amountTo;
}
public String getExchangeFrom() {
return exchangeFrom;
}
public void setExchangeFrom(String exchangeFrom) {
this.exchangeFrom = exchangeFrom;
}
public String getExchangeTo() {
return exchangeTo;
}
public void setExchangeTo(String exchangeTo) {
this.exchangeTo = exchangeTo;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getImgSend() {
return imgSend;
}
public void setImgSend(String imgSend) {
this.imgSend = imgSend;
}
public String getImgReceived() {
return imgReceived;
}
public void setImgReceived(String imgReceived) {
this.imgReceived = imgReceived;
}
}
4.And finally my fragment Activity with recycle-view
package com.eworld.myapplication;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class ExchangesFrag extends Fragment {
RecyclerView recyclerView;
ExchangesAdapter adapter;
List<ExchangesSetterGetter> listItems;
SharedPrefManager sharedPreferences;
int uid;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View exchanges=inflater.inflate(R.layout.exchanges_layout,container,false);
recyclerView=exchanges.findViewById(R.id.rview);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
listItems=new ArrayList<>();
sharedPreferences=new SharedPrefManager(getActivity());
uid = sharedPreferences.getUser().getId();
loadData();
return exchanges;
}
public void loadData() {
StringRequest stringRequest=new StringRequest(Request.Method.GET, URLs.url+uid, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray jsonArray = jsonObject.getJSONArray("data");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject receive = jsonArray.getJSONObject(i);
ExchangesSetterGetter exchangesSetterGetter = new ExchangesSetterGetter(
receive.getString("exchangeFrom"),
receive.getString("exchangeTo"),
receive.getString("status"),
receive.getString("imgSend"),
receive.getString("imgReceive"),
receive.getString("sendCurrency"),
receive.getString("receiveCurrency"),
receive.getString("amount_send"),
receive.getString("amount_receive")
);
listItems.add(exchangesSetterGetter);
}
adapter = new ExchangesAdapter(listItems, getContext());
recyclerView.setAdapter(adapter);
} catch(JSONException e){
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getContext(),"error on volley",Toast.LENGTH_LONG).show();
}
});
RequestQueue queue= Volley.newRequestQueue(getContext());
queue.add(stringRequest);
}
}
You can handle the empty state by having a TextView in your layout, which switch its visibility state depending upon the array size you are getting in your response as:
JSONArray jsonArray = jsonObject.getJSONArray("data");
if (jsonArray.length() > 0) {
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject receive = jsonArray.getJSONObject(i);
ExchangesSetterGetter exchangesSetterGetter = new ExchangesSetterGetter(
receive.getString("exchangeFrom"),
receive.getString("exchangeTo"),
receive.getString("status"),
receive.getString("imgSend"),
receive.getString("imgReceive"),
receive.getString("sendCurrency"),
receive.getString("receiveCurrency"),
receive.getString("amount_send"),
receive.getString("amount_receive")
);
listItems.add(exchangesSetterGetter);
}
adapter = new ExchangesAdapter(listItems, getContext());
recyclerView.setAdapter(adapter);
recyclerView.setVisibilty(View.VISIBLE);
noDataText.setVisibilty(View.GONE);
} else {
recyclerView.setVisiblity(View.GONE);
noDataText.setVisiblity(View.VISIBLE);
}
Add an extra textview in your fragment xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="#+id/tv_no_data"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_centerInParent="true"
android:textSize="22sp"
android:visibility="gone" />
<android.support.v7.widget.RecyclerView
android:id="#+id/rv_ride_list"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
And then in your activity
JSONArray jsonArray = jsonObject.getJSONArray("data");
if(jsonArray.length() > 0){
//process data and initialize adapter
}else{
//Set Text view visible
}
There is a simple solution for that inside your fragment xml where recycler view is being loaded take a relative layout and add a textview with your desired message at last and set it's alignment as per your requirement and inside on create of your fragment set visiblity of your text view to View.INVISIBLE and later on after api is called simply pass an if condition stating that
if(response==null){ textview.setVisiblity = View.Visible}
The way I like to handle this is to wrap your RecyclerView and your NoContentView (this can be whatever you like) in a ViewFlipper like so
<ViewFlipper>
</RecyclerView>
<NoContentView>
</NoContentView>
</ViewFlipper>
Then all you do is to check to see if you have list items and display the appropriate child layout of the ViewFlipper
if(listItems.size() == 0)
{
viewFlipper.setDisplayedChild(1)
}

checkbox select and deselect

package com.example.adapter;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.util.SparseBooleanArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.TextView;
import android.widget.Toast;
import com.example.aayushchaubey.meetdax.R;
import com.google.android.gms.tasks.Task;
import com.google.firebase.firestore.QuerySnapshot;
import java.util.ArrayList;
import java.util.HashMap;
public class DifferentGenderServicesAdapter2 extends RecyclerView.Adapter {
private Task<QuerySnapshot> task;
String id, servicename;
ArrayList<String> serviceArray = new ArrayList<>();
ArrayList<Integer> costArray = new ArrayList<>();
ArrayList<ArrayList<String>> stylistIdArray = new ArrayList<>();
ArrayList<Integer>durationArray=new ArrayList<>();
TextView serviceTv, durationTv;
int count = 0;
String strService;
ArrayList<String> keyArr = new ArrayList<>();
ArrayList<String>serviceDocumentId=new ArrayList<>();
ArrayList<String>selectedServiceId=new ArrayList<>();
ArrayList<String>selectedServiceArray=new ArrayList<>();
ArrayList<Integer>selectedServiceCost=new ArrayList<>();
ArrayList<Integer>durationArr=new ArrayList<>();
String serviceId,strStylist,strDuration;
ArrayList<String>stylist=new ArrayList<>();
ArrayList<ArrayList<String>>selectedStylistId=new ArrayList<>();
public DifferentGenderServicesAdapter2(Task<QuerySnapshot> task, ArrayList<String> id, TextView servicesTv, TextView durationTv) {
this.task = task;
this.serviceTv = servicesTv;
this.durationTv = durationTv;
this.serviceDocumentId=id;
count = task.getResult().size();
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.services_item, parent, false);
return new DifferentGenderServicesAdapter2.listViewHolder(view);
}
#Override
public void onBindViewHolder(final RecyclerView.ViewHolder holder, final int position) {
try {
((listViewHolder) holder).servicenameTv.setText(task.getResult().getDocuments().get(position).get("name").toString());
((listViewHolder) holder).serviceCost.setText(task.getResult().getDocuments().get(position).get("price").toString());
servicename = task.getResult().getDocuments().get(position).get("name").toString();
Integer price = task.getResult().getDocuments().get(position).getLong("price").intValue();
serviceArray.add(servicename);
costArray.add(price);
ArrayList<HashMap<String,String>>stylistArr=new ArrayList<>();
stylistArr=(ArrayList<HashMap<String, String>>)task.getResult().getDocuments().get(position).get("services");
ArrayList<String> stylistsId = new ArrayList<String>();
stylistsId.clear();
for (int i=0;i<stylistArr.size();i++){
strStylist=stylistArr.get(i).get("stylist").toString();
strDuration=stylistArr.get(i).get("duration").toString();
stylistsId.add(strStylist);
durationArray.add(Integer.parseInt(strDuration));
}
stylistIdArray.add(stylistsId);
((listViewHolder) holder).checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if(((listViewHolder) holder).checkBox.isChecked()){
String service=serviceArray.get(position);
selectedServiceArray.add(service);
serviceTv.setText(selectedServiceArray.toString().replaceAll("\\[|\\]", ""));
}else {
selectedServiceArray.remove(position);
if (selectedServiceArray.size()== 0) {
serviceTv.setText("0");
} else {
serviceTv.setText(selectedServiceArray.toString());
}
}
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
public ArrayList<String> getServiceId() {
return selectedServiceId;
}
public ArrayList<String> getServices() {
return selectedServiceArray;
}
public Integer getCostArray() {
Integer cost = null;
if(selectedServiceCost.size()>1){
cost=selectedServiceCost.get(0)+selectedServiceCost.get(1);
}else {
cost=selectedServiceCost.get(0);
}
return cost;
}
public Integer getDurationArr() {
Integer duration=null;
if(durationArr.size()>1){
duration=durationArr.get(0)+durationArr.get(1);
}else {
duration=durationArr.get(0);
}
return duration;
}
public ArrayList<ArrayList<String>> getSelectedStylistId() {
return selectedStylistId;
}
#Override
public int getItemCount() {
return count;
}
private class listViewHolder extends RecyclerView.ViewHolder {
private CheckBox checkBox;
private TextView servicenameTv, serviceCost;
int count = 0;
String strService;
public listViewHolder(final View itemView) {
super(itemView);
try {
servicenameTv = (TextView) itemView.findViewById(R.id.damerServiceTV);
serviceCost = (TextView) itemView.findViewById(R.id.damerRsTV);
checkBox = (CheckBox) itemView.findViewById(R.id.checkBox);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
This is the recycleradapter i am using to populate array and checkbox.i want to setText for selected items.If i deselect the items i want to remove text from textview.When i select one item select and deselect is working properly.If i had more than one or if i select and deselct multiples times its not working giving index error
You are trying to delete an item at the given ReciclerView selection, but this position is wrong because you are doing:
selectedServiceArray.add(service);
So you don't know the position which is added because could be other items in this array. You have to request delete the object instead the position. Try this:
if(checkbox.isChecked){
String service=serviceArray.get(getAdapterPosition);
selectedServiceArray.add(service);
holder.serviceNameTv.setText(selectedServiceArray.toString);
} else {
String service=serviceArray.get(getAdapterPosition);
selectedServiceArray.remove(service);
holder.serviceNameTv.setText(selectedServiceArray.toString);
}
Do it like this : -
if(checkbox.isChecked){
String service=serviceArray.get(getAdapterPosition)
selectedServiceArray.add(service);
holder.serviceNameTv.setText(selectedServiceArray.toString);
}
else{
selectedServiceArray.remove(getAdapterPosition);
if (selectedServiceArray.size = 0) {
holder.serviceNameTv.setText("0");
} else{
holder.serviceNameTv.setText(selectedServiceArray.toString);
}

Repeated data in my spinner and ListView

I have a problem receiving data from my database. As determined in my codes, my database (TBL_MAHRIE) contains three columns (ID , COL_SAL , COL_NERKH). Running my project, I received repeated data in both of spinner and ListView.
Mahrie.java (MY SPINNER LOAD HERE)
package ir.dadpardaz.mahrie_dadpardaz;
import java.util.ArrayList;
import java.util.List;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
public class Mahrie extends Activity {
private Spinner spinner_sal1, spinner_sal2;
private Button btn_calc;
EditText ed_shakhes_Nekah, ed_shakhes_Motalebe;
TextView tv_res;
float shakhes_Nekah, shakes_Motalebe, final_Res;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mahrie);
ed_shakhes_Motalebe = (EditText) findViewById(R.id.ed_shakhes_Motalebe);
ed_shakhes_Nekah = (EditText) findViewById(R.id.ed_shakes_Nekah);
tv_res = (TextView) findViewById(R.id.tv_res);
// DATABASE
DataBaseHandler databaseAdapter = new DataBaseHandler(this);
Shakhes shakhes1 = new Shakhes("1392", "250");
databaseAdapter.insertShakhes(shakhes1);
Shakhes shakhes2 = new Shakhes("1391", "200");
databaseAdapter.insertShakhes(shakhes2);
Shakhes shakhes3 = new Shakhes("1390", "150");
databaseAdapter.insertShakhes(shakhes3);
Shakhes shakhes4 = new Shakhes("1389", "100");
databaseAdapter.insertShakhes(shakhes4);
Shakhes shakhes5 = new Shakhes("1388", "50");
databaseAdapter.insertShakhes(shakhes5);
Shakhes shakhes6 = new Shakhes("1387", "25");
databaseAdapter.insertShakhes(shakhes6);
addItemsOnSpinner2();
addListenerOnButton();
addListenerOnSpinnerItemSelection();
}
// add items into spinner dynamically
public void addItemsOnSpinner2() {
spinner_sal2 = (Spinner) findViewById(R.id.spinner_Sal2);
List<String> list = new ArrayList<String>();
DataBaseHandler databaseAdapter = new DataBaseHandler(this);
List<Shakhes> data_shakhes = null;
data_shakhes = databaseAdapter.getAllShakhes();
Context context = getApplicationContext();
for (int i = 0; i < data_shakhes.size(); i++) {
list.add((data_shakhes.get(i).getSal()));
}
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, list);
dataAdapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner_sal2.setAdapter(dataAdapter);
}
public void addListenerOnSpinnerItemSelection() {
spinner_sal1 = (Spinner) findViewById(R.id.spinner_Sal1);
spinner_sal1
.setOnItemSelectedListener(new CustomOnItemSelectedListener());
}
// get the selected dropdown list value
public void addListenerOnButton() {
spinner_sal1 = (Spinner) this.findViewById(R.id.spinner_Sal1);
spinner_sal2 = (Spinner) findViewById(R.id.spinner_Sal2);
btn_calc = (Button) findViewById(R.id.btn_calc);
btn_calc.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
shakhes_Nekah = Float.parseFloat(ed_shakhes_Nekah.getText()
.toString());
shakes_Motalebe = Float.parseFloat(ed_shakhes_Motalebe
.getText().toString());
final_Res = shakes_Motalebe / shakhes_Nekah;
tv_res.setText(final_Res + "");
}
});
}
}
2.DataBase Handler.java
package ir.dadpardaz.mahrie_dadpardaz;
import java.util.ArrayList;
import java.util.List;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.widget.ToggleButton;
public class DataBaseHandler {
SQLiteDatabase database;
public DataBaseHandler(Context context) {
ShakhesDatabaseOpenHelper shakhesDatabaseOpenHelper = new ShakhesDatabaseOpenHelper(
context, "shakhsdb.db", null, 1);
database = shakhesDatabaseOpenHelper.getWritableDatabase();
}
public class ShakhesDatabaseOpenHelper extends SQLiteOpenHelper {
public ShakhesDatabaseOpenHelper(Context context, String name,
CursorFactory factory, int version) {
super(context, name, factory, version);
}
#Override
public void onCreate(SQLiteDatabase db) {
//db.execSQL("DROP TABLE IF EXISTS "+ "TBL_MAHRIE");
String query = "create table IF NOT EXISTS TBL_MAHRIE (ID INTEGER PRIMARY KEY, COL_SAL TEXT, COL_NERKH TEXT)";
db.execSQL(query);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS "+ "TBL_MAHRIE");
}
}
public long insertShakhes(Shakhes shakhes) {
ContentValues values = new ContentValues();
values.put("COL_SAL", shakhes.getSal());
values.put("COL_NERKH", shakhes.getNerkh());
return database.insert("TBL_MAHRIE", null, values);
}
boolean isTableExists(SQLiteDatabase db, String tableName) {
if (tableName == null || db == null || !db.isOpen()) {
return false;
}
Cursor cursor = db
.rawQuery(
"SELECT COUNT(*) FROM sqlite_master WHERE type = ? AND name = ?",
new String[] { "table", tableName });
if (!cursor.moveToFirst()) {
return false;
}
int count = cursor.getInt(0);
cursor.close();
return count > 0;
}
public List<Shakhes> getAllShakhes() {
List<Shakhes> shakhess = null;
Cursor c = database.rawQuery("SELECT * FROM TBL_MAHRIE",null);
//Cursor c = database.query("TBL_MAHRIE", new String[] { "ID", "COL_SAL", "COL_NERKH" }, null, null, null, null, null);
shakhess = new ArrayList<Shakhes>();
Shakhes p = new Shakhes();
if (c.moveToFirst()) {
do {
p.setId((int) c.getLong(c.getColumnIndex("ID")));
p.setSal(c.getString(c.getColumnIndex("COL_SAL")));
p.setNerkh(c.getString(c.getColumnIndex("COL_NERKH")));
shakhess.add(p);
} while (c.moveToNext());
return shakhess;
}
return shakhess;
}
}
Mahrie_JadvalActivity (My ListView inflate here)
package ir.dadpardaz.mahrie_dadpardaz;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class Mahrie_JadvalActivity extends Activity {
ListView personListView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mahrie__jadval);
personListView = (ListView) findViewById(R.id.personListView);
DataBaseHandler databaseAdapter = new DataBaseHandler(this);
Shakhes shakhes1 = new Shakhes("2392" , "250");
databaseAdapter.insertShakhes(shakhes1);
Shakhes shakhes2 = new Shakhes("2391" , "200");
databaseAdapter.insertShakhes(shakhes2);
Shakhes shakhes3 = new Shakhes("2390" , "150");
databaseAdapter.insertShakhes(shakhes3);
Shakhes shakhes4 = new Shakhes("2389" , "100");
databaseAdapter.insertShakhes(shakhes4);
Shakhes shakhes5 = new Shakhes("2388" , "50");
databaseAdapter.insertShakhes(shakhes5);
Shakhes shakhes6 = new Shakhes("2387" , "25");
databaseAdapter.insertShakhes(shakhes6);
List<Shakhes> shakhes =
databaseAdapter.getAllShakhes() ;
ShakhesListViewAdapter shakhesListViewAdapter = new ShakhesListViewAdapter(this, R.layout.mahrie_list_view_item, shakhes);
personListView.setAdapter(shakhesListViewAdapter);
}
public class ShakhesListViewAdapter extends ArrayAdapter<Shakhes> {
List<Shakhes> data;
Context context;
public ShakhesListViewAdapter(Context context, int resourceId, List<Shakhes> data) {
super(context, resourceId, data);
this.data = data;
this.context = context;
}
#Override
public View getView(final int position, View item, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
item = inflater.inflate(R.layout.mahrie_list_view_item, parent , false);
TextView familyTextView = (TextView) item.findViewById(R.id.familyTextView);
familyTextView.setText(data.get(position).getSal()) ;
//familyTextView.setTypeface(bYekan);
TextView nameTextView = (TextView) item.findViewById(R.id.nameTextView);
nameTextView.setText(data.get(position).getNerkh()) ;
//nameTextView.setTypeface(bYekan);
Button detailsButton = (Button) item.findViewById(R.id.detailsButton);
detailsButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Toast.makeText(context,
// data.get(position).getSal() + " " + data.get(position).getNerkh(),
// Toast.LENGTH_LONG).show();
Toast.makeText(context,
data.size()+"" + " and ID is " + position + "" ,
Toast.LENGTH_LONG).show();
}
});
//item.startAnimation(animation);
return item;
}
} }
4.Shakhes.java
package ir.dadpardaz.mahrie_dadpardaz;
public class Shakhes {
public int id ;
public static String sal ;
public static String nerkh ;
public Shakhes(int id, String sal, String nerkh) {
super();
this.id = id;
this.sal = sal;
this.nerkh = nerkh;
}
public Shakhes(String sal, String nerkh) {
super();
this.sal = sal;
this.nerkh = nerkh;
}
public Shakhes() {
}
public int getId() {
return this.id;
}
public void setId(int id) {
this.id = id;
}
public String getSal() {
return sal;
}
public void setSal(String sal) {
this.sal = sal;
}
public String getNerkh() {
return nerkh;
}
public void setNerkh(String nerkh) {
this.nerkh = nerkh;
}
}
Inside your DataBaseHandler.java , Make the following change
public List<Shakhes> getAllShakhes() {
List<Shakhes> shakhess = null;
Cursor c = database.rawQuery("SELECT * FROM TBL_MAHRIE",null);
//Cursor c = database.query("TBL_MAHRIE", new String[] { "ID", "COL_SAL", "COL_NERKH" }, null, null, null, null, null);
shakhess = new ArrayList<Shakhes>();
if (c.moveToFirst()) {
do {
Shakhes p = new Shakhes();
p.setId((int) c.getLong(c.getColumnIndex("ID")));
p.setSal(c.getString(c.getColumnIndex("COL_SAL")));
p.setNerkh(c.getString(c.getColumnIndex("COL_NERKH")));
shakhess.add(p);
} while (c.moveToNext());
return shakhess;
}
return shakhess;
}
}
code the line Shakhes p = new Shakhes(); inside do-while loop. Otherwise it will overwrite the old one, and the same will be added in arraylist.

Making remote server calls in an Android application

I've made an apache thrift server and I have a service which contains several functions.
I'm trying to figure out what is the best way to make calls to the remote server from my android application.
My problem is that I can't make calls from the MainActivity thread (the main thread) - and I need to use most of the remote functions in my main activity methods.
I tried to make a static class with a static member called "Server" equals to the server object, and I set it in another thread and then I tried to call it in the main thread (the main activity class) - but I had errors because of jumping from one thread to another..
To be more specified I want something like that:
public class MainActivity extends Activity {
private service.Client myService;
#Override
protected void onCreate(Bundle savedInstanceState) {
..
... Some stuff that define myService (In a new thread ofcourse) ...
}
...
private void MyFunc1() {
myService.Method1();
}
private void MyFunc2() {
myService.Method2();
}
private void MyFunc3() {
myService.Method3();
}
}
I've got a library for talking to REST APIs. Feel free to slice, dice, and re-use: https://github.com/nedwidek/Android-Rest-API
The code is BSD or GPL.
Here's how I use what I have (I've trimmed MainActivity a bit, hopefully not too much):
package com.hatterassoftware.voterguide.api;
import java.util.HashMap;
public class GoogleCivicApi {
protected final String baseUrl = "https://www.googleapis.com/civicinfo/us_v1/";
protected String apiKey = "AIzaSyBZIP5uY_fMF35SVVrytpKgHtppBbj8J0I";
public static final String DATE_FORMAT = "yyyy-MM-dd";
protected static HashMap<String, String> headers;
static {
headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json");
}
public String createUrl(String uri, HashMap<String, String> params) {
String url = baseUrl + uri + "?key=" + apiKey;
if (params != null) {
for (String hashKey: params.keySet()) {
url += hashKey + "=" + params.get(hashKey) + "&";
}
url = url.substring(0, url.length());
}
return url;
}
}
package com.hatterassoftware.voterguide.api;
import android.util.Log;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.hatterassoftware.restapi.GetTask;
import com.hatterassoftware.restapi.HttpReturn;
import com.hatterassoftware.restapi.RestCallback;
import com.hatterassoftware.voterguide.api.callbacks.ElectionCallback;
import com.hatterassoftware.voterguide.api.models.Election;
public class ElectionsQuery extends GoogleCivicApi implements RestCallback {
GetTask getTask;
ElectionCallback callback;
final String TAG = "ElectionQuery";
public ElectionsQuery(ElectionCallback callback) {
String url = this.createUrl("elections", null);
this.callback = callback;
Log.d(TAG, "Creating and executing task for: " + url);
getTask = new GetTask(url, this, null, null, null);
getTask.execute();
}
#Override
public void onPostSuccess() {
Log.d(TAG, "onPostSuccess entered");
}
#Override
public void onTaskComplete(HttpReturn httpReturn) {
Log.d(TAG, "onTaskComplete entered");
Log.d(TAG, "httpReturn.status = " + httpReturn.status);
if (httpReturn.content != null) Log.d(TAG, httpReturn.content);
if (httpReturn.restException != null) Log.d(TAG, "Exception in httpReturn", httpReturn.restException);
JsonParser parser = new JsonParser();
JsonElement electionArrayJson = ((JsonObject)parser.parse(httpReturn.content)).get("elections");
Log.d(TAG, electionArrayJson.toString());
Gson gson = new GsonBuilder().setDateFormat(GoogleCivicApi.DATE_FORMAT).create();
Election[] elections = gson.fromJson(electionArrayJson.toString(), Election[].class);
callback.retrievedElection(elections);
}
}
package com.hatterassoftware.voterguide;
import java.util.Calendar;
import java.util.List;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.hatterassoftware.voterguide.api.ElectionsQuery;
import com.hatterassoftware.voterguide.api.VoterInfoQuery;
import com.hatterassoftware.voterguide.api.callbacks.ElectionCallback;
import com.hatterassoftware.voterguide.api.callbacks.VoterInfoCallback;
import com.hatterassoftware.voterguide.api.models.Election;
import com.hatterassoftware.voterguide.api.models.VoterInfo;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.text.Editable;
import android.text.Html;
import android.text.TextWatcher;
import android.text.method.LinkMovementMethod;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends SherlockFragmentActivity implements ElectionCallback, VoterInfoCallback {
private ProgressBar mProgressBar;
public Button submit;
public Spinner state;
public Spinner election;
public EditText address;
public EditText city;
public EditText zip;
private int count=0;
private Object lock = new Object();
private static final String TAG = "MainActivity";
public static final String VOTER_INFO = "com.hatterassoftware.voterguide.VOTER_INFO";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mProgressBar = (ProgressBar) findViewById(R.id.home_progressBar);
Resources res = getResources();
SharedPreferences mPrefs = getApplicationSharedPreferences();
ImageButton gpsButton = (ImageButton) findViewById(R.id.locate);
try {
LocationManager manager = (LocationManager) getSystemService( Context.LOCATION_SERVICE );
if (!manager.isProviderEnabled(Context.LOCATION_SERVICE)) {
gpsButton.setClickable(false);
}
} catch(Exception e) {
Log.d(TAG, e.getMessage(), e);
gpsButton.setClickable(false);
gpsButton.setEnabled(false);
}
submit = (Button) findViewById(R.id.submit);
submit.setClickable(false);
submit.setEnabled(false);
state = (Spinner) findViewById(R.id.state);
election = (Spinner) findViewById(R.id.election);
address = (EditText) findViewById(R.id.streetAdress);
city = (EditText) findViewById(R.id.city);
zip = (EditText) findViewById(R.id.zip);
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
doSubmit();
}
});
gpsButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
doLocate();
}
});
// Let's check for network connectivity before we get down to business.
if (Utils.isNetworkAvailable(this, true)) {
// Show the disclaimer on first run.
if(mPrefs.getBoolean("firstRun", true)) {
AlertDialog alert = new AlertDialog.Builder(this).create();
alert.setCancelable(false);
alert.setTitle(res.getString(R.string.welcome));
LayoutInflater inflater = (LayoutInflater) this.getSystemService(LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.custom_dialog, null);
TextView alertContents = (TextView) layout.findViewById(R.id.custom_dialog_text);
alertContents.setMovementMethod(LinkMovementMethod.getInstance());
alertContents.setText(Html.fromHtml(res.getString(R.string.welcome_dialog_text)));
alert.setView(alertContents);
alert.setButton(AlertDialog.BUTTON_POSITIVE, "OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
SharedPreferences mPrefs = getApplicationSharedPreferences();
SharedPreferences.Editor editor = mPrefs.edit();
editor.putBoolean("firstRun", false);
editor.commit();
dialog.dismiss();
retrieveElections();
}
});
alert.show();
} else {
retrieveElections();
}
}
}
#Override
public void onResume() {
super.onResume();
// Let's check for network connectivity before we get down to business.
Utils.isNetworkAvailable(this, true);
LocationManager manager = (LocationManager) getSystemService( Context.LOCATION_SERVICE );
if (!(manager.isProviderEnabled(LocationManager.GPS_PROVIDER)
|| manager.isProviderEnabled(LocationManager.NETWORK_PROVIDER))) {
Toast.makeText(this, "GPS is not available", 2).show();
ImageButton gpsButton = (ImageButton) findViewById(R.id.locate);
gpsButton.setClickable(false);
}
}
public SharedPreferences getApplicationSharedPreferences() {
Context mContext = this.getApplicationContext();
return mContext.getSharedPreferences("com.hatterassoftware.voterguide", MODE_PRIVATE);
}
private void showSpinner() {
synchronized(lock) {
count++;
mProgressBar.setVisibility(View.VISIBLE);
}
}
private void hideSpinner() {
synchronized(lock) {
count--;
if(count < 0) { // Somehow we're trying to hide it more times than we've shown it.
count=0;
}
if (count == 0) {
mProgressBar.setVisibility(View.INVISIBLE);
}
}
}
public void retrieveElections() {
Log.d(TAG, "Retrieving the elections");
showSpinner();
ElectionsQuery query = new ElectionsQuery(this);
}
#Override
public void retrievedElection(Election... elections) {
Log.d(TAG, "Retrieved the elections");
hideSpinner();
for (int i=0; i<elections.length; i++) {
Log.d(TAG, elections[i].toString());
}
ArrayAdapter arrayAdapter = new ArrayAdapter(this, android.R.layout.simple_spinner_item, elections);
arrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
Spinner spinner = (Spinner) this.findViewById(R.id.election);
spinner.setAdapter(arrayAdapter);
}
}

Categories