How to delete data from firebase and recyclerview Android Studio - java

I try making program for deleting program from firebase. I use alertdialog so user can choose will delete data or not but when i try choose delete data my app get crashed. I have try some method for similar case but still not solved my case. Can someone tell me how to fix this?
My code for deleting data
#Override
protected void onStart(){
super.onStart();
firebaseRecyclerAdapter =
new FirebaseRecyclerAdapter<AdminStockIn, AdminViewHolder>(
AdminStockIn.class,
R.layout.row_admin_stockin_new,
AdminViewHolder.class,
DatabaseAddStock
) {
#Override
protected void populateViewHolder( AdminViewHolder adminViewHolder, AdminStockIn adminStockIn, int i) {
adminViewHolder.SetDetails(getApplicationContext(), adminStockIn.getDate(),
adminStockIn.getTime(), adminStockIn.getName(), adminStockIn.getQuantity(),
adminStockIn.getVendor(), adminStockIn.getRack());
adminViewHolder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Dialog dialog = new Dialog(AdminStockInActivity.this);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.admin_stock_in_popup);
Objects.requireNonNull(dialog.getWindow());
dialog.setCancelable(true);
WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
lp.copyFrom(Objects.requireNonNull(dialog.getWindow()).getAttributes());
lp.width = WindowManager.LayoutParams.MATCH_PARENT;
lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
dialog.getWindow().setAttributes(lp);
EditText namepop = dialog.findViewById(R.id.nameSearchPop);
EditText quantitypop = dialog.findViewById(R.id.inputItemQuantityPop);
EditText vendorpop = dialog.findViewById(R.id.inputItemVendorPop);
EditText rackpop = dialog.findViewById(R.id.inputItemRackPop);
Button updatepop = dialog.findViewById(R.id.buttonUpdateStockPop);
namepop.setText(adminStockIn.getName());
quantitypop.setText(adminStockIn.getQuantity().toString());
vendorpop.setText(adminStockIn.getVendor());
rackpop.setText(adminStockIn.getRack());
dialog.show();
updatepop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Map<String, Object> map = new HashMap();
map.put("name", namepop.getText().toString());
map.put("quantity", quantitypop.getText().toString());
map.put("vendor", vendorpop.getText().toString());
map.put("rack", rackpop.getText().toString());
DatabaseAddStock.child(getRef(i).getKey()).updateChildren(map).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void unused) {
Toast.makeText(AdminStockInActivity.this, "Data Have Updated", Toast.LENGTH_LONG).show();
dialog.dismiss();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(AdminStockInActivity.this, "Data Can't Updated", Toast.LENGTH_LONG).show();
dialog.dismiss();
}
});
}
});
}
});
//Hapus file
adminViewHolder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View view) {
AlertDialog.Builder builder = new AlertDialog.Builder(AdminStockInActivity.this);
builder.setTitle("Hapus Barang Ini?");
builder.setMessage("Data tidak bisa dipulihkan setelah dihapus");
builder.setPositiveButton("Ya", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
int index = i-1;
firebaseRecyclerAdapter.getRef(index).removeValue();
firebaseRecyclerAdapter.notifyItemRemoved(i);
DatabaseAddStock.child(getRef(i).getKey()).removeValue();
firebaseRecyclerAdapter.notifyDataSetChanged();
}
});
builder.setNegativeButton("Tidak", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
Toast.makeText(AdminStockInActivity.this, "Data tidak jadi dihapus", Toast.LENGTH_SHORT).show();
}
});
builder.show();
return true;
}
});
}
};
rv_item.setAdapter(firebaseRecyclerAdapter);
}
Here my logcat
2021-11-15 13:41:52.836 24724-24724/com.example.w_a_m_s_y E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.w_a_m_s_y, PID: 24724
java.lang.ArrayIndexOutOfBoundsException: length=10; index=-2
at java.util.ArrayList.get(ArrayList.java:439)
at com.firebase.ui.database.ObservableSnapshotArray.get(ObservableSnapshotArray.java:165)
at com.firebase.ui.database.FirebaseRecyclerAdapter.getRef(FirebaseRecyclerAdapter.java:185)
at com.example.w_a_m_s_y.Admin.AdminStockFlow.AdminStockInActivity$5$2$1.onClick(AdminStockInActivity.java:348)
at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:174)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:236)
at android.app.ActivityThread.main(ActivityThread.java:8043)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:620)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1011)

Related

