Populate AlertDialog With Values - android

I am new to programming and started with android development out of passion and this is my second application.
I looked into android tutorials online and was trying to do this:
1. Record button in mainaactivity
2. On-click opens up a dialog box which gives options to record.
3. Dialog box has four buttons (Start, Stop, Playback, Stop Playback).
What is working:
1. On click shows a dialog box, but no options in it.
2. Record works, when played as a different activity.
I believe I have missed something, can someone help?
//MainActivity.java
import android.app.AlertDialog;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v7.app.ActionBarActivity;
import android.view.LayoutInflater;
import android.support.v4.app.DialogFragment;
import android.view.View;
public class MainActivity extends FragmentActivity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void RecordClick(View v){
RecordDialog dialog = new RecordDialog();
dialog.show(getFragmentManager(),"Record_Dialog");
}
}
//Dialog.java
package com.example.record;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.DialogInterface;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.ActionBarActivity;
import android.view.LayoutInflater;
import android.view.View;
import java.io.File;
import java.io.IOException;
public class RecordDialog extends DialogFragment{
View v;
private MediaPlayer mediaPlayer;
private MediaRecorder mediaRecorder;
private String store_file;
/* #Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
LayoutInflater inflator = getActivity().getLayoutInflater();
v = inflator.inflate(R.layout.customdialog, null);
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setView(v).setPositiveButton("DONE", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
}
}).setNegativeButton("CANCEL", new DialogInterface.OnClickListener(){
#Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
return builder.create();
}
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LayoutInflater inflator = getActivity().getLayoutInflater();
v = inflator.inflate(R.layout.customdialog, null);
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
store_file= Environment.getExternalStorageDirectory()+"/audiorecorder.3gpp";
}
public void onButtonClick(View v){
switch (v.getId()){
case R.id.Startbtn:
try{
startRecording();
}
catch(Exception e){
e.printStackTrace();
}break;
case R.id.Stopbtn:
try{
stopRecording();
}
catch(Exception e){
e.printStackTrace();
}break;
case R.id.PlayBackbtn:
try{
startPlayBack();
}
catch(Exception e){
e.printStackTrace();
}break;
case R.id.StopPlayingbtn:
try{
stopPlayBack();
}
catch(Exception e){
e.printStackTrace();
}break;
}
}
private void startRecording() throws IOException {
discardMediaRecorder();
File storeFile= new File(store_file);
if(storeFile.exists())
storeFile.delete();
mediaRecorder = new MediaRecorder();
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
mediaRecorder.setOutputFile(store_file);
mediaRecorder.prepare();
mediaRecorder.start();
}
private void discardMediaRecorder(){
if (mediaRecorder != null)
mediaRecorder.release();
}
private void stopRecording() {
if (mediaRecorder != null)
mediaRecorder.stop();
}
private void startPlayBack() throws IOException {
discardMediaPlayer();
mediaPlayer = new MediaPlayer();
mediaPlayer.setDataSource(store_file);
mediaPlayer.prepare();
mediaPlayer.start();
}
private void discardMediaPlayer() {
if (mediaPlayer != null)
{
try{
mediaPlayer.release();
}catch (Exception e) {
e.printStackTrace();
}
}
}
private void stopPlayBack() {
if (mediaPlayer != null)
mediaPlayer.stop();
}
}
//Dialog.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:clickable="true">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/record"
android:id="#+id/imageView" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Start"
android:id="#+id/Startbtn"
android:layout_marginLeft="67dp"
android:layout_marginStart="67dp"
android:onClick="onButtonClick"
android:layout_below="#+id/imageView"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="70dp" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Stop"
android:id="#+id/Stopbtn"
android:layout_marginLeft="59dp"
android:layout_marginStart="59dp"
android:layout_alignTop="#+id/Startbtn"
android:layout_toRightOf="#+id/Startbtn"
android:layout_toEndOf="#+id/Startbtn"
android:onClick="onButtonClick"
android:clickable="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="PlayBlack"
android:id="#+id/PlayBackbtn"
android:onClick="onButtonClick"
android:clickable="true"
android:layout_centerVertical="true"
android:layout_alignLeft="#+id/Startbtn"
android:layout_alignStart="#+id/Startbtn" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="StopPlaying"
android:id="#+id/StopPlayingbtn"
android:onClick="onButtonClick"
android:nestedScrollingEnabled="true"
android:clickable="true"
android:layout_centerVertical="true"
android:layout_alignLeft="#+id/Stopbtn"
android:layout_alignStart="#+id/Stopbtn" />
</RelativeLayout>

Related

All SeekBar + onProgressChanged + MediaPlayer + MeidaPlayer.getDuration() + Android OS Bugs do not work with me I have "The Ultimate Solution"

I have tried all the solutions on StackOverflow and none solved my issue, I'm looking for the ultimate solution, for the problem, I can solve all these problems with one working code? and 1 software.
Also, I added how to load lyrics using volley, and the PHP backend code.
The Ultimate Solution is: reencode your video or audio with an encoder that put seek points of the video or audio in the start index of the file and I found one good free software that solves this problem, which is "Miro Video Converter"
Note: mp3 encoding should be 128kb or more before using Miro Video
Encoder
and the Ultimate code that Will Work for Sure with this Excellent Encoding for audio is (video is the same solution but you change the code to what your video player code is I'm making a songs player with lyrics fragment):
Java:: "SongsFragment.java"
package com.emadzedan.acdc;
import android.annotation.SuppressLint;
import android.content.SharedPreferences;
import android.graphics.PorterDuff;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.text.Html;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.SeekBar;
import android.widget.TextView;
import androidx.fragment.app.Fragment;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import java.io.IOException;
import java.util.Objects;
import static android.content.Context.MODE_PRIVATE;
public class SongsFragment extends Fragment {
private static final String TAG = "Debug: ";
private Button playButton;
private SeekBar seekBar;
private Handler handler;
private Runnable runnable;
private TextView lyricsTextView;
private TextView currentTime;
private SharedPreferences prefs;
public SongsFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_songs, container, false);
AdManager adManager = AdManager.getInstance();
adManager.createAd(getContext());
StringRequest stringRequest = new StringRequest(Request.Method.POST, "path to: volleyLyrics.php"),
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
lyricsTextView = Objects.requireNonNull(getView()).findViewById(R.id.lyricsTextView);
lyricsTextView.setText(Html.fromHtml(response));
DrawerBaseActivity.DisableBackButtonOnLoadSongDetailsError = false;
}
}, new Response.ErrorListener() {
#SuppressLint("SetTextI18n")
#Override
public void onErrorResponse(VolleyError error) {
lyricsTextView = (TextView) Objects.requireNonNull(getView()).findViewById(R.id.lyricsTextView);
lyricsTextView.setText(R.string.lyrics_error);
}
});
MySingleton.getInstance(view.getContext()).addToRequestQueue(stringRequest);
view.setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
if (!DrawerBaseActivity.DisableBackButtonOnLoadSongDetailsError) {
handler.removeCallbacks(runnable);
DrawerBaseActivity.releaseMediaPlayer();
DrawerBaseActivity.titleTextView.setText(R.string.all_songs);
DrawerBaseActivity.CurrentFragment = "Search";
Objects.requireNonNull(getActivity()).onBackPressed();
}
return true;
}
return false;
}
});
playButton = view.findViewById(R.id.playButton);
playButton.setVisibility(View.GONE);
DrawerBaseActivity.mediaPlayer = new MediaPlayer();
DrawerBaseActivity.mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
DrawerBaseActivity.mediaPlayer.seekTo(0);
currentTime = view.findViewById(R.id.currentTime);
handler = new Handler();
seekBar = view.findViewById(R.id.seekBar);
seekBar.getProgressDrawable().setColorFilter(getResources().getColor(R.color.colorAccent), PorterDuff.Mode.SRC_IN);
seekBar.getThumb().setColorFilter(getResources().getColor(R.color.colorAccent), PorterDuff.Mode.SRC_IN);
try {
DrawerBaseActivity.mediaPlayer = new MediaPlayer();
DrawerBaseActivity.mediaPlayer.setDataSource("song.mp3");
DrawerBaseActivity.mediaPlayer.prepare();
DrawerBaseActivity.mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
playButton.setVisibility(View.VISIBLE);
seekBar.setMax(DrawerBaseActivity.mediaPlayer.getDuration());
Log.v(TAG, "getDuration= " + DrawerBaseActivity.mediaPlayer.getDuration());
}
});
} catch (IOException e) {
e.printStackTrace();
}
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if (fromUser) {
DrawerBaseActivity.mediaPlayer.seekTo(progress);
}
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
playButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!DrawerBaseActivity.mediaPlayer.isPlaying()) {
DrawerBaseActivity.mediaPlayer.start();
playCycle();
playButton.setBackgroundResource(R.drawable.pause);
} else {
DrawerBaseActivity.mediaPlayer.pause();
playButton.setBackgroundResource(R.drawable.play);
handler.removeCallbacks(runnable);
}
}
});
DrawerBaseActivity.selectedItem = 0;
handler = new Handler();
Objects.requireNonNull(getActivity()).runOnUiThread(new Runnable() {
#Override
public void run() {
if (DrawerBaseActivity.mediaPlayer != null) {
seekBar.setProgress(DrawerBaseActivity.mediaPlayer.getCurrentPosition());
}
handler.postDelayed(this, 1000);
}
});
return view;
}
private void playCycle() {
if (DrawerBaseActivity.mediaPlayer != null) {
if (DrawerBaseActivity.mediaPlayer.isPlaying()) {
runnable = new Runnable() {
#Override
public void run() {
playCycle();
}
};
handler.postDelayed(runnable, 1000);
seekBar.setProgress(DrawerBaseActivity.mediaPlayer.getCurrentPosition());
currentTime.setText(formatTime(DrawerBaseActivity.mediaPlayer.getCurrentPosition()));
Log.v(TAG, "getCurrentPosition= " + DrawerBaseActivity.mediaPlayer.getCurrentPosition());
} else {
seekBar.setProgress(0);
DrawerBaseActivity.mediaPlayer.seekTo(0);
DrawerBaseActivity.mediaPlayer.pause();
playButton.setBackgroundResource(R.drawable.play);
handler.removeCallbacks(runnable);
}
}
}
#SuppressLint("DefaultLocale")
private String formatTime(int millis) {
int seconds = millis / 1000;
int minutes = seconds / 60;
int hours = minutes / 60;
//you can after ? put "00:"
return (hours == 0 ? "" : hours + ":") + String.format("%02d:%02d", minutes % 60, seconds % 60);
}
}
XML Layout: "fragment_songs.xml"
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/colorWhite"
tools:context=".SongsFragment">
<ScrollView
android:id="#+id/songLyricsScrollView"
android:layout_width="match_parent"
android:layout_alignParentTop="true"
android:layout_marginBottom="70dp"
android:layout_height="match_parent"
android:background="#color/colorWhite">
<TextView
android:id="#+id/lyricsTextView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="10dp"
android:scrollbars="vertical"
android:text="#string/TestLyrics"
android:fontFamily="#font/rudebook"
android:textColor="#color/colorPrimaryDark"
android:textSize="20sp" />
</ScrollView>
<LinearLayout
android:id="#+id/relativeLayout2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:paddingTop="8dp"
android:layout_alignParentBottom="true"
tools:ignore="RtlHardcoded"
android:background="#color/colorPrimaryDark">
<SeekBar
android:id="#+id/seekBar"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="0.90"
android:layout_marginStart="16dp"
android:layout_marginTop="16dp"
/>
<TextView
android:id="#+id/currentTime"
android:layout_width="40dp"
android:layout_height="match_parent"
android:paddingTop="14dp"
android:textColor="#color/colorAccent"
android:text="#string/_00_00"
android:fontFamily="#font/rudelight"
android:textSize="12sp"
android:layout_weight="0.05"
android:layout_marginLeft="10dp" />
<RelativeLayout
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_marginLeft="10dp"
android:layout_marginStart="10dp"
android:layout_weight="0.05"
android:layout_marginBottom="10dp"
tools:ignore="RtlHardcoded">
<Button
android:id="#+id/playButton"
android:layout_width="50dp"
android:layout_height="50dp"
android:visibility="gone"
android:background="#drawable/play"
/>
</RelativeLayout>
</LinearLayout>
</RelativeLayout>
PHP file:: "volleyLyrics.php"
<?php
$albumNumber = $_GET["albumNumber"];
$lyricsNumber = $_GET["lyricsNumber"];
$data = file_get_contents(__DIR__ . "/lyrics.txt") or die("Unable to open file!");
echo nl2br($data);
?>
Note: the text file of the lyrics is in the same directory as the PHP
file

ANdroid not display custom adapter

i work about a vtc app and I need to display on the main screen the orders of the client.
I chose the way of customing the list view with an adapter but when i launch the app nothing on the screen except the title of the page.
i divided the adapter code and the fragment code (yeah i work in a fragment) and i want to have your opinion about my code.
Here the Fragment :
package com.cmn.cmnvtc;
import android.Manifest;
import android.app.Dialog;
import android.app.Fragment;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.Snackbar;
import android.support.v4.app.ActivityCompat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.toolbox.Volley;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GoogleApiAvailability;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class MainPageFragment1 extends Fragment implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener{
private LinearLayout containerView;
private TextView NoCommand;
private UserLocalStore userLocalStore;
private List<Courses> coursesList;
private ListView lvCourses;
private CoursesAdapter coursesAdapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_main1, container, false);
userLocalStore = new UserLocalStore(getActivity());
NoCommand = (TextView) v.findViewById(R.id.NoCommand);
lvCourses = (ListView) v.findViewById(R.id.lvCourses);
coursesList = new ArrayList<>();
final Response.Listener<String> responseListener = new Response.Listener<String>(){
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
boolean success = jsonObject.getBoolean("success");
if(success){
int count = jsonObject.getInt("count");
for(int i=0; i<count; i++) {
JSONObject obj = jsonObject.getJSONObject(String.valueOf(i));
String origin = obj.getString("origin");
String destination = obj.getString("destination");
String date_depart = obj.getString("date_depart");
String heure_depart = obj.getString("heure_depart");
int nb_passagers = Integer.parseInt(obj.getString("nb_passagers"));
float prix = Float.parseFloat(obj.getString("prix"));
String mode_paiement = obj.getString("paiement");
String etat_paiement = obj.getString("course_payee");
Courses course = new Courses(origin, destination, date_depart, heure_depart, nb_passagers, prix
, mode_paiement, etat_paiement);
coursesList.add(course);
}
}else{
NoCommand.setEnabled(true);
NoCommand.setText("Oups... Vous n'avez commandé aucune course pour le moment.");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
User currentUser = userLocalStore.getLoggedInUser();
final GetAllCourseRequest getAllCourse = new GetAllCourseRequest(currentUser.user_id,responseListener);
RequestQueue queue = Volley.newRequestQueue(getActivity());
queue.add(getAllCourse);
coursesAdapter = new CoursesAdapter(getActivity(), coursesList);
lvCourses.setAdapter(coursesAdapter);
lvCourses.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getActivity(), "CLicked", Toast.LENGTH_SHORT).show();
}
});
if (googleServicesAvailable()) {
containerView = (LinearLayout) v.findViewById(R.id.containerView);
askForPermission();
}
return v;
}
public boolean googleServicesAvailable() {
GoogleApiAvailability api = GoogleApiAvailability.getInstance();
int isAvaibable = api.isGooglePlayServicesAvailable(getActivity());
if (isAvaibable == ConnectionResult.SUCCESS) {
return true;
} else if (api.isUserResolvableError(isAvaibable)) {
Dialog dialog = api.getErrorDialog(getActivity(), isAvaibable, 0);
dialog.show();
} else {
Toast.makeText(getActivity(), "Can't connect to play services", Toast.LENGTH_SHORT).show();
}
return false;
}
private void explain() {
Snackbar.make(containerView, "Cette permission est nécessaire pour vous géolocalisez", Snackbar.LENGTH_LONG).setAction("Activer", new View.OnClickListener() {
#Override
public void onClick(View view) {
askForPermission();
}
}).show();
}
private void askForPermission() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION, android.Manifest.permission.ACCESS_COARSE_LOCATION}, 2);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
if (requestCode == 2) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (shouldShowRequestPermissionRationale(permissions[0]) == false) {
displayOptions();
} else {
explain();
}
}
if (grantResults[1] == PackageManager.PERMISSION_GRANTED) {
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (shouldShowRequestPermissionRationale(permissions[1]) == false) {
displayOptions();
} else {
explain();
}
}
}
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
private void displayOptions() {
Snackbar.make(containerView, "Vous avez désactivé la permission", Snackbar.LENGTH_LONG).setAction("Paramètres", new View.OnClickListener() {
#Override
public void onClick(View view) {
final Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
final Uri uri = Uri.fromParts("package", getActivity().getPackageName(), null);
intent.setData(uri);
startActivity(intent);
}
}).show();
}
#Override
public void onConnected(#Nullable Bundle bundle) {
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
}
My custom adapter :
package com.cmn.cmnvtc;
import android.content.Context;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageButton;
import android.widget.TextView;
import org.w3c.dom.Text;
import java.util.List;
/**
* Created by Wild Shadow on 18/06/2017.
*/
public class CoursesAdapter extends BaseAdapter {
private List<Courses> coursesList;
private Context ctx;
public CoursesAdapter(Context context, List<Courses> coursesList) {
this.ctx = context;
this.coursesList = coursesList;
}
#Override
public int getCount() {
return coursesList.size();
}
#Override
public Object getItem(int position) {
return coursesList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = View.inflate(ctx, R.layout.row_courses, null);
TextView adrOrigin = (TextView) v.findViewById(R.id.adrOriginList);
TextView adrDestinaiton = (TextView)
v.findViewById(R.id.adrDestList);
TextView dateDepart = (TextView) v.findViewById(R.id.dateDepList);
TextView heureDepart = (TextView)
v.findViewById(R.id.heureDepList);
ImageButton viewDetails = (ImageButton)
v.findViewById(R.id.viewDetailsCourse);
adrOrigin.setText(coursesList.get(position).getOrigin());
adrDestinaiton.setText(coursesList.get(position).getDestination());
dateDepart.setText(coursesList.get(position).getDate_depart());
heureDepart.setText(coursesList.get(position).getHeure_depart());
return v;
}
}
the model layout :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="6dp">
<LinearLayout
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="5dp">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_depart_courselist"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/adrOriginList"
android:textSize="17dp"
android:textColor="#000"
android:paddingTop="3dp"
android:text=" : Adresse de départ"/>
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_destination_courselist"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/adrDestList"
android:paddingTop="3dp"
android:textColor="#000"
android:textSize="17dp"
android:text=" : Adresse d'arrivée"
android:layout_marginBottom="5dp"/>
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_date_depart_courselist"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/dateDepList"
android:paddingTop="3dp"
android:textColor="#000"
android:textSize="17dp"
android:text=" : date de départ"
android:layout_marginBottom="3dp"
android:layout_marginRight="20dp"/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_heure_dep_courselist"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/heureDepList"
android:paddingTop="3dp"
android:textColor="#000"
android:textSize="17dp"
android:text=" : Heure"
android:layout_marginBottom="3dp"/>
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_details_courselist"
android:layout_marginLeft="65dp"
android:id="#+id/viewDetailsCourse"
android:paddingTop="5dp"
android:background="?android:selectableItemBackground"/>
</LinearLayout>
</LinearLayout>
</LinearLayout>
and the listview :
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingTop="10dp"
android:theme="#style/AppTheme"
tools:context="com.cmn.cmnvtc.MainPageFragment1">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center_horizontal">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAlignment="center"
android:id="#+id/TitleListCommand"
android:textSize="25dp"
android:layout_marginBottom="15dp"
android:textColor="#727574"
android:text="Liste de mes courses "/>
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/TitleListCommand"
android:layout_alignParentStart="true"
android:id="#+id/lvCourses"></ListView>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="200dp"
android:textColor="#969696"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:textSize="15dp"
android:textAlignment="center"
android:id="#+id/NoCommand"
android:text=""
android:enabled="false"/>
</RelativeLayout>
</ScrollView>
I hope you will help me to find the error and if you want more, try to explain me how i can optimize my code. TY
You should call notifyDataSetChanged() in the ResponseListener after filling your list.
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
boolean success = jsonObject.getBoolean("success");
if(success){
int count = jsonObject.getInt("count");
for(int i=0; i<count; i++) {
...
coursesList.add(course);
}
//notify adapter about change in data
coursesAdapter.notifyDataSetChanged();
}else{
NoCommand.setEnabled(true);
NoCommand.setText("Oups... Vous n'avez commandé aucune course pour le moment.");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};

Android text to speech not working on mobile

i am having problem in text to speech. have this code in java class
package com.techblogon.loginexample;
import java.util.Locale;
import android.os.Bundle;
import android.app.Activity;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.Toast;
public class listenActivity extends Activity implements OnClickListener, OnInitListener {
private TextToSpeech tts;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.categories);
tts = new TextToSpeech(this, this);
findViewById(R.id.button1).setOnClickListener(this);
}
#Override
public void onClick(View v) {
if (tts!=null) {
String text = ((EditText)findViewById(R.id.editText1)).getText().toString();
if (text!=null) {
if (!tts.isSpeaking()) {
tts.speak(text, TextToSpeech.QUEUE_FLUSH, null);
}
}
}
}
#Override
public void onInit(int code) {
if (code==TextToSpeech.SUCCESS) {
tts.setLanguage(Locale.getDefault());
} else {
tts = null;
Toast.makeText(this, "Failed to initialize TTS engine.", Toast.LENGTH_SHORT).show();
}
}
#Override
protected void onDestroy() {
if (tts!=null) {
tts.stop();
tts.shutdown();
}
super.onDestroy();
}
}
and xml file has this code
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".listenActivity" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TTS Demonstration" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/editText1"
android:layout_centerHorizontal="true"
android:layout_marginTop="43dp"
android:text="Say It" />
<EditText
android:id="#+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/textView1"
android:layout_centerHorizontal="true"
android:layout_marginTop="77dp"
android:ems="10"
android:text="Hello world!" />
</RelativeLayout>
but issue is when i click button no sound heard on my mobile. does i need any permission for that
any help
Many thanks

