How can I add Continues Speech Recognition in my Android Application? - java

I want to create application which will write text while listening. I have tried this code but this is not working. and i have followed this link. but it couldn't work for me.
If i speak, it is not displaying spoken words and speech recognition is also not working. if you know the solution Please guide me to solve this problem. Thank you...
package com.kp.notesapp;
import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
import android.Manifest;
import android.annotation.SuppressLint;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.graphics.fonts.Font;
import android.graphics.pdf.PdfDocument;
import android.graphics.pdf.PdfRenderer;
import android.os.Bundle;
import android.os.Environment;
import android.print.PageRange;
import android.provider.DocumentsContract;
import android.speech.RecognitionListener;
import android.speech.RecognizerIntent;
import android.speech.SpeechRecognizer;
import android.text.Html;
import android.text.style.ParagraphStyle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.compose.ui.text.Paragraph;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import com.google.android.material.internal.ViewUtils;
import com.kp.notesapp.Models.Notes;
import org.w3c.dom.Document;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Locale;
public class NoteView extends AppCompatActivity {
EditText contentEditText;
ImageView micImg;
SpeechRecognizer speechRecognizer;
int count = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_note_view);
getSupportActionBar().hide();
contentEditText = findViewById(R.id.contentNotes);
micImg = findViewById(R.id.micImg);
speechRecognizer = SpeechRecognizer.createSpeechRecognizer(this);
Intent speechIntent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
speechIntent.putExtra(RecognizerIntent.EXTRA_PARTIAL_RESULTS, true);
speechIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
speechIntent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE,"voice.recognition.test");
speechIntent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS,5);
micImg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(count==0){
micImg.setImageResource(R.drawable.micvoice);
speechRecognizer.startListening(speechIntent);
count=1;
}
else{
micImg.setImageResource(R.drawable.mic);
speechRecognizer.stopListening();
count=0;
}
}
});
speechRecognizer.setRecognitionListener(new RecognitionListener() {
#Override
public void onReadyForSpeech(Bundle bundle) {
}
#Override
public void onBeginningOfSpeech() {
}
#Override
public void onRmsChanged(float v) {
}
#Override
public void onBufferReceived(byte[] bytes) {
}
#Override
public void onEndOfSpeech() {
}
#Override
public void onError(int i) {
}
#Override
public void onResults(Bundle bundle) {
/*ArrayList<String> data = bundle.getStringArrayList(speechRecognizer.RESULTS_RECOGNITION);
contentEditText.setText(data.get(0));
Log.e("csData", String.valueOf(data));*/
String str = new String();
Log.e( "csonResults " , String.valueOf(bundle));
ArrayList data = bundle.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
for (int i = 0; i < data.size(); i++)
{
Log.e("csresult", String.valueOf(data.get(i)));
str += data.get(i);
}
}
#Override
public void onPartialResults(Bundle bundle) {
ArrayList data = bundle.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
String word = (String) data.get(data.size() - 1);
contentEditText.setText(word);
Log.e("csWord", word);
}
#Override
public void onEvent(int i, Bundle bundle) {
}
});
}
#Override
public void onBackPressed() {
super.onBackPressed();
saveData();
finish();
}
}

Related

onclicklistner on videoview in recyclerview