nothing happen when i select the song to upload from my android app to firebase realtime database

I was creating an app for my semester project to upload songs from mobile storage to firebase's realtime database. app run correctly but when i select the songs to upload nothing happens and the app also does not crash. my main activity code is:
public class MainActivity extends AppCompatActivity {
private boolean checkPermission = false;
Uri uri;
String songName, songUrl;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
//Create 2 function
//onCreate option menu to initialize menu
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.custom_menu , menu);
return super.onCreateOptionsMenu(menu);
}
//2nd function is onoption item selected (button sy reloated sari coding yaha hogi
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
if (item.getItemId()==R.id.nav_upload){
if (validatePermission()){
picksongs();
}
}
return super.onOptionsItemSelected(item);
}
private void picksongs() {
Intent intent_upload = new Intent();
intent_upload.setType("audio/*");
intent_upload.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent_upload , 1);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
if(requestCode == 1){
if (requestCode==RESULT_OK){
uri = data.getData();
Cursor mcursor = getApplicationContext().getContentResolver().query(uri , null, null, null , null);
int indexName = mcursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
songName = mcursor.getString(indexName);
mcursor.close();
uploadSong();
}
}
super.onActivityResult(requestCode, resultCode, data);
}
private void uploadSong() {
StorageReference storageReference = FirebaseStorage.getInstance().getReference().child("Songs").child(uri.getLastPathSegment());
ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.show();
//upload files to firebase
storageReference.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Task<Uri> uriTask = taskSnapshot.getStorage().getDownloadUrl();
while (!uriTask.isComplete());
Uri urlSong =uriTask.getResult();
songUrl = urlSong.toString();
uploadtoDataBase();
progressDialog.dismiss();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(MainActivity.this, e.getMessage().toString(), Toast.LENGTH_SHORT).show();
progressDialog.dismiss();
}
}).addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(#NonNull UploadTask.TaskSnapshot tasksnapshot) {
double progress = (100.0*tasksnapshot.getBytesTransferred())/tasksnapshot.getTotalByteCount();
int currentProgress = (int)progress;
progressDialog.setMessage("Uploaded "+ currentProgress+"%");
}
});
}
private void uploadtoDataBase(){
Song songobj = new Song(songName , songUrl);
FirebaseDatabase.getInstance().getReference("Songs").push().setValue(songobj).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()){
Toast.makeText(MainActivity.this, "Uploaded Successfully", Toast.LENGTH_SHORT).show();
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(MainActivity.this, e.getMessage().toString(), Toast.LENGTH_SHORT).show();
}
});
}
private boolean validatePermission(){
Dexter.withActivity(this)
//Dexter.withActivity(MainActivity.this)
.withPermission(Manifest.permission.READ_EXTERNAL_STORAGE)
.withListener(new PermissionListener() {
#Override
public void onPermissionGranted(PermissionGrantedResponse permissionGrantedResponse) {
checkPermission=true;
}
#Override
public void onPermissionDenied(PermissionDeniedResponse permissionDeniedResponse) {
checkPermission=false;
}
#Override
public void onPermissionRationaleShouldBeShown(PermissionRequest permissionRequest, PermissionToken permissionToken) {
permissionToken.continuePermissionRequest();
}
}).check();
return checkPermission;
}
}
please help me to find where i made a mistake. but their is 1 problem startActivityForResult(android.content.Intent, int)' is deprecated is that cause the problem? if yes then how can i solve this

How do I make the terms and conditions appear only when I log in to Google for the first time?