Android TextToSpeech doesn't work

I would like to use TTS in my application. First of all I'm trying to run some examples, but every time TTS doesn't work on my device. In example I have the code:
MainActivity:
package com.example.tts;
import java.util.Locale;
import android.app.Activity;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends Activity implements TextToSpeech.OnInitListener {
private TextToSpeech textToSpeech;
private Button button;
private EditText inputText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.button1);
inputText = (EditText) findViewById(R.id.inputText);
textToSpeech = new TextToSpeech(this, this);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
convertTextToSpeech();
}
});
convertTextToSpeech();
}
#Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
int result = textToSpeech.setLanguage(Locale.US);
if (result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED) {
Log.e("error", "This Language is not supported");
} else {
convertTextToSpeech();
}
} else {
Log.e("error", "Initilization Failed!");
}
}
#Override
public void onDestroy() {
textToSpeech.shutdown();
super.onDestroy();
}
private void convertTextToSpeech() {
//String text = "test";
String text = inputText.getText().toString();
if (null == text || "".equals(text)) {
text = "Please give some input.";
}
textToSpeech.speak(text, TextToSpeech.QUEUE_FLUSH, null);
}
}
activity_main.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".TextToSpeechActivity" >
<EditText
android:id="#+id/inputText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="42dp"
android:layout_marginTop="28dp"
android:ems="10" >
<requestFocus />
</EditText>
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/inputText"
android:layout_below="#+id/inputText"
android:layout_marginTop="14dp"
android:text="Speak" />
</RelativeLayout>
After typing the word and clicking button application says nothing.
Does anyone have an idea how to solve it? Thanks in advance.