hi i am building a app where, i show videos from firebase to videoview which is in recyclerview in gridlayout form, means at each fragment there are two videos shown, i want to add on clicklisten to them as when someone click on it, a new activity opens and at that activity, the same video is shown in fullscreen (vertically). i used putextra to transfer my data, but i am getting error, "uristring",
bellow is my code
Adapter code
package com.example.godhelpme.Adapter;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.MediaController;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.VideoView;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import androidx.recyclerview.widget.RecyclerView;
import com.example.godhelpme.Fragments.HomeFragment;
import com.example.godhelpme.FullScreen;
import com.example.godhelpme.LoginActivity;
import com.example.godhelpme.MainActivity;
import com.example.godhelpme.Model.Post;
import com.example.godhelpme.Model.User;
import com.example.godhelpme.R;
import com.example.godhelpme.StartActivity;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.List;
public class PostAdapter extends RecyclerView.Adapter<PostAdapter.ViewHolder>{
private Context mContext;
private List<Post> mPosts;
private FirebaseUser firebaseUser;
public PostAdapter(Context mContext, List<Post> mPosts) {
this.mContext = mContext;
this.mPosts = mPosts;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(mContext).inflate(R.layout.upload_item, parent,false);
return new PostAdapter.ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
Post post = mPosts.get(position);
try {
String link = post.getVideourl();
MediaController mediaController = new MediaController(mContext);
mediaController.setAnchorView(holder.video1);
Uri video = Uri.parse(link);
holder.video1.setMediaController(mediaController);
holder.video1.setVideoURI(video);
holder.video1.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mediaPlayer) {
try {
if (mediaPlayer.isPlaying()) {
mediaPlayer.stop();
mediaPlayer.release();
mediaPlayer = new MediaPlayer();
}
mediaPlayer.setVolume(0f, 0f);
mediaPlayer.setLooping(false);
mediaPlayer.start();
} catch (Exception e) {
e.printStackTrace();
}
mediaController.setVisibility(View.GONE);
}
});
holder.video1.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mediaPlayer) {
mediaPlayer.start(); }
});
holder.id.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent in = new Intent(view.getContext(),FullScreen.class);
in.putExtra(" videourl", post.getVideourl());
in.putExtra("publisher", post.getPublisher());
in.putExtra("postid", post.getPostid());
view.getContext().startActivity(in);
}
});
}catch (Exception e){
Toast.makeText(mContext,e.getMessage(), Toast.LENGTH_SHORT).show();
}
FirebaseDatabase.getInstance().getReference().child("Users").child(post.getPublisher())
.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
User user = snapshot.getValue(User.class);
holder.id.setText(user.getUsername());
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
#Override
public int getItemCount() {
return mPosts.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
public VideoView video1;
public TextView id;
public ViewHolder(#NonNull View itemView) {
super(itemView);
video1 = itemView.findViewById(R.id.video1);
id = itemView.findViewById(R.id.id);
}
}
}
THAT ACTIVITY CODE WHERE I WANT TO SHOW
package com.example.godhelpme;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.widget.MediaController;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.VideoView;
import com.example.godhelpme.Model.Post;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
public class FullScreen extends AppCompatActivity {
VideoView videoFull;
TextView idFull;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().hide();
setContentView(R.layout.activity_full_screen);
videoFull = findViewById(R.id.videoFull);
idFull = findViewById(R.id.idFull);
Intent in = getIntent();
try{
String ttr = in.getStringExtra("videourl");
MediaController mediaController = new MediaController(this);
mediaController.setAnchorView(videoFull);
Uri video1 = Uri.parse(ttr);
videoFull.setMediaController(mediaController);
videoFull.setVideoURI(video1);
}catch (Exception e){
Toast.makeText(this,e.getMessage(), Toast.LENGTH_SHORT).show();
}
videoFull.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mediaPlayer) {
mediaPlayer.start(); }
});
idFull.setText(in.getStringExtra("publisher"));
}
}
PLEASE HELP GUYS PLEASE
It took me three days to figure out what's the problem in my code. After knowing my mistake i am feeling very ashamed as well as happy that i figured, it out.
the mistake is in the adapter code,
in.putExtra(" videourl", post.getVideourl());
String ttr = in.getStringExtra("videourl");
the difference between above two code line is the, in first line there is space before the videourl and in the second line there is no space before videourl, and that's a problem. :-)

My Quiz App is crashing when I load Categories from Firebase Firestore but able to recieve users data to firestore from App