I want to add terms and conditions when users use my app.
But I have to show terms and conditions only one time.
I'm using firebase google login. But I have a problem when I show terms and conditions and how code remembers users accept terms and conditions and shows only one time.
Here's a google login code.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
//새로운 코드다 마
signInButton = findViewById(R.id.signInButton);
GoogleSignInOptions googleSignInOptions = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.default_web_client_id))
.requestEmail()
.build();
googleApiClient = new GoogleApiClient.Builder(this)
.enableAutoManage(this,this)
.addApi(Auth.GOOGLE_SIGN_IN_API, googleSignInOptions)
.build();
auth = FirebaseAuth.getInstance(); //파이어 베이스 인증 객체 초기화
signInButton.setOnClickListener(new View.OnClickListener() { // 구글 로그인 버튼을 클릭했을때 이곳을 수행
#Override
public void onClick(View view) {
Intent intent = Auth.GoogleSignInApi.getSignInIntent(googleApiClient);
startActivityForResult(intent,REQ_SIGN_GOOGLE);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) { // 구글 로그인 인증을 요청했을때 결과 값을 되돌려 받는 곳
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == REQ_SIGN_GOOGLE) {
GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
if(result.isSuccess() == true) { // true 생략 가능, 인증 결과가 성공적이면
GoogleSignInAccount account = result.getSignInAccount(); //account 라는 데이터는 구글 로그인 정보를 담고 있습니다. - 닉네임,프로필사진uri,이메일 주소등
resultLogin(account); // 로그인 결과 값 출력 수행하라는 메서드
}
}
}
private void resultLogin(GoogleSignInAccount account) {
AuthCredential credential = GoogleAuthProvider.getCredential(account.getIdToken(), null);
auth.signInWithCredential(credential).addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()) { //로그인이 성공했으면
Intent intent = new Intent(getApplicationContext(),Home.class);
startActivity(intent);
}
else{
Toast.makeText(LoginActivity.this,"로그인 실패",Toast.LENGTH_SHORT).show();
}
}
});
}
#Override
public void onBackPressed() {
long curTime=System.currentTimeMillis();
long gapTime=curTime-backBtnTime;
if(0<=gapTime && 2000>= gapTime){
moveTaskToBack(true);
finishAndRemoveTask();
android.os.Process.killProcess(android.os.Process.myPid());
}
else {
backBtnTime = curTime;
Toast.makeText(this,"뒤로 버튼을 한 번 더 누르면 종료됩니다.",Toast.LENGTH_SHORT).show();
}
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
Here is a code I want to show (terms and conditions)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_terms);
CheckBox checkBox=findViewById(R.id.checkbox);
CheckBox checkBox2=findViewById(R.id.checkbox2);
CheckBox checkBox3=findViewById(R.id.checkbox3);
checkBox.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(checkBox.isChecked()){
checkBox2.setChecked(true);
checkBox3.setChecked(true);
}else {
checkBox2.setChecked(false);
checkBox3.setChecked(false);
}
}
});
checkBox2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(checkBox.isChecked()){
checkBox.setChecked(false);
}else if(checkBox2.isChecked()&&checkBox3.isChecked()){
checkBox.setChecked(true);
}
}
});
checkBox3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(checkBox.isChecked()){
checkBox.setChecked(false);
}else if(checkBox2.isChecked()&&checkBox3.isChecked()){
checkBox.setChecked(true);
}
}
});
Button btn_agr = findViewById(R.id.btn_agr1);
btn_agr.setText(R.string.app_name);
btn_agr.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(TermsActivity.this);
builder.setTitle("서비스 이용약관 ");
builder.setMessage(R.string.app_name);
builder.setNegativeButton("닫기",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
System.out.println(TAG + "이용약관 닫기");
}
});
builder.show();
}
});
Button btn_agr2 = findViewById(R.id.btn_agr2);
btn_agr2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(TermsActivity.this);
builder.setTitle("위치 정보 이용 약관 ");
builder.setMessage(R.string.app_name);
builder.setNegativeButton("닫기",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
System.out.println(TAG + "이용약관 닫기");
}
});
builder.show();
}
});
Button btn_complete = findViewById(R.id.button_complete);
btn_complete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
I tried my self - transmit variables when the user accept terms and conditions but when the user reopens the app user has to open it again
Maybe there is a way to transmit certain variables to firebase and confirm it when the user clicks the login button??
There is a way to transmit certain variables to firebase and confirm it when the user clicks the login button?
The simplest solution would be to call AuthResult#getAdditionalUserInfo() method on the Task object, because it returns an object of type AdditionalUserInfo. In this class, you can find a very useful method called isNewUser(), which can help you check if the user signs in for the first time. In code should look like this:
AuthCredential credential = GoogleAuthProvider.getCredential(account.getIdToken(), null);
auth.signInWithCredential(credential).addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()) { //로그인이 성공했으면
boolean isNewUser = task.getResult().getAdditionalUserInfo().isNewUser();
if (isNewUser) {
//Display Terms & Conditions
}
Intent intent = new Intent(getApplicationContext(),Home.class);
startActivity(intent);
}
else{
Toast.makeText(LoginActivity.this,"로그인 실패",Toast.LENGTH_SHORT).show();
}
}
});

Android studio : FATAL EXCEPTION: main

