Hello eveyone i hope you are all doing good. I have a little problem and I couldn't find the solution. I have a translation app and after the user input his phrase by a record, the translation message doesn't appear. So I hope that someone could help me.
Here is my xml file:
<?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"
tools:context=".MainActivity">
<EditText
android:id="#+id/edittext"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:hint="Tap Mic to Speak"
android:padding="20dp"
android:textColor="#000000"
android:textSize="20sp" />
<Button
android:id="#+id/idBtnTranslateLanguage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/TransledText"
android:layout_centerInParent="true"
android:text="Translate language" />
<ImageButton
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/edittext"
android:layout_centerHorizontal="true"
android:layout_marginTop="128dp"
android:background="#color/white"
android:padding="40dp"
android:src="#drawable/ic_baseline_mic_24" />
<TextView
android:id="#+id/TransledText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/edittext"
android:layout_centerHorizontal="true"
android:layout_margin="20dp"
android:gravity="center_horizontal"
android:text="Translated language"
android:textAlignment="center"
android:textSize="20sp"
tools:ignore="UnknownId" />
</RelativeLayout>
And my main code:
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Locale;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.ml.common.modeldownload.FirebaseModelDownloadConditions;
import com.google.firebase.ml.naturallanguage.FirebaseNaturalLanguage;
import com.google.firebase.ml.naturallanguage.translate.FirebaseTranslateLanguage;
import com.google.firebase.ml.naturallanguage.translate.FirebaseTranslator;
import com.google.firebase.ml.naturallanguage.translate.FirebaseTranslatorOptions;
public class MainActivity extends AppCompatActivity {
private static final int CodeSpeechInput =100;
private TextView EditText;
private ImageButton SpeakButton;
private TextView TransledText;
FirebaseTranslator englishFrenshTranslator;
private Button translateLanguageBtn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FirebaseTranslatorOptions options =
new FirebaseTranslatorOptions.Builder()
.setSourceLanguage(FirebaseTranslateLanguage.EN)
.setTargetLanguage(FirebaseTranslateLanguage.FR)
.build();
englishFrenshTranslator = FirebaseNaturalLanguage.getInstance().getTranslator(options);
EditText = (TextView) findViewById(R.id.edittext);
SpeakButton = (ImageButton) findViewById(R.id.button);
TransledText = (TextView) findViewById(R.id.TransledText);
translateLanguageBtn = findViewById(R.id.idBtnTranslateLanguage);
translateLanguageBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String string = EditText.getText().toString();
downloadModal(string);
}
private void downloadModal(String input) {
FirebaseModelDownloadConditions conditions = new FirebaseModelDownloadConditions.Builder().requireWifi().build();
englishFrenshTranslator.downloadModelIfNeeded(conditions).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
// this method is called when modal is downloaded successfully.
Toast.makeText(MainActivity.this, "Please wait language modal is being downloaded.", Toast.LENGTH_SHORT).show();
// calling method to translate our entered text.
translateLanguage(input);
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(MainActivity.this, "Fail to download modal", Toast.LENGTH_SHORT).show();
}
});
}
private void translateLanguage(String input) {
englishFrenshTranslator.translate(input).addOnSuccessListener(new OnSuccessListener<String>() {
#Override
public void onSuccess(String result) {
TransledText.setText(input);
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(MainActivity.this, "Fail to translate", Toast.LENGTH_SHORT).show();
}
});
}
});
SpeakButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startVoiceInput();
}
private void startVoiceInput() {
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault());
try {
startActivityForResult(intent, CodeSpeechInput);
} catch (ActivityNotFoundException a) {
}
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case CodeSpeechInput : {
if (resultCode == RESULT_OK && null != data) {
ArrayList<String> result = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
EditText.setText(result.get(0));
}
break;
}
}
}
}
I also use firebase if that could help you.
Related
To save this PDF I have added a while loop where the last letter has added a specific number from 0 to n in parentheses. When I save the first PDF it is saved as myPDFfile.pdf then the second pdf will be saved as myPDFFile(1).pdf but when I save the third pdf it will be saved as myPDFFile(1)(1).pdf
but I want this pdf to save as myPDFfile(2).pdf.
import static android.Manifest.permission.CAMERA;
import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.graphics.Paint;
import android.graphics.pdf.PdfDocument;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.speech.tts.TextToSpeech;
import android.util.SparseArray;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import com.google.android.gms.vision.CameraSource;
import com.google.android.gms.vision.Detector;
import com.google.android.gms.vision.text.TextBlock;
import com.google.android.gms.vision.text.TextRecognizer;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Locale;
public class MainActivity extends AppCompatActivity {
private TextView textView;
private SurfaceView surfaceView;
private CameraSource cameraSource;
private TextRecognizer textRecognizer;
Button button;
private TextToSpeech textToSpeech;
private String stringResult = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = findViewById(R.id.btn);
button = findViewById(R.id.btn1);
ActivityCompat.requestPermissions(this, new String[]{CAMERA}, PackageManager.PERMISSION_GRANTED);
textToSpeech = new TextToSpeech(this, new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
textToSpeech.setLanguage(Locale.US);
}
});
}
#Override
protected void onDestroy() {
super.onDestroy();
cameraSource.release();
}
private void textRecognizer() {
textRecognizer = new TextRecognizer.Builder(getApplicationContext()).build();
cameraSource = new CameraSource.Builder(getApplicationContext(), textRecognizer)
.setRequestedPreviewSize(1280, 1024)
.setAutoFocusEnabled(true)
.build();
surfaceView = findViewById(R.id.surfaceView);
Context context = this;
surfaceView.getHolder().addCallback(new SurfaceHolder.Callback() {
#Override
public void surfaceCreated(SurfaceHolder holder) {
try {
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
cameraSource.start(surfaceView.getHolder());
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
cameraSource.stop();
}
});
}
private void capture() {
textRecognizer.setProcessor(new Detector.Processor<TextBlock>() {
#Override
public void release() {
}
#Override
public void receiveDetections(Detector.Detections<TextBlock> detections) {
SparseArray<TextBlock> sparseArray = detections.getDetectedItems();
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < sparseArray.size(); ++i) {
TextBlock textBlock = sparseArray.valueAt(i);
if (textBlock != null && textBlock.getValue() != null) {
stringBuilder.append(textBlock.getValue() + " ");
}
}
final String stringText = stringBuilder.toString();
Handler handler = new Handler(Looper.getMainLooper());
handler.post(new Runnable() {
#Override
public void run() {
stringResult = stringText;
resultObtained();
}
});
}
});
}
private void resultObtained() {
setContentView(R.layout.activity_main);
textView = findViewById(R.id.textView);
textView.setText(stringResult);
textToSpeech.speak(stringResult, TextToSpeech.QUEUE_FLUSH, null, null);
}
public void buttonStart(View view) {
setContentView(R.layout.surface);
Button capture = findViewById(R.id.capture);
capture.setOnClickListener(v -> capture());
textRecognizer();
}
public void createMyPDF(View view) {
PdfDocument myPdfDocument = new PdfDocument();
PdfDocument.PageInfo myPageInfo = new PdfDocument.PageInfo.Builder(300, 600, 1).create();
PdfDocument.Page myPage = myPdfDocument.startPage(myPageInfo);
Paint myPaint = new Paint();
String myString = textView.getText().toString();
int x = 10, y = 25;
for (String line : myString.split("\n")) {
myPage.getCanvas().drawText(line, x, y, myPaint);
y += myPaint.descent() - myPaint.ascent();
}
myPdfDocument.finishPage(myPage);
String myFilePath = Environment.getExternalStorageDirectory().getPath() + "/myPDFFile.pdf";
File myFile = new File(myFilePath);
while (myFile.exists()) {
int i = 0;
i++;
myFile = new File(myFile.toString().replace("myPDFFile", "myPDFFile (" + i + ")"));
}
try {
myPdfDocument.writeTo(new FileOutputStream(myFile));
} catch (Exception e) {
e.printStackTrace();
textView.setText("ERROR");
}
myPdfDocument.close();
}
public void onPause() {
if (textToSpeech != null) {
textToSpeech.stop();
}
super.onPause();
}
}
XML Code:-
<?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"
tools:context=".MainActivity"
android:layout_height="match_parent">
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginStart="-2dp"
android:layout_marginTop="-4dp">
<TextView
android:id="#+id/textView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentTop="true"
android:layout_marginStart="-4dp"
android:layout_marginTop="-2dp"
android:background="#color/black"
android:gravity="center"
android:text="OCR READER FOR VISUALLY IMPARED PEOPLES"
android:textColor="#color/white"
android:textIsSelectable="true"
android:textSize="20dp"
android:textStyle="bold"
tools:layout_editor_absoluteX="8dp" />
</ScrollView>
<Button
android:id="#+id/btn"
android:layout_width="407dp"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginStart="0dp"
android:layout_marginBottom="24dp"
android:onClick="buttonStart"
android:text="Click here"
android:textSize="20dp" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/btn1"
android:layout_alignBottom="#+id/btn"
android:layout_alignParentStart="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="45dp"
android:onClick="createMyPDF"
android:text="Create PDF"
android:textSize="20dp" />
</RelativeLayout>
surface.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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"
xmlns:app="http://schemas.android.com/apk/res-auto">
<SurfaceView
android:id="#+id/surfaceView"
android:layout_width="378dp"
android:layout_height="628dp"
android:layout_marginStart="16dp"
android:layout_marginTop="4dp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
android:id="#+id/capture"
android:layout_marginHorizontal="32dp"
android:layout_marginBottom="32dp"
android:text="Capture"
app:layout_constraintEnd_toEndOf="parent"/>
</androidx.constraintlayout.widget.ConstraintLayout>
Problem
I am creating music player using android studio.
Everything was fine until I added search filter to search songs.
Search filter returns the song right but when I click on searched result wrong music file is opened however the music name shown on player activity is right but the song played is first song of list every time .
Example
There are 4 song items named: A,B,C,D
When searched C ,filtered result C is shown. But when Clicked on it Song name C is shown but Song A is played.
This is really frustrating.
Main Activity.java
package com.example.musicplayer2;
import android.Manifest;
import android.content.Intent;
import android.icu.text.Transliterator;
import android.os.Bundle;
import android.os.Environment;
import android.view.Menu;
import android.view.MenuItem;
import android.view.SearchEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import com.karumi.dexter.Dexter;
import com.karumi.dexter.PermissionToken;
import com.karumi.dexter.listener.PermissionDeniedResponse;
import com.karumi.dexter.listener.PermissionGrantedResponse;
import com.karumi.dexter.listener.PermissionRequest;
import com.karumi.dexter.listener.single.PermissionListener;
import java.io.File;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
static boolean shuffleBol = false;
static boolean loopBol = false;
ListView listView;
String[] items;
ArrayAdapter<String> myAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = findViewById(R.id.listViewSong);
runtimePermission();
}
public void runtimePermission()
{
Dexter.withContext(this).withPermission(Manifest.permission.READ_EXTERNAL_STORAGE)
.withListener(new PermissionListener() {
#Override
public void onPermissionGranted(PermissionGrantedResponse permissionGrantedResponse) {
displaySongs();
}
#Override
public void onPermissionDenied(PermissionDeniedResponse permissionDeniedResponse) {
}
#Override
public void onPermissionRationaleShouldBeShown(PermissionRequest permissionRequest, PermissionToken permissionToken) {
permissionToken.continuePermissionRequest();
}
}).check();
}
public ArrayList<File> findSong(File file)
{
ArrayList<File> arrayList = new ArrayList<>();
File[] files = file.listFiles();
if (files != null){
for (File singlefile : files)
{
if (singlefile.isDirectory() && !singlefile.isHidden())
{
arrayList.addAll(findSong(singlefile));
}
else
{
if (singlefile.getName().endsWith(".mp3") && !singlefile.getName().startsWith("."))
{
arrayList.add(singlefile);
}
}
}
}
return arrayList;
}
void displaySongs()
{
ArrayList<File> mysongs;
mysongs = findSong(Environment.getExternalStorageDirectory());
items = new String[mysongs.size()];
for (int i=0; i < mysongs.size(); i++)
{
items[i] = mysongs.get(i).getName().replace(".mp3","");
}
// ArrayAdapter<String> myAdapter;
myAdapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1, items);
listView.setAdapter(myAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String songName = (String) listView.getItemAtPosition(position);
startActivity(new Intent(getApplicationContext(),PlayerActivity.class)
.putExtra("songs",mysongs)
.putExtra("songname",songName)
.putExtra("position",position));
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu,menu);
MenuItem menuItem = menu.findItem(R.id.search_view);
SearchView searchView = (SearchView) menuItem.getActionView();
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
myAdapter.getFilter().filter(newText);
return false;
}
});
return super.onCreateOptionsMenu(menu);
}
}
main activity.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"
tools:context=".MainActivity">
<ListView
android:id="#+id/listViewSong"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:divider="#android:color/transparent"
android:dividerHeight="10.0sp"
android:padding="8dp"
>
</ListView>
</RelativeLayout>
PlayerActivity.java
package com.example.musicplayer2;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import org.w3c.dom.Text;
import java.io.File;
import java.util.ArrayList;
import java.util.Random;
import static com.example.musicplayer2.MainActivity.loopBol;
import static com.example.musicplayer2.MainActivity.shuffleBol;
public class PlayerActivity extends AppCompatActivity {
ImageView btnplay,btnnext,btnprev,btnshuffle,btnloop;
TextView txtsname,txtstart,txtstop;
SeekBar seekmusic;
String sname;
public static final String EXTRA_NAME = "song_name";
static MediaPlayer mediaPlayer;
int position;
ArrayList<File> mySongs;
Thread updateseekbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_player);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle("Player");
btnprev = findViewById(R.id.btnprev);
btnnext = findViewById(R.id.btnnext);
btnplay = findViewById(R.id.playbtn);
btnshuffle = findViewById(R.id.btnshuffle);
btnloop = findViewById(R.id.btnloop);
txtsname = findViewById(R.id.txtsn);
txtstart = findViewById(R.id.txtstart);
txtstop = findViewById(R.id.txtstop);
seekmusic = findViewById(R.id.seekbar);
// if a media player is already running then.
if (mediaPlayer != null)
{
mediaPlayer.stop();
mediaPlayer.release();
}
Intent i = getIntent();
Bundle bundle = i.getExtras();
mySongs = (ArrayList)bundle.getParcelableArrayList("songs");
String songName = i.getStringExtra("songname");
position = bundle.getInt("position",0);
txtsname.setSelected(true);
Uri uri = Uri.parse(mySongs.get(position).toString());
sname = mySongs.get(position).getName();
txtsname.setText(sname);
mediaPlayer = MediaPlayer.create(getApplicationContext(),uri);
mediaPlayer.start();
updateseekbar = new Thread()
{
#Override
public void run() {
int totalDuration = mediaPlayer.getDuration();
int currentPosition = 0;
while (currentPosition<totalDuration)
{
try {
sleep(500);
currentPosition = mediaPlayer.getCurrentPosition();
seekmusic.setProgress(currentPosition);
}
catch (InterruptedException | IllegalStateException e)
{
e.printStackTrace();
}
}
}
};
seekmusic.setMax(mediaPlayer.getDuration());
updateseekbar.start();
seekmusic.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
mediaPlayer.seekTo(seekBar.getProgress());
}
});
String endTime = createTime(mediaPlayer.getDuration());
txtstop.setText(endTime);
final Handler handler = new Handler();
final int delay = 1000;
handler.postDelayed(new Runnable() {
#Override
public void run() {
String currentTime = createTime(mediaPlayer.getCurrentPosition());
txtstart.setText(currentTime);
handler.postDelayed(this,delay);
}
},delay);
// click Listener ON PLAY button
btnplay.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mediaPlayer.isPlaying())
{
btnplay.setBackgroundResource(R.drawable.play);
mediaPlayer.pause();
}
else
{
btnplay.setBackgroundResource(R.drawable.pause);
mediaPlayer.start();
}
}
});
// click Listener ON next button
btnnext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mediaPlayer.stop();
mediaPlayer.release();
if (shuffleBol && !loopBol){
position=getRandom((mySongs.size()));
}
else if(!shuffleBol && !loopBol)
{
position=((position+1)%mySongs.size());
}
Uri u = Uri.parse(mySongs.get(position).toString());
mediaPlayer = MediaPlayer.create(getApplicationContext(),u);
sname=mySongs.get(position).getName();
txtsname.setText(sname);
mediaPlayer.start();
btnplay.setBackgroundResource(R.drawable.pause);
String endTime = createTime(mediaPlayer.getDuration());
txtstop.setText(endTime);
}
});
// click Listener ON previous button
btnprev.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mediaPlayer.stop();
mediaPlayer.release();
if (shuffleBol && !loopBol){
position=getRandom((mySongs.size()));
}
else if(!shuffleBol && !loopBol){
position=((position-1)<0)?(mySongs.size()-1):(position-1);
}
Uri u = Uri.parse(mySongs.get(position).toString());
mediaPlayer = MediaPlayer.create(getApplicationContext(),u);
sname=mySongs.get(position).getName();
txtsname.setText(sname);
mediaPlayer.start();
btnplay.setBackgroundResource(R.drawable.pause);
String endTime = createTime(mediaPlayer.getDuration());
txtstop.setText(endTime);
}
});
// click listener for shuffle btn
btnshuffle.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (shuffleBol){
shuffleBol=false;
btnshuffle.setImageResource(R.drawable.shuffle_off);
}
else {
shuffleBol=true;
btnshuffle.setImageResource(R.drawable.shuffle_on);
}
}
});
// click listener for loop btn
btnloop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (loopBol){
loopBol=false;
btnloop.setImageResource(R.drawable.loop_off);
}
else {
loopBol=true;
btnloop.setImageResource(R.drawable.loop_on);
}
}
});
// next Listener ON song completion
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
btnnext.performClick();
}
});
}
public String createTime(int duration)
{
String time = "";
int min = duration/1000/60;
int sec = duration/1000%60;
time+=min+":";
if (sec<10)
{
time+="0";
}
time+=sec;
return time;
}
private int getRandom(int i) {
Random random= new Random();
return random.nextInt(i+1);
}
}
PlayerActivity.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#drawable/bg"
android:orientation="vertical"
android:weightSum="10"
tools:context=".PlayerActivity"
android:baselineAligned="false">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="7"
android:gravity="center"
android:orientation="vertical"
tools:ignore="Suspicious0dp,UselessParent">
<TextView
android:id="#+id/txtsn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="0dp"
android:ellipsize="marquee"
android:marqueeRepeatLimit="marquee_forever"
android:singleLine="true"
android:text="#string/song_name"
android:textAlignment="center"
android:textColor="#color/black"
android:textSize="18sp"
android:textStyle="italic">
</TextView>
<ImageView
android:id="#+id/imageview"
android:layout_width="250dp"
android:layout_height="250dp"
android:layout_marginBottom="8dp"
android:src="#drawable/logo">
</ImageView>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="60dp">
<SeekBar
android:id="#+id/seekbar"
android:layout_width="250dp"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerInParent="true"
android:layout_margin="20dp"
android:layout_marginBottom="40dp">
</SeekBar>
<TextView
android:id="#+id/txtstart"
android:layout_width="78dp"
android:layout_height="wrap_content"
android:layout_alignParentLeft="false"
android:layout_centerInParent="true"
android:layout_centerVertical="true"
android:layout_marginLeft="20dp"
android:layout_marginRight="-17dp"
android:layout_toLeftOf="#+id/seekbar"
android:text="0:00"
android:textAlignment="center"
android:textColor="#color/black"
android:textSize="15sp">
</TextView>
<TextView
android:id="#+id/txtstop"
android:layout_width="78dp"
android:layout_height="wrap_content"
android:layout_alignParentRight="false"
android:layout_centerInParent="true"
android:layout_marginLeft="-14dp"
android:layout_marginRight="20dp"
android:layout_toRightOf="#+id/seekbar"
android:text="#string/_4_10"
android:textAlignment="center"
android:textColor="#color/black"
android:textSize="15sp">
</TextView>
</RelativeLayout>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="98dp"
android:layout_weight="3">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="#+id/playbtn"
android:layout_width="70dp"
android:layout_height="70dp"
android:layout_centerHorizontal="true"
android:background="#drawable/pause" />
<ImageView
android:id="#+id/btnnext"
android:layout_width="55dp"
android:layout_height="55dp"
android:layout_marginLeft="20dp"
android:layout_marginTop="10dp"
android:layout_toRightOf="#+id/playbtn"
android:background="#drawable/next" />
<ImageView
android:id="#+id/btnprev"
android:layout_width="55dp"
android:layout_height="55dp"
android:layout_marginTop="10dp"
android:layout_marginRight="20dp"
android:layout_toLeftOf="#+id/playbtn"
android:background="#drawable/previous" />
<ImageView
android:id="#+id/btnshuffle"
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_toLeftOf="#+id/btnprev"
android:layout_marginTop="85dp"
android:layout_marginRight="35dp"
android:background="#drawable/shuffle_off"/>
<ImageView
android:id="#+id/btnloop"
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_toRightOf="#+id/btnnext"
android:layout_marginTop="85dp"
android:layout_marginLeft="35dp"
android:background="#drawable/loop_off"/>
</RelativeLayout>
</LinearLayout>
</LinearLayout>
In above image, you see that you are sending the position of filtered array and sending the songs list (mysongs) which is not filtered. That's why it's happening.
So you need to do is that either send the filtered array. Or add some logic to get the correct position from songs list. that's it.
if you can not figure out then let me know I will update appropriate logic.
I'm trying to select images from the gallery and upload them to firebase storage but after selecting the image it doesn't show in the image view and the app get crash
Note I'm using a fragment and not an activity
Here is the Error Message
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageView.setImageURI(android.net.Uri)' on a null object reference
Here is my MainActivity.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"
tools:context=".MainActivity"
android:background="#color/black">
<include
android:id="#+id/tool_bar"
layout="#layout/tool_bar" />
<include
android:id="#+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
layout="#layout/fragment_container"
android:layout_below="#+id/tool_bar"
android:layout_above="#id/bottom_navigation_view" />
<include
android:id="#+id/bottom_navigation_view"
layout="#layout/bottom_navigation_view" />
</RelativeLayout>
Here is my fragment_upload.XML file
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/black">
<ImageView
android:id="#+id/upload_image_view"
android:layout_width="match_parent"
android:layout_height="600dp"
app:layout_constraintBottom_toTopOf="#+id/done_button"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="#+id/done_button"
android:layout_width="match_parent"
android:layout_height="60dp"
android:backgroundTint="#color/grey"
android:text="#string/done"
android:textColor="#color/white"
app:layout_constraintBottom_toTopOf="#+id/upload_image_button"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent" />
<Button
android:id="#+id/upload_image_button"
android:layout_width="match_parent"
android:layout_height="60dp"
android:backgroundTint="#color/grey"
android:text="#string/upload"
android:textColor="#color/white"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
Here is MainActivity.java
public class MainActivity extends AppCompatActivity {
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BottomNavigationView bottomNavigationView = findViewById(R.id.bottom_navigation_view);
bottomNavigationView.setOnNavigationItemSelectedListener(navigationItemSelectedListener);
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new Home_Fragment()).commit();
Window window = this.getWindow();
window.setStatusBarColor(this.getResources().getColor(R.color.black));
}
private final BottomNavigationView.OnNavigationItemSelectedListener navigationItemSelectedListener =
item -> {
Fragment selectedFragment = null;
switch (item.getItemId()) {
case R.id.nav_home:
selectedFragment = new Home_Fragment();
break;
case R.id.nav_following:
selectedFragment = new Following_Fragment();
break;
case R.id.nav_upload:
selectedFragment = new Upload_Fragment();
break;
case R.id.nav_notification:
selectedFragment = new Notification_Fragment();
break;
case R.id.nav_profile:
selectedFragment = new Profile_Fragment();
break;
}
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
selectedFragment).commit();
return true;
};
}
Here is Upload_Fragment.java
import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import com.example.myappnotfinal.R;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.OnProgressListener;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import java.util.UUID;
import static android.app.Activity.RESULT_OK;
public class Upload_Fragment extends Fragment {
private static final int PICK_IMAGE_REQUEST = 1;
private Button choseImageButton;
private Button uploadImageButton;
private ImageView uploadImageView;
private Uri imageUri;
private FirebaseStorage storage;
private StorageReference storageReference;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_upload, container, false);
Button chooseImageButton = view.findViewById(R.id.upload_image_button);
Button uploadImageButton = view.findViewById(R.id.done_button);
uploadeImageView = view.findViewById(R.id.upload_image_view);
storage = FirebaseStorage.getInstance();
storageReference = storage.getReference();
chooseImageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openFileChooser();
}
});
uploadImageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
uploadToFirebase();
}
});
return view;
}
private void openFileChooser() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent, PICK_IMAGE_REQUEST);
}
#Override
public void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK
&& data != null && data.getData() != null) {
imageUri = data.getData();
uploadImageView.setImageURI(imageUri);
}
}
private void uploadToFirebase() {
if (imageUri != null) {
final ProgressDialog progressDialog = new ProgressDialog(getActivity());
progressDialog.setTitle("Uploading...");
progressDialog.show();
StorageReference ref = storageReference.child("images/" + UUID.randomUUID().toString());
ref.putFile(imageUri)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
progressDialog.dismiss();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
progressDialog.dismiss();
}
})
.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
double progress = (100.0 * taskSnapshot.getBytesTransferred() / taskSnapshot
.getTotalByteCount());
progressDialog.setMessage("Uploaded " + (int) progress + "%");
}
});
}
}
}
From what I can understand is that your image_view is null rather than your URI since you have already put a check for that, and after reading your code inside the onCreateView() method, there is this line
uploadeImageView = view.findViewById(R.id.upload_image_view);
This might just be a typo, there is an extra 'e' at the end while your top variable is
private ImageView uploadImageView;
and even later when you are setting it you are using following
uploadImageView.setImageURI(imageUri);
I making an app which you can use to start other apps like Netflix on. I have four imagebuttons on the first XML file which is going to be the "Favorites". When you click on any of these imagebuttons you start the intent for the app you wanted to start. Then the app gets opened. How can I make it so that the Favorites changes automatically after what the user uses.
Here is my Java Code:
package com.carlo_projekt.tvprograms;
import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.speech.RecognizerIntent;
import android.speech.tts.TextToSpeech;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Locale;
' public class MainActivity extends AppCompatActivity {
ImageButton speakBtn;
Button CategoriesBtn;
TextView text;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
speakBtn = (ImageButton) findViewById(R.id.SpeakImageBtn);
CategoriesBtn = (Button) findViewById(R.id.CategoriesBtn);
text = (TextView) findViewById(R.id.textView);
}
public void OpenGame(View view) {
Intent intent = new Intent(this, MoreActivity.class);
startActivity(intent);
}
public void Speak(View view)
{
Intent recognizeIntent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
recognizeIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
recognizeIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, "en-US");
recognizeIntent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Hi! Which app do you want to start?");
try {
startActivityForResult(recognizeIntent, 1);
}
catch (ActivityNotFoundException a)
{
Toast.makeText(MainActivity.this, "Sorry! Your device doesn't support this function!", Toast.LENGTH_LONG).show();
}
}
public void onActivityResult(int request_Code, int result_Code, Intent recognizeIntent)
{
super.onActivityResult(request_Code, result_Code, recognizeIntent);
switch (request_Code)
{
case 1: if(result_Code == RESULT_OK && recognizeIntent != null)
{
ArrayList<String> result = recognizeIntent.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
for(int i = 0; i<result.size(); i++)
{
result.set(i, result.get(i).toLowerCase());
if(result.get(i).compareTo("start netflix") == 0)
{
Intent NetflixIntent = getPackageManager().getLaunchIntentForPackage("com.netflix.mediaclient");
startActivity(NetflixIntent);
}
else if(result.get(i).compareTo("start youtube") == 0)
{
Intent NetflixIntent = getPackageManager().getLaunchIntentForPackage("com.google.android.youtube");
startActivity(NetflixIntent);
}
else if(result.get(i).compareTo("start viafree") == 0)
{
Intent NetflixIntent = getPackageManager().getLaunchIntentForPackage("se.viafree.android");
startActivity(NetflixIntent);
}
else if(result.get(i).compareTo("start tvfour") == 0)
{
Intent NetflixIntent = getPackageManager().getLaunchIntentForPackage("se.tv4.tv4playtab");
startActivity(NetflixIntent);
}
else if(result.get(i).compareTo("start dplay") == 0)
{
Intent NetflixIntent = getPackageManager().getLaunchIntentForPackage("se.kanal5play");
startActivity(NetflixIntent);
}
else if(result.get(i).compareTo("start viaplay") == 0)
{
Intent NetflixIntent = getPackageManager().getLaunchIntentForPackage("com.viaplay.android");
startActivity(NetflixIntent);
}
else if(result.get(i).compareTo("start svtplay") == 0)
{
Intent NetflixIntent = getPackageManager().getLaunchIntentForPackage("se.svt.android.svtplay");
startActivity(NetflixIntent);
}
/**text.setText(result.get(i));*/
}
}
}
}
public void OpenApps(String packageName)
{
if(getPackageManager().getLaunchIntentForPackage(packageName) != null)
{
Intent tv4PlayIntent = getPackageManager().getLaunchIntentForPackage(packageName);
startActivity(tv4PlayIntent);
}
else
{
String marketAppPackageName = "market://details?id="+ packageName;
MessageBox(marketAppPackageName);
}
}
public void NetflixFunction(View view)
{
String netflixPackageName = new String("com.netflix.mediaclient");
OpenApps(netflixPackageName);
}
public void ViafreeFunction(View view)
{
String viafreePackageName = new String("se.viafree.android");
OpenApps(viafreePackageName);
}
public void YoutubeFunction(View view)
{
String youtubePackageName = new String("com.google.android.youtube");
OpenApps(youtubePackageName);
}
public void Tv4PlayFunction(View view)
{
String tv4playPackageName = new String("se.tv4.tv4playtab");
OpenApps(tv4playPackageName);
}
public void LayoutsShow(View view)
{
RelativeLayout layoutShow = findViewById(R.id.LayoutShow);
if (layoutShow.getVisibility() == View.GONE) {
layoutShow.setVisibility(View.VISIBLE);
}
else if (layoutShow.getVisibility() == View.VISIBLE) {
layoutShow.setVisibility(View.GONE);
}
}
public void MessageBox(final String uriIntent)
{
AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this).create();
alertDialog.setTitle("Couldn't find this app");
String messageText = "We cant find this app, do you want to download it?";
alertDialog.setMessage(messageText);
alertDialog.setButton(AlertDialog.BUTTON_NEGATIVE, "Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent MarketIntent = new Intent(Intent.ACTION_VIEW);
MarketIntent.setData(Uri.parse(uriIntent));
startActivity(MarketIntent);
dialog.dismiss();
}
});
alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "No",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.show();
}}
This is my XML Code:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/backgroundColor"
tools:context="com.carlo_projekt.tvprograms.MainActivity">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:ignore="MissingConstraints"
tools:layout_editor_absoluteX="0dp"
tools:layout_editor_absoluteY="0dp">
<Button
android:id="#+id/CategoriesBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="56dp"
android:background="#drawable/round_corners"
android:onClick="OpenGame"
android:text="Categories"
android:textAllCaps="false" />
<ImageButton
android:id="#+id/NetflixImageBtn"
android:layout_width="90dp"
android:layout_height="90dp"
android:layout_centerVertical="true"
android:layout_toStartOf="#+id/CategoriesBtn"
android:onClick="NetflixFunction"
app:srcCompat="#drawable/netflix" />
<ImageButton
android:id="#+id/YoutubeImageBtn"
android:layout_width="90dp"
android:layout_height="90dp"
android:layout_alignTop="#+id/NetflixImageBtn"
android:layout_toEndOf="#+id/CategoriesBtn"
android:onClick="YoutubeFunction"
app:srcCompat="#drawable/youtube" />
<ImageButton
android:id="#+id/ViafreeImageBtn"
android:layout_width="90dp"
android:layout_height="90dp"
android:layout_alignStart="#+id/NetflixImageBtn"
android:layout_below="#+id/NetflixImageBtn"
android:layout_marginTop="52dp"
android:onClick="ViafreeFunction"
app:srcCompat="#drawable/viafree" />
<ImageButton
android:id="#+id/Tv4PlayImageBtn"
android:layout_width="90dp"
android:layout_height="90dp"
android:layout_alignEnd="#+id/YoutubeImageBtn"
android:layout_alignTop="#+id/ViafreeImageBtn"
android:onClick="Tv4PlayFunction"
app:srcCompat="#drawable/tv4" />
<ImageButton
android:id="#+id/SpeakImageBtn"
android:layout_width="40dp"
android:layout_height="60dp"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:onClick="Speak"
app:srcCompat="#drawable/microphone" />
<ImageButton
android:id="#+id/imageButton19"
android:layout_width="40dp"
android:layout_height="20dp"
android:layout_alignParentEnd="true"
app:srcCompat="#drawable/sweden" />
<ImageButton
android:id="#+id/imageButton24"
android:layout_width="40dp"
android:layout_height="20dp"
android:layout_alignParentEnd="true"
android:layout_below="#+id/imageButton19"
app:srcCompat="#drawable/great_britain" />
<ImageButton
android:id="#+id/imageButton22"
android:layout_width="40dp"
android:layout_height="20dp"
android:layout_alignParentEnd="true"
android:layout_below="#+id/imageButton24"
app:srcCompat="#drawable/germany" />
<ImageButton
android:id="#+id/imageButton23"
android:layout_width="40dp"
android:layout_height="20dp"
android:layout_alignParentEnd="true"
android:layout_below="#+id/imageButton22"
app:srcCompat="#drawable/france" />
<ImageButton
android:id="#+id/imageButton25"
android:layout_width="40dp"
android:layout_height="20dp"
android:layout_alignParentEnd="true"
android:layout_below="#+id/imageButton23"
app:srcCompat="#drawable/spanish" />
<TextView
android:id="#+id/textView"
android:layout_width="193dp"
android:layout_height="33dp"
android:layout_alignParentBottom="true"
android:layout_alignParentEnd="true"
android:layout_marginBottom="217dp"
android:layout_marginEnd="90dp"
android:text="TextView"
android:textColor="#ff00" />
</RelativeLayout>
</android.support.constraint.ConstraintLayout>
`
I'm pretty new with stack overflow so I hope you understand what I'm trying to do.
Get SharedPreferences object:
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
Create a click listener that will update the click count for the appropriate button:
View.OnClickListener myClickListener= new View.OnClickListener() {
public void onClick(View v) {
String tag = (String) v.getTag();
sharedPref
.edit()
.putInt(tag, shardPref.getInteger(tag) + 1)
.apply();
}
};
Now for each of your buttons, you will want to set both the click listener and a tag for naming purposes:
Button btn = findViewById(R.id.NetflixImageBtn);
btn.setTag("netflix");
btn.setOnClickListener(myClickListener);
Now when you click a button, it will increment the count associated with the tag. You can use that information however you wish.
With this code i want to create custom TextToSpeech files with the text written in the Textedit.
The User can write something in the TextEdit and the TextToSpeech converts this into speech and then I want to create this speech as a audiofile, which I can share.
But now I dont know where my error is and I don't know further.
Could you please help me :)
import android.os.Build;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import java.io.File;
import java.util.HashMap;
import java.util.Locale;
import static de.fresenborg.aufeinwort4.R.id.editText;
public class MainActivity extends AppCompatActivity implements TextToSpeech.OnInitListener, View.OnClickListener {
private TextToSpeech tts;
private static String fileLocation;
private static String text;
public TextToSpeechFile(String fLocation, String txt) {
fileLocation = fLocation;
text = txt;
}
#Override
public void onClick(View view) {
final EditText wassoll = (EditText) findViewById(editText);
tts.speak(wassoll.getText().toString(), TextToSpeech.QUEUE_FLUSH, null);
ImageButton Sharebutton = (ImageButton) findViewById(R.id.Sharebutton);
Sharebutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
public static void createFile(){
TextToSpeech tts;
HashMap<String, String> myHashRender = new HashMap();
myHashRender.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, text);
tts.synthesizeToFile(text, myHashRender, fileLocation);
final int utteranceId = 1;
File destinationFile = new File(getCacheDir(), utteranceId + ".wav");
int utteranceId++;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
tts.synthesizeToFile(TextToSpeech.ACTION_TTS_QUEUE_PROCESSING_COMPLETED, null, destinationFile, utteranceId);
} else {
Bundle params = new Bundle();
params.putString(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, utteranceId);
tts.synthesizeToFile(TextToSpeech.ACTION_TTS_QUEUE_PROCESSING_COMPLETED, params, destinationFile.getPath());)
tts.setOnUtteranceCompletedListener(new TextToSpeech.OnUtteranceCompletedListener() {
#Override
public void onUtteranceCompleted(String s) {
if (s.equals(utteranceId)) {
}
}
});
}
}
}
});
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tts = new TextToSpeech(this, this);
}
#Override
public void onInit(int arg0) {
tts.setLanguage(Locale.GERMAN);
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(this);
}
}
This is my XML:
<EditText
android:id="#+id/editText"
android:layout_width="wrap_content"
android:layout_height="100dp"
android:layout_alignParentEnd="true"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentStart="true"
android:layout_below="#+id/my_toolbar"
android:ems="10"
android:hint="Was soll ich sagen?"
android:inputType="textMultiLine"
android:lines="8"
android:minLines="1"
android:text="#string/wassoll" />
<ImageButton
android:id="#+id/Sharebutton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/button"
android:layout_toEndOf="#+id/button"
android:layout_toRightOf="#+id/button"
android:background="#null"
app:srcCompat="#drawable/share" />
<Button
android:id="#+id/button"
android:layout_width="130dp"
android:layout_height="50dp"
android:layout_below="#+id/editText"
android:layout_centerHorizontal="true"
android:layout_marginTop="14dp"
android:text="#string/button_sag_es" />