When I try to load categories in any activity the quizapp is getting crashed when i load. But when i send users data to firestore, its working.
All the data set in DbQuery.java matches the names entered with Firestore data. But There is something wrong in this that whenever I load this data in login Activity, signup activity or splash activity the app is getting crashed.
Here is my code:
DbQuery.java
package com.nightout.ttsgeneralawareness;
import android.content.Intent;
import android.util.ArrayMap;
import androidx.annotation.NonNull;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.firestore.DocumentReference;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.FieldValue;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.QueryDocumentSnapshot;
import com.google.firebase.firestore.QuerySnapshot;
import com.google.firebase.firestore.WriteBatch;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
public class DbQuery {
public static FirebaseFirestore g_firestore;
public static List<CategoryModel> g_catList = new ArrayList<>();
public static void createUserData(String email, String name, MyCompleteListener completeListener) {
Map<String, Object> userData = new ArrayMap<>();
userData.put("EMAIL_ID", email);
userData.put("NAME", name);
userData.put("TOTAL_SCORE", 0);
DocumentReference userDoc = g_firestore.collection("USERS")
.document(Objects.requireNonNull(FirebaseAuth.getInstance().getCurrentUser()).getUid());
WriteBatch batch = g_firestore.batch();
batch.set(userDoc, userData);
DocumentReference countDoc = g_firestore.collection("USERS").document("TOTAL_USERS");
batch.update(countDoc, "COUNT", FieldValue.increment(1));
batch.commit()
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void unused) {
completeListener.onSuccess();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
completeListener.onFailure();
}
});
}
public static void loadCategories(MyCompleteListener completeListener) {
g_catList.clear();
g_firestore.collection("QUIZ").get()
.addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
#Override
public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
Map<String, QueryDocumentSnapshot> docList = new ArrayMap<>();
for (QueryDocumentSnapshot doc : queryDocumentSnapshots) {
docList.put(doc.getId(), doc);
}
QueryDocumentSnapshot catListDooc = docList.get("Categories");
long catCount = catListDooc.getLong("COUNT");
for (int i = 1; i <= catCount; i++) {
String catID = catListDooc.getString("CAT" + String.valueOf(i) + "_ID");
QueryDocumentSnapshot catDoc = docList.get(catID);
int noOfTest = catDoc.getLong("NO_OF_TESTS").intValue();
String catName = catDoc.getString("NAME");
g_catList.add(new CategoryModel(catID, catName, noOfTest));
}
completeListener.onSuccess();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
completeListener.onFailure();
}
});
}
LoginActivity.java
package com.nightout.ttsgeneralawareness;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.auth.api.signin.GoogleSignIn;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInClient;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.common.api.ApiException;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthCredential;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.auth.GoogleAuthProvider;
import java.util.Locale;
public class LoginActivity extends AppCompatActivity {
private EditText email, password;
private Button loginButton;
private TextView forgotpwd, signup_button;
private FirebaseAuth mAuth;
private Dialog progressDialog;
private TextView dialogText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
getSupportActionBar().hide();
email = findViewById(R.id.email);
password = findViewById(R.id.password);
loginButton = findViewById(R.id.login_button);
forgotpwd = findViewById(R.id.forgot_pwd);
signup_button = findViewById(R.id.signup_button);
//google
progressDialog = new Dialog(LoginActivity.this);
progressDialog.setContentView(R.layout.dialog);
progressDialog.setCancelable(false);
progressDialog.getWindow().setLayout(ViewGroup.LayoutParams.WRAP_CONTENT,ViewGroup.LayoutParams.WRAP_CONTENT);
dialogText = progressDialog.findViewById(R.id.dialog_text);
dialogText.setText("Signing in...");
mAuth = FirebaseAuth.getInstance();
//google
loginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (validData())
{
login();
}
}
});
signup_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(LoginActivity.this, SignUpActivity.class);
startActivity(intent);
}
});
}
private boolean validData()
{
if (email.getText().toString().isEmpty())
{
email.setError("Enter E-Mail ID");
return false;
}
if (password.getText().toString().isEmpty())
{
password.setError("Enter Password");
return false;
}
return true;
}
private void login()
{
progressDialog.show();
mAuth.signInWithEmailAndPassword(email.getText().toString().trim(), password.getText().toString().trim())
.addOnCompleteListener(this, task -> {
if (task.isSuccessful()) {
// Sign in success, update UI with the signed-in user's information
Toast.makeText(LoginActivity.this,"Login Success",Toast.LENGTH_SHORT).show();
DbQuery.loadCategories(new MyCompleteListener() {
#Override
public void onSuccess() {
progressDialog.dismiss();
Intent intent = new Intent(LoginActivity.this,MainActivity.class);
startActivity(intent);
LoginActivity.this.finish();
}
#Override
public void onFailure() {
progressDialog.dismiss();
Toast.makeText(LoginActivity.this,"Something Went Wrong!",Toast.LENGTH_SHORT).show();
}
});
} else {
progressDialog.dismiss();
// If sign in fails, display a message to the user.
Toast.makeText(LoginActivity.this, task.getException().getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
}
}

Android Studio, Screeen To Screen Problem

basically im trying to make it so LoginScreen goes to Category screen .
package Screens;
import androidx.appcompat.app.AppCompatActivity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.hr111.User.R;
import Utils.DisplayUtils;
import Utils.PlanUtils;
import Utils.SharedPreferencesUtils;
public class CategoryScreen extends AppCompatActivity {
Button btnExit;
Button btnChemistry;
Button btnBiology;
Button btnPhysics;
TextView textPlayerName;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_category_screen);
btnExit = findViewById(R.id.btnExit);
textPlayerName = findViewById(R.id.textViewName);
btnBiology = findViewById(R.id.btnBiology);
btnPhysics = findViewById(R.id.btnPhysics);
btnChemistry = findViewById(R.id.btnChemistry);
String username = SharedPreferencesUtils.getStringPreference(CategoryScreen.this, "username");
textPlayerName.append(username);
btnBiology.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
goToQuestions(btnBiology.getText().toString());
}
});
btnPhysics.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
goToQuestions(btnPhysics.getText().toString());
}
});
btnChemistry.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
goToQuestions(btnChemistry.getText().toString());
}
});
btnExit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DisplayUtils.DisplayScript(CategoryScreen.this, "Exit", "Cikmak Istiyor Musunuz?",
"Hayır", "Evet", null, null);
}
});
}
void goToQuestions(String CategoryName){
SharedPreferencesUtils.settingStringPreference(CategoryScreen.this, "category", CategoryName);
SharedPreferencesUtils.settingIntegerPreference(CategoryScreen.this, "questionCount", 1);
SharedPreferencesUtils.settingIntegerPreference(CategoryScreen.this, "score", 0);
PlanUtils.GoToActivity(CategoryScreen.this, GameScreen.class);
}
}
package Screens;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.hr111.User.MainActivity;
import com.hr111.User.R;
import Utils.DisplayUtils;
import Utils.ExcerciseClass;
import Utils.PlanUtils;
import Utils.SharedPreferencesUtils;
public class LoginScreen extends AppCompatActivity implements View.OnClickListener {
Button btnNext;
TextView username;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login_screen);
btnNext = findViewById(R.id.buttonLogin);
username = findViewById(R.id.plaintextName);
btnNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String name = username.getText().toString().trim();
if(nameCheck(name))
{
SharedPreferencesUtils.settingStringPreference(LoginScreen.this, "playername", name);
PlanUtils.GoToActivity(LoginScreen.this, CategoryScreen.class);
}
else
{
DisplayUtils.DisplayScript(LoginScreen.this, "ERROR!", "Gecerli bir oyuncu adi seciniz!", null, null, null, null);
}
}
});
}
boolean nameCheck(String name){
if(name == null) return false;
if(name.length() == 0) return false;
return true;
}
#Override
public void onClick(View v) {
}
}
Both screens are in different Classes.
But it simply crashes before LoginScreen can reach to Category Screen. Any clue why this is not working? I have been trying to figure out and i used different variations of codes but all led me to to nothing. I have also tried on a different project but that also led me to nowhere. Thanks in advance