while I testing my app, I get the following error in the Android-Studio-logcat:
before getting this error, I was clicked on setPositiveButton of alert Dialog Button name is "EMAIL ME" with empty EditText.
and then I got Unfortunately twist has stopped.
please I need help!!
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.testing.twist, PID: 30072
java.lang.IllegalArgumentException: Given String is empty or null
at com.google.android.gms.common.internal.Preconditions.checkNotEmpty(Unknown
Source)
at com.google.firebase.auth.FirebaseAuth.sendPasswordResetEmail(com.google.firebase:firebase-auth##19.3.1:307)
at com.testing.twist.login.beginforgotpasswd(login.java:141)
at com.testing.twist.login.access$400(login.java:26)
at com.testing.twist.login$4.onClick(login.java:119)
at androidx.appcompat.app.AlertController$ButtonHandler.handleMessage(AlertController.java:167)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5268)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:902)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:697)
here is some code of my login.java file
public class login extends AppCompatActivity {
private EditText Email;
private EditText password;
private Button btn_login;
private TextView tv_signup;
private FirebaseAuth firebaseAuth;
private TextView tv_forgotpasswd_l;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
Email = (EditText)findViewById(R.id.et_email_l);
password = (EditText)findViewById(R.id.et_passwd_l);
btn_login = (Button)findViewById(R.id.btn_l);
tv_signup = (TextView)findViewById(R.id.tv_sign_up);
tv_forgotpasswd_l = (TextView)findViewById(R.id.tv_f_passwd);
firebaseAuth = FirebaseAuth.getInstance();
FirebaseUser user = firebaseAuth.getCurrentUser();
if(user != null){
finish();
startActivity(new Intent(login.this, MainActivity.class));
}
btn_login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
validate(Email.getText().toString(), password.getText().toString());
}
});
tv_signup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(login.this,Register.class));
}
});
// Login button hide
Email.addTextChangedListener(loginTextWatcher);
password.addTextChangedListener(loginTextWatcher);
// recover pass textview click
tv_forgotpasswd_l.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showForgotpasswdDialog();
}
});
}
// Alert Dialog
private void showForgotpasswdDialog()
{
//Dialog Box code
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Forgot your password?");
//set linear layout
LinearLayout linearLayout = new LinearLayout(this);
linearLayout.setOrientation(LinearLayout.VERTICAL);
linearLayout.setPadding(30,30,30,30);
Email.setPadding(10,10,10,10);
//view to set an dialog
final EditText Email = new EditText(this);
Email.setHint("Email");
Email.setInputType(InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS);
//text view
linearLayout.addView(Email);
builder.setView(linearLayout);
//text style
// Text view
final TextView tv = new TextView(this);
tv.setTextSize(14);
tv.setTypeface(null, Typeface.BOLD);
tv.setTextColor(Color.parseColor("black"));
tv.setText("Unfortunately, if you have never given us your email, we will not be able to reset your password.");
tv.setPadding(10,10,10,10);
linearLayout.addView(tv);
builder.setView(linearLayout);
//buttons for EMAIL ME
builder.setPositiveButton("EMAIL ME", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
//input email
String email = Email.getText().toString().trim();
beginforgotpasswd(email);
}
});
//buttons for CANCEL
builder.setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int i) {
// dismiss dialog
dialog.dismiss();
}
});
///show dialog
builder.create().show();
}
private void beginforgotpasswd(String email)
{
firebaseAuth.sendPasswordResetEmail(email).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task)
{
if (task.isSuccessful())
{
Toast.makeText(login.this,"Email sent",Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(login.this,"Failed...",Toast.LENGTH_SHORT).show();
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
//get and show proper error message
Toast.makeText(login.this,""+e.getMessage(),Toast.LENGTH_SHORT).show();
}
});
}
private TextWatcher loginTextWatcher = new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
String emailInput = Email.getText().toString().trim();
String passwdInput = password.getText().toString().trim();
btn_login.setEnabled(!emailInput.isEmpty() && !passwdInput.isEmpty());
}
#Override
public void afterTextChanged(Editable editable) {
}
};
private void validate(String usremail, String usrpassword){
firebaseAuth.signInWithEmailAndPassword(usremail,usrpassword).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(Task<AuthResult> task) {
if(task.isSuccessful()){
//Toast.makeText(login.this, "Login Successful",Toast.LENGTH_SHORT).show();
checkEmailVerification();
}
else{
Toast.makeText(login.this, "Login Failed",Toast.LENGTH_SHORT).show();
}
}
});
}
private void checkEmailVerification()
{
FirebaseUser firebaseUser = firebaseAuth.getInstance().getCurrentUser();
Boolean emailflag = firebaseUser.isEmailVerified();
if(emailflag)
{
finish();
startActivity(new Intent(login.this,MainActivity.class));
}
else
{
Toast.makeText(login.this, "Verify your email", Toast.LENGTH_SHORT).show();
firebaseAuth.signOut();
}
}
}
The call to firebaseAuth.sendPasswordResetEmail requires that the email you're sending the forgot password email to is not empty. Before calling the function check if the email is not empty.
private void beginforgotpasswd(String email)
{
if(email.isEmpty()) {
// display toast
} else {
firebaseAuth.sendPasswordResetEmail(email).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task)
{
if (task.isSuccessful())
{
Toast.makeText(login.this,"Email sent",Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(login.this,"Failed...",Toast.LENGTH_SHORT).show();
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
//get and show proper error message
Toast.makeText(login.this,""+e.getMessage(),Toast.LENGTH_SHORT).show();
}
});
}
}