Call multiple services in background in android

I have to call multiple services in background for a project in android app.
In each services i have to call separate web service and get some data and process it with local sqlite database. I am able to call each service separately and can manipulate its result with local database.
But not able to call all services in a sequence.
my code is as below:
#Override
public void onStart(Intent intent, int startid) {
Toast.makeText(this, "My Service Started", Toast.LENGTH_LONG).show();
Timer timer = new Timer();
final SyncTableUsers syncUserObj = new SyncTableUsers(LocalService.this);
final SyncTableVehicles syncVehicleObj = new SyncTableVehicles(this);
final SyncTableLicenses syncLicenseObj = new SyncTableLicenses(this);
final SyncTableTags syncTagObj = new SyncTableTags(this);
final SyncTableTagMappings syncTagMapObj = new SyncTableTagMappings(this);
final SyncTableAddresses syncAddressObj = new SyncTableAddresses(this);
final SyncTableDispatches syncDispatchObj = new SyncTableDispatches(this);
final SyncEditCompany syncCompanyObj = new SyncEditCompany(LocalService.this);
final SyncEditVehicle syncEditVehicleObj = new SyncEditVehicle(LocalService.this);
final SyncEditUser syncEditUserObj = new SyncEditUser(this);
final SyncVehicleLog vLogObj = new SyncVehicleLog(LocalService.this);
TimerTask timerTask = new TimerTask() {
#Override
public void run() {
syncUserObj.syncUserData();
syncVehicleObj.syncVehicleData();
syncLicenseObj.syncLicensesData();
syncTagObj.syncTagData();
syncTagMapObj.syncTagMappingData();
syncAddressObj.syncAddressData();
syncDispatchObj.syncDispatchData();
syncCompanyObj.syncCompanyData();
syncEditVehicleObj.syncVehicleData();
syncEditUserObj.syncUserData();
Log.i("TAG", "LogId After insert values ");
}
}
};
timer.scheduleAtFixedRate(timerTask, 10000, 180000); call after every
3 minute
super.onStart(intent, startid);
syncUserData is a method, which call web service.
I recommend you go for the AsyncTask solution. It is an easy and straightforward way of running requests or any other background tasks and calling web services using devices having latest OS virsion you must need to use AsyncTask.
It's also easy to implement e.g. onProgressUpdate if you need to show a progress bar of some sort while running your requests.
private class YourTask extends AsyncTask<URL, Integer, Long> {
protected Long doInBackground(URL... urls) {
//call your methods from here
//publish yor progress here..
publishProgress((int) ((i / (float) count) * 100));
}
protected void onProgressUpdate(Integer... progress) {
setProgressPercent(progress[0]);
}
protected void onPostExecute(Long result) {
//action after execution success or not
}
}
Use Intent Service to execute your tasks in sequence.
Check out the below link for details
https://developer.android.com/reference/android/app/IntentService.html
<uses-sdk
android:minSdkVersion="8"
tools:ignore="GradleOverrides" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
Videocapture Activity - activitymain
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<SurfaceView
android:id="#+id/CameraView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="bottom"
android:orientation="vertical">
<LinearLayout
android:gravity="center_vertical"
android:background="#color/color_transparent"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:layout_width="match_parent"
android:layout_height="150dp"
android:orientation="horizontal">
<TextView
android:id="#+id/txt_cancel"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="Cancel"
android:layout_weight="1"
android:textSize="30dp"
android:textColor="#color/color_white" />
<CheckBox
android:button="#drawable/checkbox"
android:id="#+id/chk_videorecord"
android:layout_width="100dp"
android:layout_height="100dp"
android:textColor="#color/color_white"
android:textOff="#null"
android:textOn="#null" />
<TextView
android:id="#+id/txt_submit"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="Submit"
android:textSize="30dp"
android:textColor="#color/color_white" />
</LinearLayout>
</LinearLayout>
</RelativeLayout>
</LinearLayout>
import java.io.File;
import java.io.IOException;
import android.app.Activity;
import android.content.Intent;
import android.hardware.Camera;
import android.media.CamcorderProfile;
import android.media.MediaRecorder;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.MediaController;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;
import android.widget.VideoView;
public class VideoCapture extends Activity implements OnClickListener, SurfaceHolder.Callback {
public static final String LOGTAG = "VIDEOCAPTURE";
private MediaRecorder recorder;
private SurfaceHolder holder;
private CamcorderProfile camcorderProfile;
private Camera camera;
boolean recording = false;
boolean usecamera = true;
boolean previewRunning = false;
TextView txt_cancel, txt_submit;
CheckBox chk_videorecord;
private String str_record_file;
private Uri uri;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
camcorderProfile = CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH);
setContentView(R.layout.activity_main);
chk_videorecord = findViewById(R.id.chk_videorecord);
final SurfaceView cameraView = (SurfaceView) findViewById(R.id.CameraView);
txt_cancel = findViewById(R.id.txt_cancel);
txt_submit = findViewById(R.id.txt_submit);
holder = cameraView.getHolder();
holder.addCallback(this);
holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
cameraView.setClickable(true);
cameraView.setOnClickListener(this);
chk_videorecord.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (chk_videorecord.isChecked())
{
chk_videorecord.setBackgroundDrawable(getResources().getDrawable(R.drawable.img_stop_record));
recording = true;
recorder.start();
Toast.makeText(VideoCapture.this, "Recording Started", Toast.LENGTH_SHORT).show();
} else {
chk_videorecord.setBackgroundDrawable(getResources().getDrawable(R.drawable.img_start_record));
recorder.stop();
Toast.makeText(VideoCapture.this, "Recording Stop", Toast.LENGTH_SHORT).show();
if (usecamera) {
try {
camera.reconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
// recorder.release();
recording = false;
Log.v(LOGTAG, "Recording Stopped");
// Let's prepareRecorder so we can record again
prepareRecorder();
}
}
});
txt_cancel.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
txt_submit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v)
{
if(str_record_file!=null) {
Intent intent = new Intent(VideoCapture.this, HomeActivity.class);
intent.putExtra("str_record_file", str_record_file);
startActivity(intent);
}
}
});
}
private void prepareRecorder() {
recorder = new MediaRecorder();
recorder.setPreviewDisplay(holder.getSurface());
if (usecamera) {
camera.unlock();
recorder.setCamera(camera);
}
recorder.setAudioSource(MediaRecorder.AudioSource.DEFAULT);
recorder.setVideoSource(MediaRecorder.VideoSource.DEFAULT);
recorder.setProfile(camcorderProfile);
// This is all very sloppy
if (camcorderProfile.fileFormat == MediaRecorder.OutputFormat.THREE_GPP)
{
try {
File newFile = File.createTempFile("videocapture", ".3gp", Environment.getExternalStorageDirectory());
recorder.setOutputFile(newFile.getAbsolutePath());
str_record_file = newFile.getAbsolutePath();
Log.d("file_path", "=======>" + str_record_file);
} catch (IOException e) {
Log.v(LOGTAG, "Couldn't create file");
e.printStackTrace();
finish();
}
} else if (camcorderProfile.fileFormat == MediaRecorder.OutputFormat.MPEG_4) {
try {
File newFile = File.createTempFile("videocapture", ".mp4", Environment.getExternalStorageDirectory());
recorder.setOutputFile(newFile.getAbsolutePath());
str_record_file = newFile.getAbsolutePath();
Log.d("file_path", "=======>" + str_record_file);
} catch (IOException e) {
Log.v(LOGTAG, "Couldn't create file");
e.printStackTrace();
finish();
}
} else {
try {
File newFile = File.createTempFile("videocapture", ".mp4", Environment.getExternalStorageDirectory());
recorder.setOutputFile(newFile.getAbsolutePath());
str_record_file = newFile.getAbsolutePath();
Log.d("file_path", "=======>" + str_record_file);
} catch (IOException e) {
Log.v(LOGTAG, "Couldn't create file");
e.printStackTrace();
finish();
}
}
//recorder.setMaxDuration(50000); // 50 seconds
//recorder.setMaxFileSize(5000000); // Approximately 5 megabytes
try {
recorder.prepare();
} catch (IllegalStateException e) {
e.printStackTrace();
finish();
} catch (IOException e) {
e.printStackTrace();
finish();
}
}
public void onClick(View v) {
if (recording) {
recorder.stop();
if (usecamera) {
try {
camera.reconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
// recorder.release();
recording = false;
Log.v(LOGTAG, "Recording Stopped");
// Let's prepareRecorder so we can record again
prepareRecorder();
} else {
recording = true;
recorder.start();
Log.v(LOGTAG, "Recording Started");
}
}
public void surfaceCreated(SurfaceHolder holder) {
Log.v(LOGTAG, "surfaceCreated");
if (usecamera) {
camera = Camera.open();
try {
camera.setPreviewDisplay(holder);
camera.startPreview();
previewRunning = true;
} catch (IOException e) {
Log.e(LOGTAG, e.getMessage());
e.printStackTrace();
}
}
}
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
Log.v(LOGTAG, "surfaceChanged");
if (!recording && usecamera) {
if (previewRunning) {
camera.stopPreview();
}
try {
Camera.Parameters p = camera.getParameters();
p.setPreviewSize(camcorderProfile.videoFrameWidth, camcorderProfile.videoFrameHeight);
p.setPreviewFrameRate(camcorderProfile.videoFrameRate);
camera.setParameters(p);
camera.setPreviewDisplay(holder);
camera.startPreview();
previewRunning = true;
} catch (IOException e) {
Log.e(LOGTAG, e.getMessage());
e.printStackTrace();
}
prepareRecorder();
}
}
public void surfaceDestroyed(SurfaceHolder holder) {
Log.v(LOGTAG, "surfaceDestroyed");
if (recording) {
recorder.stop();
recording = false;
}
recorder.release();
if (usecamera) {
previewRunning = false;
//camera.lock();
camera.release();
}
finish();
}
}
Custom Tinder
implementation 'com.mindorks:placeholderview:0.7.1'
implementation 'com.android.support:cardview-v7:25.3.1'
implementation 'com.github.bumptech.glide:glide:3.7.0'
implementation 'com.google.code.gson:gson:2.7'
<string-array name="arry_card">
<item>Sofia</item>
<item>Roma</item>
<item>Zoya</item>
</string-array>
<color name="colorPrimary">#008577</color>
<color name="colorPrimaryDark">#00574B</color>
<color name="colorAccent">#D81B60</color>
<color name="white">#FFFFFF</color>
<color name="grey">#757171</color>
activity_main
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/grey">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="80dp"
android:layout_gravity="bottom"
android:gravity="center"
android:orientation="horizontal">
<ImageButton
android:id="#+id/rejectBtn"
android:layout_width="50dp"
android:layout_height="50dp"
android:background="#drawable/ic_cancel"/>
<ImageButton
android:id="#+id/acceptBtn"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_marginLeft="30dp"
android:background="#drawable/ic_heart"/>
</LinearLayout>
<com.mindorks.placeholderview.SwipePlaceHolderView
android:id="#+id/swipeView"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</FrameLayout>
tinder_card_view
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="350dp"
android:layout_height="425dp"
android:layout_marginBottom="50dp"
android:orientation="vertical">
<android.support.v7.widget.CardView
android:orientation="vertical"
android:background="#color/white"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="10dp"
app:cardCornerRadius="7dp"
app:cardElevation="4dp">
<ImageView
android:id="#+id/profileImageView"
android:scaleType="centerCrop"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="75dp"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="75dp"
android:orientation="vertical"
android:layout_gravity="bottom"
android:gravity="center|left"
android:paddingLeft="20dp">
<TextView
android:id="#+id/nameAgeTxt"
android:layout_width="wrap_content"
android:textColor="#color/colorPrimaryDark"
android:textSize="18dp"
android:textStyle="bold"
android:layout_height="wrap_content"/>
<TextView
android:id="#+id/locationNameTxt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#color/colorPrimaryDark"
android:textSize="14dp"
android:textStyle="normal"/>
</LinearLayout>
</android.support.v7.widget.CardView>
</FrameLayout>
tinder_swipe_in_msg_view
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="350dp"
android:layout_height="425dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="32sp"
android:textStyle="bold"
android:layout_margin="40dp"
android:textColor="#android:color/holo_green_light"
android:text="Accept"/>
</LinearLayout>
tinder_swipe_out_msg_view
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="350dp"
android:gravity="right"
android:layout_height="425dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="32sp"
android:textStyle="bold"
android:layout_margin="40dp"
android:textColor="#android:color/holo_red_light"
android:text="Reject"/>
</LinearLayout>
Profile
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Profile {
#SerializedName("name")
#Expose
private String name;
#SerializedName("url")
#Expose
private String imageUrl;
#SerializedName("age")
#Expose
private Integer age;
#SerializedName("location")
#Expose
private String location;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getImageUrl() {
return imageUrl;
}
public void setImageUrl(String imageUrl) {
this.imageUrl = imageUrl;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
TinderCard
import android.content.Context;
import android.util.Log;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.mindorks.placeholderview.SwipePlaceHolderView;
import com.mindorks.placeholderview.annotations.Layout;
import com.mindorks.placeholderview.annotations.Resolve;
import com.mindorks.placeholderview.annotations.View;
import com.mindorks.placeholderview.annotations.swipe.SwipeCancelState;
import com.mindorks.placeholderview.annotations.swipe.SwipeIn;
import com.mindorks.placeholderview.annotations.swipe.SwipeInState;
import com.mindorks.placeholderview.annotations.swipe.SwipeOut;
import com.mindorks.placeholderview.annotations.swipe.SwipeOutState;
#Layout(R.layout.tinder_card_view)
public class TinderCard {
#View(R.id.profileImageView)
private ImageView profileImageView;
#View(R.id.nameAgeTxt)
private TextView nameAgeTxt;
#View(R.id.locationNameTxt)
private TextView locationNameTxt;
private Profile mProfile;
private Context mContext;
private SwipePlaceHolderView mSwipeView;
public TinderCard(Context context, Profile profile, SwipePlaceHolderView swipeView) {
mContext = context;
mProfile = profile;
mSwipeView = swipeView;
}
#Resolve
private void onResolved(){
Glide.with(mContext).load(mProfile.getImageUrl()).into(profileImageView);
nameAgeTxt.setText(mProfile.getName() + ", " + mProfile.getAge());
locationNameTxt.setText(mProfile.getLocation());
}
#SwipeOut
private void onSwipedOut(){
Log.d("EVENT", "onSwipedOut");
mSwipeView.addView(this);
}
#SwipeCancelState
private void onSwipeCancelState(){
Log.d("EVENT", "onSwipeCancelState");
}
#SwipeIn
private void onSwipeIn(){
Log.d("EVENT", "onSwipedIn");
}
#SwipeInState
private void onSwipeInState(){
Log.d("EVENT", "onSwipeInState");
}
#SwipeOutState
private void onSwipeOutState(){
Log.d("EVENT", "onSwipeOutState");
}
}
import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import com.google.gson.Gson;
import com.mindorks.placeholderview.SwipeDecor;
import com.mindorks.placeholderview.SwipePlaceHolderView;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private SwipePlaceHolderView mSwipeView;
private Context mContext;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mSwipeView = (SwipePlaceHolderView) findViewById(R.id.swipeView);
mContext = getApplicationContext();
mSwipeView.getBuilder()
.setDisplayViewCount(3)
.setSwipeDecor(new SwipeDecor()
.setPaddingTop(20)
.setRelativeScale(0.01f)
.setSwipeInMsgLayoutId(R.layout.tinder_swipe_in_msg_view)
.setSwipeOutMsgLayoutId(R.layout.tinder_swipe_out_msg_view));
List<Profile> profileList = new ArrayList<>();
List<String> arrayList = Arrays.asList(getResources().getStringArray(R.array.arry_card));
for (int i = 0; i < arrayList.size(); i++) {
//Profile profile = Gson.fromJson(arrayList.get(i), Profile.class);
Profile profile = new Profile();
profile.setName(arrayList.get(i));
profile.setAge(2);
profile.setImageUrl("");
profile.setLocation("");
profileList.add(profile);
}
for (Profile profile : profileList) {
mSwipeView.addView(new TinderCard(mContext, profile, mSwipeView));
}
findViewById(R.id.rejectBtn).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mSwipeView.doSwipe(false);
}
});
findViewById(R.id.acceptBtn).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mSwipeView.doSwipe(true);
}
});
}
}

Categories

Resources