No setter/field for url found on class com.example.scheduletask.model.Task can't retrieve data from firebase database to detail activity

im trying to retrieve data from firebase to detail activity. On the listview, it show perfectly. But when i click, the detail activity opened but still empty. All it says "W/ClassMapper: No setter/field for url found on class com.example.scheduletask.model.Task". I thought the setter on model task wasn't used, but i don't know... im sorry, i don't understand, i don't know what i missed:( any help is appreciated, thank youuu
TaskActivity.java
package com.example.scheduletask;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.example.scheduletask.adapter.MatkulAdapter;
import com.example.scheduletask.adapter.TaskAdapter;
import com.example.scheduletask.adapter.TaskDetailAdapter;
import com.example.scheduletask.database.FirebaseTaskHelper;
import com.example.scheduletask.model.Matkul;
import com.example.scheduletask.model.Task;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import java.util.Iterator;
public class TaskActivity extends AppCompatActivity {
DatabaseReference databaseReference;
ListView listViewTask;
FloatingActionButton fabAddTask;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_task);
databaseReference = FirebaseDatabase.getInstance().getReference("Task");
listViewTask = findViewById(R.id.tasklist);
showData();
fabAddTask = findViewById(R.id.fab_addtask);
fabAddTask.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(TaskActivity.this, CreateTaskActivity.class);
startActivity(intent);
}
});
listViewTask.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String subjectTask = ((TextView)view.findViewById(R.id.txt_subjectlisttask)).getTag().toString();
Intent taskDetail = new Intent(TaskActivity.this, TaskDetailActivity.class);
taskDetail.putExtra("subjectTask", subjectTask);
startActivity(taskDetail);
}
});
}
private void showData() {
final ArrayList<String> subjectTask = new ArrayList<>();
final ArrayList<String> taskDueDate = new ArrayList<>();
final ArrayList<String> taskDescription = new ArrayList<>();
final ArrayList<String> imageURL = new ArrayList<>();
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
Iterable<DataSnapshot> snapshotIterable = dataSnapshot.getChildren();
Iterator<DataSnapshot> iterator = snapshotIterable.iterator();
while (iterator.hasNext()){
Task value = iterator.next().getValue(Task.class);
assert value != null;
subjectTask.add(value.getSubjectTask());
taskDescription.add(value.getTaskDescription());
taskDueDate.add(value.getTaskDueDate());
imageURL.add(value.getImageURL());
((TaskAdapter)listViewTask.getAdapter()).notifyDataSetChanged();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
listViewTask.setAdapter(new TaskAdapter(subjectTask, taskDescription, taskDueDate, imageURL, this));
}
#Override
protected void onResume() {
super.onResume();
showData();
}
}
Task.java (this is the model)
package com.example.scheduletask.model;
public class Task {
private String taskDueDate;
public String getTaskDueDate() {
return taskDueDate;
}
public void setTaskDueDate(String taskDueDate) {
this.taskDueDate = taskDueDate;
}
private String subjectTask;
public String getTaskDescription() {
return taskDescription;
}
public void setTaskDescription(String taskDescription) {
this.taskDescription = taskDescription;
}
public String getImageURL() {
return imageURL;
}
public void setImageURL(String imageURL) {
this.imageURL = imageURL;
}
private String taskDescription;
private String imageURL;
public String getSubjectTask() {
return subjectTask;
}
public void setSubjectTask(String subjectTask) {
this.subjectTask = subjectTask;
}
}
TaskDetailActivity.java
package com.example.scheduletask;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.example.scheduletask.model.Task;
import com.github.barteksc.pdfviewer.PDFView;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
import com.google.firebase.database.ValueEventListener;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.squareup.picasso.Picasso;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;
public class TaskDetailActivity extends AppCompatActivity {
EditText edtSubject, edtDueDate, edtDescription;
ImageView filePhoto;
ProgressBar progressBarDetail;
Button btnEdit, btnDelete;
DatabaseReference databaseReference;
private String photoURL, subjectTask;
Button btnViewPDF;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_task_detail);
databaseReference = FirebaseDatabase.getInstance().getReference("Task");
subjectTask = getIntent().getExtras().getString("subjectTask");
progressBarDetail = findViewById(R.id.progressbardetail);
progressBarDetail.setVisibility(View.INVISIBLE);
readData();
findAllViewsID();
}
private void readData() {
progressBarDetail.setVisibility(View.VISIBLE);
Query findQuery = databaseReference.orderByKey().equalTo(subjectTask);
findQuery.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot getSnapshot : dataSnapshot.getChildren()){
edtSubject.setText(getSnapshot.child("subjectTask").getValue().toString());
edtDescription.setText(getSnapshot.child("taskDescription").getValue().toString());
edtDueDate.setText(getSnapshot.child("taskDueDate").getValue().toString());
photoURL = getSnapshot.child("imageURL").getValue().toString();
Picasso.get().load(photoURL).fit().into(filePhoto);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
progressBarDetail.setVisibility(View.INVISIBLE);
}
});
progressBarDetail.setVisibility(View.INVISIBLE);
}
private void findAllViewsID() {
edtSubject = findViewById(R.id.edt_updatetasksubject);
edtDescription = findViewById(R.id.edt_updatetaskdescription);
edtDueDate = findViewById(R.id.edt_updateduedatetime);
filePhoto = findViewById(R.id.iv_taskphotoinput);
btnViewPDF = findViewById(R.id.btn_viewpdf);
btnDelete = findViewById(R.id.btn_deletetask);
btnEdit = findViewById(R.id.btn_edittask);
}
}
TaskAdapter.java
package com.example.scheduletask.adapter;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import com.example.scheduletask.R;
import com.example.scheduletask.TaskActivity;
import com.example.scheduletask.TaskDetailActivity;
import com.example.scheduletask.model.Task;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
public class TaskAdapter extends BaseAdapter {
private ArrayList<String> subjectTask;
private ArrayList<String> taskDescription;
private ArrayList<String> taskDueDate;
private ArrayList<String> imageURL;
private AppCompatActivity activity;
public TaskAdapter(ArrayList<String> subjectTask, ArrayList<String> taskDescription, ArrayList<String> taskDueDate, ArrayList<String> imageURL, AppCompatActivity activity) {
this.subjectTask = subjectTask;
this.taskDescription = taskDescription;
this.taskDueDate = taskDueDate;
this.imageURL = imageURL;
this.activity = activity;
}
Context ctx;
ArrayList<Task> tasks;
#Override
public int getCount() {
return subjectTask.size();
}
#Override
public Object getItem(int position) {
return subjectTask.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
public TaskAdapter(#NonNull Context ctx, ArrayList<Task> tasks) {
this.ctx = ctx;
this.tasks = tasks;
}
public View getView(int position, View view, ViewGroup parent) {
view = LayoutInflater.from(activity.getApplicationContext())
.inflate(R.layout.list_task, parent, false);
view.findViewById(R.id.txt_subjectlisttask).setTag(String.valueOf(subjectTask.get(position)));
((TextView)view.findViewById(R.id.txt_subjectlisttask)).setText(String.valueOf(subjectTask.get(position)));
((TextView)view.findViewById(R.id.txt_duedatetasklist)).setText(String.valueOf(taskDueDate.get(position)));
return view; }
}
Here is the logcat when i click the task listview
And this is my database

Text-to-Speech Function not working

The Android does not talk despite my code being error free and accurate. I have used a toast function to see where the issue occurs. However, both toasts are called.
I have removed all irrelevant code.
The code below is mostly relevant.
package com.example.android.BluetoothChat;
import android.R.string;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.telephony.SmsManager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.Locale;
import java.util.Set;
import android.bluetooth.BluetoothDevice;
import java.io.InputStream;
import java.io.OutputStream;
import android.bluetooth.BluetoothSocket;
import android.widget.EditText;
import java.io.IOException;
import java.util.UUID;
public class MainActivity extends Activity implements LocationListener{
Button start, stop;
TextView tv;
TextView tv2;
TextView sum;
LocationManager lm;
static TextToSpeech Talker;
TextView myLabel;
Handler mhandler = new Handler();
int i;
int sum1 = 0;
static BluetoothDevice mmDevice;
static BluetoothAdapter mBluetoothAdapter;
static BluetoothSocket mmSocket;
String lat;
String lon;
EditText myTextbox;
static OutputStream mmOutputStream;
static InputStream mmInputStream;
static Thread workerThread;
static byte[] readBuffer;
static int readBufferPosition;
static int counter;
static volatile boolean stopWorker;
TextToSpeech talker;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main2);
setTitle("Seizure Detection Helmet Application");
myTextbox = (EditText)this.findViewById(R.id.name);
talker = new TextToSpeech(getApplicationContext(),new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
if(status != TextToSpeech.ERROR)
{
talker.setLanguage(Locale.US);
}
}
});
Button talk = (Button)this.findViewById(R.id.talk);
talk.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
speakOut();
}
});
public void speakOut()
{
String toSpeak = myTextbox.getText().toString();
Toast.makeText(getApplicationContext(), toSpeak, Toast.LENGTH_SHORT).show();
String full = ("My name is"+toSpeak+ "and I am having a Seizure at 38.901 Latitude and -77.031 Longitude ");
Toast.makeText(getApplicationContext(), toSpeak, Toast.LENGTH_SHORT).show();
talker.speak(full, TextToSpeech.QUEUE_FLUSH, null);
Toast.makeText(getApplicationContext(), full, Toast.LENGTH_SHORT).show();
talker.speak("HELLO",TextToSpeech.QUEUE_FLUSH, null);
}
}
There are several problems with your code. You should check for error returned by setLanguage. You cannot call speakOut until onInit has been called. One way you can insure this is to disable the talk button in the xml layout file and enable it in onInit.

Categories