Text to Speech without button(will be continuous act)

this project code belongs to the project for the blinds to purchase the items. the scanresult fetch the details to the textview and reads for them and uses gesture options to handle the app.
i created the android project byr barcode scanner and output as textview and voice output. used xzing library as you can see it in the code. the problem is after showing the scanresult in plaintext, it does't atuostart the audio output functionallity. that is the real usage of this project. i referred youtube but can't. then making a chance to anyone to fix this program to text to voice.
this is my code, when working no errors at all. but no audio output after the scanresult from the barcodescanner. i tried my level best. so anyone can help out of it ??/?.
public class SecondActivity extends AppCompatActivity implements ZXingScannerView.ResultHandler {
private static final int REQUEST_CAMERA =1;
private ZXingScannerView scannerView;
TextView result;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
scannerView = new ZXingScannerView(this);
setContentView(scannerView);
Toast.makeText(SecondActivity.this, "Firebase connection is successful", Toast.LENGTH_LONG).show();
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
{
if(checkPermission())
{
Toast.makeText(this, "permission is granted", Toast.LENGTH_SHORT).show();
}
else
{
requestPermission();
}
}
}
private boolean checkPermission()
{
return (ContextCompat.checkSelfPermission(SecondActivity.this, CAMERA) == PackageManager.PERMISSION_GRANTED);
}
private void requestPermission()
{
ActivityCompat.requestPermissions(this, new String[]{CAMERA}, REQUEST_CAMERA);
}
public void onRequestPermissionsResult(int requestCode, String permission[], int grantResults[])
{
switch(requestCode) {
case REQUEST_CAMERA:
if (grantResults.length > 0)
{
boolean cameraAccepted = grantResults[0] == PackageManager.PERMISSION_GRANTED;
if(cameraAccepted)
{
Toast.makeText(SecondActivity.this, "Permission Denied", Toast.LENGTH_LONG).show();
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
{
if(shouldShowRequestPermissionRationale(CAMERA))
{
displayAlertMessage("you need to allow access for both permission",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
requestPermissions(new String[]{CAMERA}, REQUEST_CAMERA);
}
});
return;
}
}
}
}
break;
}
}
#Override
public void onResume()
{
super.onResume();
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
{
if(checkPermission())
{
if(scannerView == null)
{
scannerView = new ZXingScannerView(this);
setContentView(scannerView);
}
scannerView.setResultHandler(this);
scannerView.startCamera();
}
else
{
requestPermission();
}
}
}
#Override
public void onDestroy(){
super.onDestroy();
scannerView.stopCamera();
}
public void displayAlertMessage(String message, DialogInterface.OnClickListener listener)
{
new AlertDialog.Builder(SecondActivity.this)
.setMessage(message)
.setPositiveButton("OK", listener)
.setNegativeButton("Cancel", null)
.create()
.show();
}
EditText ed1;
TextToSpeech txt;
#Override
public void handleResult(Result result) {
final String scanResult = result.getText();
setContentView(R.layout.activity_second);
final TextView text = (TextView) findViewById(R.id.editText);
/* long n=890103073;
long n1=Integer.parseInt(scanResult);
if(n1 == n)
text.setText("Pears Bathing Bar, Pure and Gentle.98% pure Glycerin & Natural Oils. Net weight 75 grams. MRP rupees 105 ");
*/
text.setText(scanResult);
scannerView.stopCamera();
txt=new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
if(status!=TextToSpeech.ERROR)
{
txt.setLanguage(Locale.UK);
}
}
});
String toSpeak=ed1.getText().toString();
Toast.makeText(getApplicationContext(),toSpeak,Toast.LENGTH_SHORT).show();
txt.speak(toSpeak,TextToSpeech.QUEUE_FLUSH,null);
/* public void onPause()
{
if(txt!=null)
{
txt.stop();
txt.shutdown();
}
super.onPause();
}*/
/*AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
scannerView.resumeCameraPreview(SecondActivity.this);
}
});
builder.setNeutralButton("Visit", new DialogInterface.OnClickListener(){
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Intent.ACTION_VIEW , Uri.parse(scanResult));
startActivity(intent);
}
});
builder.setMessage(scanResult);
AlertDialog alert = builder.create();
alert.show();*/
}
}

How to show ProgressDialog after AlertDialog

I am having trouble with an alert dialog that I cannot hide.
when the user press a button I show a dialog that is created with this code :
new AlertDialog.Builder(this)
.setTitle(R.string.enterPassword)
.setView(textEntryView)
.setPositiveButton(R.string.ok,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String password = pwdText.getText().toString();
dialog.dismiss();
processUserAction(password,targetUri);
}
})
.setNegativeButton(R.string.cancel,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
}
})
.
create();
There are some heavy operations performed in the 'processUserAction' method, and inside it I am using an AysncTask that displays a ProgressDialog.
The problem I am having is that the dialog prompting for the password never goes of the screen (I have tried with dismiss(), cancel()).
I guess it stays there until the onClick method is finished.
So, my question is how to close that AlertDialog, so I can show the ProgressDialog?
Another approach I have been trying is to set a DismissListener in the AlertDialog and calling the heavy operations from there, but I have had no luck ( it didn't get called ).
EDIT: Adding AsyncTask code
public class BkgCryptOperations extends AsyncTask<File,Void,Integer>{
#Override
protected Integer doInBackground(File... files) {
if (files!=null && files.length > 0){
File source = files[0];
File target = files[1];
return cryptAction.process(source,password, target);
}
return Constants.RetCodeKO;
}
CryptAction cryptAction;
String password;
ProgressDialog progressDialog;
public BkgCryptOperations (CryptAction cryptAction,String password,ProgressDialog progressDialog){
this.cryptAction=cryptAction;
this.password=password;
this.progressDialog=progressDialog;
}
#Override
protected void onPreExecute() {
if (progressDialog!=null){
progressDialog.show();
}
}
protected void onPostExecute(Integer i) {
if (progressDialog!=null){
progressDialog.dismiss();
}
}
}
Thanks in advance
Here is a excample how I do it:
public void daten_remove_on_click(View button) {
// Nachfragen
if (spinadapter.getCount() > 0) {
AlertDialog Result = new AlertDialog.Builder(this)
.setIcon(R.drawable.icon)
.setTitle(getString(R.string.dialog_data_remove_titel))
.setMessage(getString(R.string.dialog_data_remove_text))
.setNegativeButton(getString(R.string.dialog_no),
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface dialogInterface, int i) {
// Nicht löschen
dialogInterface.cancel();
}
})
.setPositiveButton(getString(R.string.dialog_yes),
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface dialogInterface, int i) {
String _quellenName = myCursor.getString(1);
deleteQuellenRecord(_quellenName);
zuletztGelöscht = _quellenName;
}
}).show();
} else {
// Keine Daten mehr vorhanden
Toast toast = Toast.makeText(Daten.this,
getString(R.string.dialog_data_remove_empty),
Toast.LENGTH_SHORT);
toast.show();
}
}
Here is the code of deleteQuellenRecord:
private void deleteQuellenRecord(String _quellenName) {
String DialogTitel = getString(R.string.daten_delete_titel);
String DialogText = getString(R.string.daten_delete_text);
// Dialogdefinition Prograssbar
dialog = new ProgressDialog(this) {
#Override
public boolean onSearchRequested() {
return false;
}
};
dialog.setCancelable(false);
dialog.setTitle(DialogTitel);
dialog.setIcon(R.drawable.icon);
dialog.setMessage(DialogText);
// set the progress to be horizontal
dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
// reset the bar to the default value of 0
dialog.setProgress(0);
// set the maximum value
dialog.setMax(4);
// display the progressbar
increment = 1;
dialog.show();
// Thread starten
new Thread(new MyDeleteDataThread(_quellenName)) {
#Override
public void run() {
try {
// Datensatz löschen
myDB.execSQL("DELETE ... ');");
progressHandler
.sendMessage(progressHandler.obtainMessage());
myDB.execSQL("DELETE ...);");
// active the update handler
progressHandler
.sendMessage(progressHandler.obtainMessage());
myDB.execSQL("DELETE ...;");
// active the update handler
progressHandler
.sendMessage(progressHandler.obtainMessage());
// Einstellung speichern
try {
settings.edit().putString("LetzteQuelle", "-1")
.commit();
} catch (Exception ex) {
settings.edit().putString("LetzteQuelle", "").commit();
}
} catch (Exception ex) {
// Wait dialog beenden
dialog.dismiss();
Log.e("Glutenfrei Viewer",
"Error in activity MAIN - remove data", ex); // log
// the
// error
}
// Wait dialog beenden
dialog.dismiss();
}
}.start();
this.onCreate(null);
}
Wiht Async Task I do it this way:
private class RunningAlternativSearch extends
AsyncTask<Integer, Integer, Void> {
final ProgressDialog dialog = new ProgressDialog(SearchResult.this) {
#Override
public boolean onSearchRequested() {
return false;
}
};
#Override
protected void onPreExecute() {
alternativeSucheBeendet = false;
String DialogTitel = getString(R.string.daten_wait_titel);
DialogText = getString(R.string.dialog_alternativ_text);
DialogZweiteChance = getString(R.string.dialog_zweite_chance);
DialogDritteChance = getString(R.string.dialog_dritte_chance);
sucheNach = getString(R.string.dialog_suche_nach);
dialog.setCancelable(true);
dialog.setTitle(DialogTitel);
dialog.setIcon(R.drawable.icon);
dialog.setMessage(DialogText);
dialog.setOnDismissListener(new OnDismissListener() {
public void onDismiss(DialogInterface arg0) {
// TODO Auto-generated method stub
cancleBarcodeWorker();
if (alternativeSucheBeendet==false){
// Activity nur beenden wenn die Suche
// nicht beendet wurde, also vom User abgebrochen
Toast toast = Toast.makeText(SearchResult.this, SearchResult.this
.getString(R.string.toast_suche_abgebrochen),
Toast.LENGTH_LONG);
toast.show();
myDB.close();
SearchResult.this.finish();
}
}
});
dialog.show();
}
...
Can you show the code for processUserAction(..)? There is no need to include the dismiss.
I did something very similar and had no problems...
Here's the code:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Export data.\nContinue?")
.setCancelable(false)
.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
String file = getObra().getNome();
d = new ProgressDialog(MenuActivity.this);
d.setTitle("Exporting...");
d.setMessage("please wait...");
d.setIndeterminate(true);
d.setCancelable(false);
d.show();
export(file);
}
})
.setNegativeButton("No",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
In export(file) I open the thread:
private void export(final String file) {
new Thread() {
public void run() {
try {
ExportData ede = new ExportData(
getApplicationContext(), getPmo().getId(),
file);
ede.export();
handlerMessage("Done!!");
} catch (Exception e) {
handlerMessage(e.getMessage());
System.out.println("ERROR!!!" + e.getMessage());
}
}
}.start();
}
In handlerMessage I dismiss the progressDialog and show the final message.
Hope it helps you.
You could create a listener outside of the AlertDialog, to abstract out the logic within the OnClickListener for the positive button. That way, the listener can be notified, and the AlertDialog will be dismissed immediately. Then, whatever processing of the user's input from the AlertDialog can take place independently of the AlertDialog. I'm not sure if this is the best way to accomplish this or not, but it's worked well for me in the past.
As far as I can tell, I don't see any obvious problems with your AsyncTask code.
public interface IPasswordListener {
public void onReceivePassword(String password);
}
IPasswordListener m_passwordListener = new IPasswordListener {
#Override
public void onReceivePassword(String password) {
processUserAction(password,targetUri);
}
}
public void showPasswordDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(R.string.enterPassword);
builder.setView(textEntryView);
builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
m_passwordListener.onReceivePassword(pwdText.getText().toString());
dialog.dismiss();
}
});
builder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.cancel();
}
});
builder.show();
}

Categories

Resources