How can I do this, I searched on StackOverflow, but solution is for iphone, not android.
Here is my chat app: https://play.google.com/store/apps/details?id=com.jimmytrivedi.lapitchat
package com.jimmytrivedi.lapitchat;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.FirebaseException;
import com.google.firebase.FirebaseTooManyRequestsException;
import com.google.firebase.analytics.FirebaseAnalytics;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseAuthInvalidCredentialsException;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.auth.PhoneAuthCredential;
import com.google.firebase.auth.PhoneAuthProvider;
import java.util.concurrent.TimeUnit;
public class PhoneAuthActivity extends AppCompatActivity {
private LinearLayout DialLayout, LockLayout;
private EditText PhoneNumber, code;
private ProgressBar PhoneProgress, CodeProgress;
private Button sendVerification;
private Toolbar PhoneToolbar;
private PhoneAuthProvider.OnVerificationStateChangedCallbacks mCallbacks;
private String number;
private FirebaseAnalytics mFirebaseAnalytics;
private String mVerificationId;
private PhoneAuthProvider.ForceResendingToken mResendToken;
private FirebaseAuth mAuth;
private TextView ErrorView;
private int Verify = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_phone_auth);
DialLayout = findViewById(R.id.DialLayout);
LockLayout = findViewById(R.id.LockLayout);
PhoneNumber = findViewById(R.id.PhoneNumber);
code = findViewById(R.id.code);
PhoneProgress = findViewById(R.id.PhoneProgress);
CodeProgress = findViewById(R.id.CodeProgress);
sendVerification = findViewById(R.id.sendVerification);
PhoneToolbar = findViewById(R.id.PhoneToolbar);
ErrorView = findViewById(R.id.ErrorView);
PhoneProgress.setVisibility(View.INVISIBLE);
CodeProgress.setVisibility(View.INVISIBLE);
sendVerification.setEnabled(false);
LockLayout.setVisibility(View.INVISIBLE);
setSupportActionBar(PhoneToolbar);
getSupportActionBar().setTitle("Welcome to Phone Verification");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
mFirebaseAnalytics = FirebaseAnalytics.getInstance(this);
mAuth = FirebaseAuth.getInstance();
PhoneNumber.addTextChangedListener(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 text = charSequence.toString();
if (!text.isEmpty()) {
sendVerification.setEnabled(true);
}
}
#Override
public void afterTextChanged(Editable editable) {
}
});
sendVerification.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(Verify == 0) {
if (!PhoneNumber.getText().toString().isEmpty()) {
number = PhoneNumber.getText().toString();
PhoneNumber.setEnabled(false);
sendVerification.setEnabled(false);
PhoneProgress.setVisibility(View.VISIBLE);
PhoneAuthProvider.getInstance().verifyPhoneNumber(
number,
60,
TimeUnit.SECONDS,
PhoneAuthActivity.this,
mCallbacks
);
}
} else {
String VerificationCode = code.getText().toString();
sendVerification.setEnabled(false);
CodeProgress.setVisibility(View.VISIBLE);
PhoneAuthCredential credential = PhoneAuthProvider.getCredential(
mVerificationId,VerificationCode);
signInWithPhoneAuthCredential(credential);
}
}
});
mCallbacks = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
#Override
public void onVerificationCompleted(PhoneAuthCredential phoneAuthCredential) {
PhoneProgress.setVisibility(View.INVISIBLE);
signInWithPhoneAuthCredential(phoneAuthCredential);
}
#Override
public void onVerificationFailed(FirebaseException e) {
ErrorView.setText("There was some error in verification");
ErrorView.setVisibility(View.VISIBLE);
if (e instanceof FirebaseAuthInvalidCredentialsException) {
Log.d("wihddiewd", "FirebaseAuthInvalidCredentialsException: " + e);
} else if (e instanceof FirebaseTooManyRequestsException) {
Log.d("wihddiewd", "FirebaseTooManyRequestsException: " + e);
}
}
#Override
public void onCodeSent(String verificationId,
PhoneAuthProvider.ForceResendingToken token) {
Log.d("wihddiewd", "onCodeSent:" + verificationId);
mVerificationId = verificationId;
mResendToken = token;
Verify=1;
PhoneProgress.setVisibility(View.INVISIBLE);
LockLayout.setVisibility(View.VISIBLE);
sendVerification.setEnabled(true);
sendVerification.setText("Verify code");
}
};
}
private void signInWithPhoneAuthCredential(PhoneAuthCredential credential) {
mAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
FirebaseUser user = task.getResult().getUser();
startActivity(new Intent(PhoneAuthActivity.this, MainActivity.class));
finish();
} else {
ErrorView.setText("There was some error in logging in");
ErrorView.setVisibility(View.VISIBLE);
Log.w("wihddiewd", "signInWithCredential:failure", task.getException());
if (task.getException() instanceof FirebaseAuthInvalidCredentialsException) {
}
}
}
});
}
}
I don't know what type of code is necessary and where should I add?
Try this lib:
CountryCodePicker
dependencies {
implementation 'com.hbb20:ccp:2.2.2'
}
In XML
<com.hbb20.CountryCodePicker
android:id="#+id/country_picker"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:gravity="center|center_vertical"
android:includeFontPadding="false"
android:textColor="#color/text_black"
app:ccp_showNameCode="false"
app:ccp_textSize="#dimen/small_text_size" />
In Activity
CountryCodePicker country_picker = findViewById(R.id.country_picker);
String country_code = country_picker.getSelectedCountryCode();
Related
Hi I'm following this video tutorial https://www.youtube.com/watch?v=wQN2eCO-M_Q&t=7717s (the part I suppose create this issue can be found at time 2:01:17)and I managed to make this code work without implementing the notifications, but it only works on the simulator.
When I try to debug it with my phone it gives me the following error
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.chat, PID: 7894
java.lang.RuntimeException: Could not deserialize object. Failed to convert value of type java.lang.Long to Timestamp (found in field 'timestamp')
On others real devices it works properly but on my real me 8 pro it does not
here is some code from my android studio:
ChatModel.java
package com.example.chat.model;
import com.google.firebase.Timestamp;
import java.sql.Time;
import java.util.Date;
public class ChatModel {
String message;
String user_name;
String messageID;
String user_image_url;
String chat_image;
Timestamp timestamp;
public ChatModel() {
}
public ChatModel(String message, String user_name, String messageID, String user_image_url, String chat_image, Timestamp timestamp) {
this.message = message;
this.user_name = user_name;
this.messageID = messageID;
this.user_image_url = user_image_url;
this.chat_image = chat_image;
this.timestamp = timestamp;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getUser_name() {
return user_name;
}
public void setUser_name(String user_name) {
this.user_name = user_name;
}
public String getMessageID() {
return messageID;
}
public void setMessageID(String messageID) {
this.messageID = messageID;
}
public String getUser_image_url() {
return user_image_url;
}
public void setUser_image_url(String user_image_url) {
this.user_image_url = user_image_url;
}
public String getChat_image() {
return chat_image;
}
public void setChat_image(String chat_image) {
this.chat_image = chat_image;
}
public Timestamp getTimestamp() {
return timestamp;
}
public void setTimestamp(Timestamp timestamp) {
this.timestamp = timestamp;
}
}
i have tried to change Timestamp with: long, Long, Date and Number.
But i wouldn't work anyways
MainActivity.java
package com.example.chat;
import static com.example.chat.cords.FirebaseCords.MAIN_CHAT_DATABASE;
import static com.example.chat.cords.FirebaseCords.mAuth;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import androidx.appcompat.widget.Toolbar;
import androidx.core.app.ActivityCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.example.chat.adapter.ChatAdapter;
import com.example.chat.cords.FirebaseCords;
import com.example.chat.model.ChatModel;
import com.example.chat.model.SaveState;
import com.firebase.ui.firestore.FirestoreRecyclerAdapter;
import com.firebase.ui.firestore.FirestoreRecyclerOptions;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.firestore.FieldValue;
import com.google.firebase.firestore.Query;
import com.theartofdev.edmodo.cropper.CropImage;
import com.theartofdev.edmodo.cropper.CropImageView;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Queue;
public class MainActivity extends AppCompatActivity {
#Override
public void onStart() {
super.onStart();
// Check if user is signed in (non-null) and update UI accordingly.
FirebaseUser currentUser = mAuth.getCurrentUser();
if (currentUser == null) {
startActivity(new Intent(this, LoginActivity.class));
finish();
}
chatAdapter.startListening();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.chat_room, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.logout:
mAuth.signOut();
startActivity((new Intent(this, LoginActivity.class)));
break;
}
return super.onOptionsItemSelected(item);
}
EditText chat_box;
RecyclerView chat_list;
ChatAdapter chatAdapter;
Uri imageUri;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
chat_box = findViewById(R.id.chat_box);
chat_list = findViewById(R.id.chat_list);
initChatList();
}
private void initChatList() {
chat_list.setHasFixedSize(true);
chat_list.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, true));
Query query = MAIN_CHAT_DATABASE.orderBy("timestamp", Query.Direction.DESCENDING);
FirestoreRecyclerOptions<ChatModel> option = new FirestoreRecyclerOptions.Builder<ChatModel>()
.setQuery(query, ChatModel.class)
.build();
chatAdapter = new ChatAdapter(option);
chat_list.setAdapter(chatAdapter);
chatAdapter.startListening();
}
public void addMessage(View view) {
String message = chat_box.getText().toString();
FirebaseUser user = mAuth.getCurrentUser();
if (!TextUtils.isEmpty(message)) {
/*Generate messageID using the current date. */
Date today = new Date();
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String messageID = format.format(today);
/*Getting user image from Google account*/
String user_image_url = "";
Uri photoUrl = user.getPhotoUrl();
String originalUrl = "s96-c/photo.jpg";
String resizeImageUrl = "s400-c/photo.jpg";
if (photoUrl!=null) {
String photoPath = photoUrl.toString();
user_image_url = photoPath.replace(originalUrl,resizeImageUrl);
}
HashMap<String, Object> messageObj = new HashMap<>();
messageObj.put("message", message);
messageObj.put("user_name", user.getDisplayName());
messageObj.put("timestamp",FieldValue.serverTimestamp());
messageObj.put("messageID", messageID);
messageObj.put("chat_image","");
messageObj.put("user_image_url", user_image_url);
MAIN_CHAT_DATABASE.document(messageID).set(messageObj).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Toast.makeText(MainActivity.this, "Message send", Toast.LENGTH_SHORT).show();
chat_box.setText("");
} else {
Toast.makeText(MainActivity.this, task.getException().getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
}
}
public void OpenExplorer(View view) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) ==
PackageManager.PERMISSION_GRANTED) {
ChoseImage();
} else {
if(ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.READ_EXTERNAL_STORAGE)) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 20);
} else {
Toast.makeText(this, "Storage Permission Needed", Toast.LENGTH_SHORT).show();
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 20);
}
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions,#NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == 20) {
if (grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, "Permission Granted", Toast.LENGTH_SHORT).show();
ChoseImage();
} else {
Toast.makeText(this, "Permission Denied", Toast.LENGTH_SHORT).show();
}
}
}
private void ChoseImage(){
CropImage.activity()
.setGuidelines(CropImageView.Guidelines.ON)
.start(MainActivity.this);
}
#Override
protected void onActivityResult(int requestCode, int resultCode,#Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
Log.d("TAG", "onActivityResult:"+result);
if (resultCode == RESULT_OK) {
imageUri = result.getUri();
Log.d("TAG", "onActivityResult:"+imageUri);
startActivity(new Intent(MainActivity.this, ImageUploadPreview.class)
.putExtra("image_uri", imageUri.toString()));
} else if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
Toast.makeText(this, result.getError().getMessage(),Toast.LENGTH_SHORT).show();
}
}
}
public void Finish(View view) {
long currentTime = new Date().getTime();
new SaveState(this).setClickTime(currentTime);
finish();
}
}
ChatAdapter.java
package com.example.chat.adapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import com.example.chat.R;
import com.firebase.ui.firestore.FirestoreRecyclerAdapter;
import com.firebase.ui.firestore.FirestoreRecyclerOptions;
import com.example.chat.model.ChatModel;
import org.w3c.dom.Text;
import de.hdodenhof.circleimageview.CircleImageView;
public class ChatAdapter extends FirestoreRecyclerAdapter<ChatModel, ChatAdapter.ChatViewHolder> {
public ChatAdapter (#NonNull FirestoreRecyclerOptions <ChatModel> options) {
super(options);
}
#Override
protected void onBindViewHolder (#NonNull ChatViewHolder chatViewHolder, int i, #NonNull ChatModel chatModel) {
chatViewHolder.message.setText(chatModel.getMessage());
Glide.with(chatViewHolder.user_image.getContext().getApplicationContext())
.load(chatModel.getUser_image_url())
.into(chatViewHolder.user_image);
if(!chatModel.getChat_image().equals("")){
Glide.with(chatViewHolder.chat_image.getContext().getApplicationContext())
.load(chatModel.getChat_image())
.into(chatViewHolder.chat_image);
chatViewHolder.chat_image.setVisibility(View.VISIBLE);
}else{
chatViewHolder.chat_image.setVisibility(View.GONE);
}
}
#NonNull
#Override
public ChatViewHolder onCreateViewHolder (#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.chat_item,parent,false);
return new ChatViewHolder(v);
}
class ChatViewHolder extends RecyclerView.ViewHolder {
TextView message;
CircleImageView user_image;
ImageView chat_image;
public ChatViewHolder(#NonNull View itemView) {
super(itemView);
message = itemView.findViewById(R.id.message);
user_image = itemView.findViewById(R.id.user_image);
chat_image = itemView.findViewById(R.id.chat_image);
}
}
}
Screenshoot of thedatabase structure:
here
I have no idea how to solve that error can someone help me?
If you need any more information comment i will add it as soon as i see the message thanks in advance.
i am working on a freelancing app called frelance. the idea of the app is to connect freelancers with clients that need their services.
and I am trying to retrieve data from the realtime database but it's not working.
ShowActivity Xml
<?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"
tools:context=".ShowActivity">
<androidx.appcompat.widget.SearchView
android:id="#+id/Search"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="5dp"
android:background="#color/black"
android:layout_marginBottom="5dp"
android:hint="Search"/>
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recyclerview"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
ShowActivity Java
Package com.example.frelance0;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.SearchView;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import com.google.firebase.auth.FirebaseAuth;
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.security.PrivateKey;
import java.util.ArrayList;
import java.util.Map;
public class ShowActivity extends AppCompatActivity {
private RecyclerView recyclerView;
SearchView searchView;
FirebaseAuth mAuth=FirebaseAuth.getInstance();
FirebaseAuth.AuthStateListener firebaseAuthListener;
String user_id = mAuth.getCurrentUser().getUid();
DatabaseReference F_Database= FirebaseDatabase.getInstance().getReference().child("Users");
DatabaseReference Current_user_db = FirebaseDatabase.getInstance().getReference().child("Users").child("Freelancers");
private MyAdapter adapter;
private ArrayList<Model> list;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show);
recyclerView = findViewById(R.id.recyclerview);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
list = new ArrayList<>();
adapter = new MyAdapter(this, list);
recyclerView.setAdapter(adapter);
searchView = findViewById(R.id.Search);
//Log.d("user id", user_id);
//Log.d("database",F_Database.toString());
F_Database.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
Log.d("OUTSIDE LOOP", snapshot.getChildren().toString());
for(DataSnapshot dataSnapshot : snapshot.getChildren()){
Log.d("INSIDE LOOP", "MESSAGE");
Model model = dataSnapshot.getValue(Model.class);
list.add(model);
}
adapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
if(searchView != null){
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
search(newText);
return true;
}
});
}
}
private void search(String str){
ArrayList<Model> mylist = new ArrayList<>();
for(Model object: list){
if(object.getEmail().toLowerCase().contains(str.toLowerCase())){
mylist.add(object);
}
}
MyAdapter newAdapter = new MyAdapter(mylist);
recyclerView.setAdapter(newAdapter);
}
}
Adapter Code
package com.example.frelance0;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.example.frelance0.R;
import java.util.ArrayList;
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder>{
ArrayList<Model> mlist;
Context context;
public MyAdapter(Context context, ArrayList<Model> mlist){
this.mlist = mlist;
this.context = context;
}
public MyAdapter(ArrayList<Model> mylist) {
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(context).inflate(R.layout.item, parent, false);
return new MyViewHolder(v);
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, int position) {
Model model = mlist.get(position);
holder.Name.setText(model.getName());
holder.Email.setText(model.getEmail());
holder.JobTitle.setText(model.getJobTitle());
}
#Override
public int getItemCount() {
return mlist.size();
}
public static class MyViewHolder extends RecyclerView.ViewHolder{
TextView Name , Email , JobTitle;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
Name= itemView.findViewById(R.id.Name);
Email= itemView.findViewById(R.id.Email);
JobTitle= itemView.findViewById(R.id.Job);
}
}
}
Model Class
package com.example.frelance0;
public class Model {
String Name , JobTitle , Email;
public void setName(String name) {
Name = name;
}
public void setJobTitle(String jobTitle) {
JobTitle = jobTitle;
}
public void setEmail(String email) {
Email = email;
}
public String getName() {
return Name;
}
public String getJobTitle() {
return JobTitle;
}
public String getEmail() {
return Email;
}
}
and Here is a screenshot of my Realtime Database:
Realtime Database
Realtime Database
Realtime Database
as you can see its nested and i don't know why.
app error recyclerview screenshot
I will also attach the Sign up Code in Case You need it Because i Have a nested database problem:
package com.example.frelance0;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.TextUtils;
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.bumptech.glide.Glide;
import com.example.frelance0.C_Sign_in;
import com.example.frelance0.Client_Profile;
import com.example.frelance0.R;
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.AuthResult;
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.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
public class F_Sign_Up extends AppCompatActivity {
EditText mFirstName , mLastName , mEmail , mPassword , mphone;
EditText insta , behance , website ;
EditText Skill1 , Skill2 , Skill3 , Skill4 , Brief , jobTitle , Software1 , Software2 , Software3 , Software4;
ImageView ProfileImg;
Button register;
TextView mlogin;
ProgressBar progressBar;
String ProfileimgUrl;
FirebaseAuth mAuth;
FirebaseAuth.AuthStateListener firebaseAuthListener;
DatabaseReference F_Database;
Uri resultUri;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_f__sign__up);
//connect Xml
mFirstName= (EditText) findViewById(R.id.FirstName);
mLastName= (EditText) findViewById(R.id.LastName);
mEmail= (EditText) findViewById(R.id.email);
mPassword= (EditText) findViewById(R.id.password);
mphone= (EditText) findViewById(R.id.phone);
register= (Button) findViewById(R.id.signUp);
mlogin = (TextView) findViewById(R.id.logIn);
progressBar= (ProgressBar) findViewById(R.id.progressBar);
Skill1 = (EditText) findViewById(R.id.skill1);
Skill2 = (EditText) findViewById(R.id.skill2);
Skill3 = (EditText) findViewById(R.id.skill3);
Skill4 = (EditText) findViewById(R.id.skill4);
Software1 = (EditText) findViewById(R.id.software1);
Software2 = (EditText) findViewById(R.id.software2);
Software3 = (EditText) findViewById(R.id.software3);
Software4 =(EditText) findViewById(R.id.software4);
jobTitle = (EditText) findViewById(R.id.JobTiTleHint);
Brief = (EditText) findViewById(R.id.Brief);
insta = (EditText) findViewById(R.id.insta);
behance = (EditText) findViewById(R.id.Behance);
website = (EditText) findViewById(R.id.Website);
ProfileImg = findViewById(R.id.ProfilePic);
String img = ProfileImg.toString();
ProfileImg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(intent , 1);
}
});
mAuth =FirebaseAuth.getInstance();
firebaseAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if(user != null) {
Intent intent = new Intent(com.example.frelance0.F_Sign_Up.this, Freelancer_Profile.class);
String P = mphone.getText().toString();
intent.putExtra("Phone",P);
startActivity(intent);
return;
}
}
};
register.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String Email = mEmail.getText().toString().trim();
String Password = mPassword.getText().toString().trim();
mAuth =FirebaseAuth.getInstance();
progressBar.setVisibility(View.VISIBLE);
mAuth.createUserWithEmailAndPassword(Email,Password).addOnCompleteListener(com.example.frelance0.F_Sign_Up.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
// if (task.isSuccessful()){
//Toast.makeText(F_Sign_Up.this, "Sign Up Error", Toast.LENGTH_SHORT).show();
if(TextUtils.isEmpty(Email)){
mEmail.setError("E-mail is Required");
return;
}
if(TextUtils.isEmpty(Password)){
mPassword.setError("Password is Required");
return;
}
if(Password.length() < 6){
mPassword.setError("Password Must Be More Than 6 Char ");
return;
}
if(mAuth.getCurrentUser() != null) {
String user_id = mAuth.getCurrentUser().getUid();
DatabaseReference Current_user_db = FirebaseDatabase.getInstance().getReference().child("Users").child("Freelancers").child(user_id);
Current_user_db.setValue(true);
F_Database =FirebaseDatabase.getInstance().getReference().child("Users").child("Freelancers").child(user_id);
Getinfo();
Saveinfo();
Intent intent = new Intent(com.example.frelance0.F_Sign_Up.this, loading.class);
//Phone Intent
String P = mphone.getText().toString();
intent.putExtra("Phone",P);
startActivity(intent);
String Email = mEmail.getText().toString().trim();
String Password = mPassword.getText().toString().trim();
String FirstName = mFirstName.getText().toString();
String LastName = mLastName.getText().toString();
String FullName = mFirstName.getText().toString() + " " + mLastName.getText().toString();
String PhoneNum= mphone.getText().toString();
String Fsoftware= Software1.getText().toString();
String ssoftware= Software2.getText().toString();
String tsoftware= Software3.getText().toString();
String Ffsoftware= Software4.getText().toString();
String Fskill= Skill1.getText().toString();
String sskill= Skill2.getText().toString();
String tskill= Skill3.getText().toString();
String Ffskill= Skill4.getText().toString();
String JB= jobTitle.getText().toString();
String B= Brief.getText().toString();
String Be = behance.getText().toString();
String instag = insta.getText().toString();
String web = website.getText().toString();
Users user = new Users(FullName,FirstName,LastName,Email,Fskill,sskill,tskill,Ffskill,Fsoftware,ssoftware,tsoftware,Ffsoftware,web,instag,Be,JB,Integer.parseInt(PhoneNum));
F_Database.child("Users").child("Freelancers").push().setValue(user);
}
}
});
}
});
}
#Override
protected void onStart() {
super.onStart();
mAuth.addAuthStateListener(firebaseAuthListener);
}
#Override
protected void onStop() {
super.onStop();
mAuth.removeAuthStateListener(firebaseAuthListener);
}
public void Saveinfo(){
String Email = mEmail.getText().toString().trim();
String Password = mPassword.getText().toString().trim();
String FirstName = mFirstName.getText().toString();
String LastName = mLastName.getText().toString();
String FullName = mFirstName.getText().toString() + " " + mLastName.getText().toString();
String PhoneNum= mphone.getText().toString();
String Fsoftware= Software1.getText().toString();
String ssoftware= Software2.getText().toString();
String tsoftware= Software3.getText().toString();
String Ffsoftware= Software4.getText().toString();
String Fskill= Skill1.getText().toString();
String sskill= Skill2.getText().toString();
String tskill= Skill3.getText().toString();
String Ffskill= Skill4.getText().toString();
String JB= jobTitle.getText().toString();
String B= Brief.getText().toString();
String Be = behance.getText().toString();
String instag = insta.getText().toString();
String web = website.getText().toString();
Map<String,Object> Map = new HashMap<>();
Map userinfo = new HashMap();
userinfo.put("First Name",FirstName);
userinfo.put("Last Name",LastName);
userinfo.put("Full Name",FullName);
userinfo.put("Email",Email);
userinfo.put("Phone Number" , PhoneNum);
//Skills
userinfo.put("Skill 1",Fskill);
userinfo.put("Skill 2",sskill);
userinfo.put("Skill 3",tskill);
userinfo.put("Skill 4",Ffskill);
//Softwares
userinfo.put("Software 1",Fsoftware);
userinfo.put("Software 2",ssoftware);
userinfo.put("Software 3",tsoftware);
userinfo.put("Software 4",Ffsoftware);
//other
userinfo.put("Brief",B);
userinfo.put("Job Title",JB);
userinfo.put("Website",web);
userinfo.put("Instagram",instag);
userinfo.put("Behance",Be);
String user_id = mAuth.getCurrentUser().getUid();
F_Database.updateChildren(userinfo);
if(resultUri!= null){
StorageReference FilePath = FirebaseStorage.getInstance().getReference().child("Profile images").child(user_id);
Bitmap bitmap = null;
try {
bitmap = MediaStore.Images.Media.getBitmap(getApplication().getContentResolver(), resultUri);
} catch (IOException e) {
e.printStackTrace();
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG,20,baos);
byte[] data = baos.toByteArray();
UploadTask uploadTask = FilePath.putBytes(data);
uploadTask.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
finish();
return;
}
});
uploadTask.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Task<Uri> downloadUrl = taskSnapshot.getStorage().getDownloadUrl();
Map newImg = new HashMap();
newImg.put("ProfileImageUrl", downloadUrl.toString());
F_Database.updateChildren(newImg);
finish();
return;
}
});
}else {
finish();
}
}
public void Getinfo(){
F_Database.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot datasnapshot) {
if(datasnapshot.exists() && datasnapshot.getChildrenCount()>0){
String Email = mEmail.getText().toString().trim();
String Password = mPassword.getText().toString().trim();
String FirstName = mFirstName.getText().toString();
String LastName = mLastName.getText().toString();
// String FullName = mFirstName.getText().toString() + " " + mLastName.getText().toString();
String PhoneNum= mphone.getText().toString();
String Fsoftware= Software1.getText().toString();
String ssoftware= Software2.getText().toString();
String tsoftware= Software3.getText().toString();
String Ffsoftware= Software4.getText().toString();
String Fskill= Skill1.getText().toString();
String sskill= Skill2.getText().toString();
String tskill= Skill3.getText().toString();
String Ffskill= Skill4.getText().toString();
String JB= jobTitle.getText().toString();
String B= Brief.getText().toString();
String Be = behance.getText().toString();
String instag = insta.getText().toString();
String web = website.getText().toString();
Map<String,Object> Map = new HashMap<>();
if(Map.get("First Name")!=null){
FirstName = Map.get("First Name").toString();
mFirstName.setText(FirstName);
}
if(Map.get("Email")!=null){
Email = Map.get("Email").toString();
mEmail.setText(Email);
}
if(Map.get("Password")!=null){
Password = Map.get("Password").toString();
mPassword.setText(Password);
}
if(Map.get("LastName")!=null){
LastName = Map.get("LastName").toString();
mLastName.setText(LastName);
}
if(Map.get("PhoneNum")!=null){
PhoneNum = Map.get("PhoneNum").toString();
mphone.setText(PhoneNum);
}
if(Map.get("Fsoftware")!=null){
Fsoftware = Map.get("Fsoftware").toString();
Software1.setText(Fsoftware);
}
if(Map.get("ssoftware")!=null){
ssoftware = Map.get("ssoftware").toString();
Software2.setText(ssoftware);
}
if(Map.get("tsoftware")!=null){
tsoftware= Map.get("ssoftware").toString();
Software3.setText(tsoftware);
}
if(Map.get("Ffsoftware")!=null){
Ffsoftware = Map.get("Ffsoftware").toString();
Software4.setText(Ffsoftware);
}
if(Map.get("Fskill")!=null){
Fskill = Map.get("First Name").toString();
Skill1.setText(Fskill);
}
if(Map.get("sskill")!=null){
sskill = Map.get("First Name").toString();
Skill2.setText(sskill);
}
if(Map.get("tskill")!=null){
tskill = Map.get("tskill").toString();
Skill3.setText(tskill);
}
if(Map.get("Ffskill")!=null){
Ffskill= Map.get("Ffskill").toString();
Skill4.setText(Ffskill);
}
if(Map.get("JB")!=null){
JB = Map.get("JB").toString();
jobTitle.setText(JB);
}
if(Map.get("B")!=null){
B = Map.get("B").toString();
Brief.setText(B);
}
if(Map.get("Be")!=null){
Be = Map.get("Be").toString();
behance.setText(Be);
}
if(Map.get("instag")!=null){
instag = Map.get("instag").toString();
insta.setText(instag);
}
if(Map.get("web")!=null){
web = Map.get("web").toString();
website.setText(web);
}
if(Map.get("ProfileImageUrl")!=null){
ProfileimgUrl = Map.get("ProfileImageUrl").toString();
Glide.with(getApplication()).load(ProfileimgUrl).into(ProfileImg);
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
public void onClick(View view){
Intent intent = new Intent(com.example.frelance0.F_Sign_Up.this, Freelancer_Log_in.class);
startActivity(intent);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == 1 && requestCode == Activity.RESULT_OK);
final Uri imgUri = data.getData();
resultUri = imgUri;
ProfileImg.setImageURI(imgUri);
}
}
I am a beginner at coding in Java. I am creating a notes app with lots of other features. And one of the features are, storing the user's bank card details in a RecyclerView. I did this by making an SQLite CRUD. All of the Create, Read, Update and Delete works. And I protected this page with a Pattern lock.
And when we are in the Input Pattern page, we can see a clickable text called Click HERE if you forgot your pattern, That works. And when you click on that clickable text, the app shows an Alert Dialog, titled are you sure? and the message is If you change your pattern, all your data will be deleted then there are two buttons Yes and No. No does nothing, it just cancel the forgot pattern thing. But the problem is with the Yes button.
When we click it, It should delete all bank cards or delete all data. Please suggest a way to delete all data from the SQLite Database. I tried lots of ways to do this.
HERE IS MY INPUT PATTERN ACTIVITY
package com.ixidev.simplenotepad;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.WebChromeClient;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.ixidev.simplenotepad.model.Note;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
public class ProgramActivity extends AppCompatActivity {
FloatingActionButton fab, fabChangePattern, fabexit;
RecyclerView mRecyclerViewBC;
CardsDatabaseHelper cardsDatabaseHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_program);
mRecyclerViewBC = findViewById(R.id.recyclerViewBC);
cardsDatabaseHelper = new CardsDatabaseHelper(this);
showRecord();
fabexit = findViewById(R.id.exitProgram);
fab = findViewById(R.id.addFabButtonBC);
fabChangePattern = findViewById(R.id.ChangePattern);
fabexit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(ProgramActivity.this, MainActivity.class);
startActivity(intent);
}
});
fabChangePattern.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(ProgramActivity.this, CreatePasswordActivity.class);
startActivity(intent);
}
});
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(ProgramActivity.this, AddBankCardActivity.class);
intent.putExtra("BCeditMode", false);
startActivity(intent);
}
});
}
private void showRecord() {
CardAdapter cardAdapter = new CardAdapter(ProgramActivity.this, cardsDatabaseHelper.getAllBCdata(ConstantsCard.BC_C_ADD_TIMESTAMP + " DESC"));
mRecyclerViewBC.setAdapter(cardAdapter);
}
#Override
protected void onResume() {
super.onResume();
showRecord();
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == event.KEYCODE_BACK) {
moveTaskToBack(true);
}
return super.onKeyDown(keyCode, event);
}
}
HERE IS MY DATABASE HELPER CLASS
package com.ixidev.simplenotepad;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.widget.Toast;
import androidx.annotation.Nullable;
import java.util.ArrayList;
public class CardsDatabaseHelper extends SQLiteOpenHelper {
public CardsDatabaseHelper(#Nullable Context context) {
super(context, ConstantsCard.BC_DB_NAME, null, ConstantsCard.BC_DB_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(ConstantsCard.BC_CREATE_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + ConstantsCard.BC_TABLE_NAME);
onCreate(db);
}
public long insertInfo(String number, String cvv, String expiry, String image, String addTimestamp, String updateTimestamp) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(ConstantsCard.BC_C_NUMBER, number);
values.put(ConstantsCard.BC_C_CVV, cvv);
values.put(ConstantsCard.BC_C_EXPIRY, expiry);
values.put(ConstantsCard.BC_C_IMAGE, image);
values.put(ConstantsCard.BC_C_ADD_TIMESTAMP, addTimestamp);
values.put(ConstantsCard.BC_C_UPDATE_TIMESTAMP, updateTimestamp);
long id = db.insert(ConstantsCard.BC_TABLE_NAME, null, values);
db.close();
return id;
}
public void updateInfo(String BCid, String number, String cvv, String expiry, String image, String addTimestamp, String updateTimestamp) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(ConstantsCard.BC_C_NUMBER, number);
values.put(ConstantsCard.BC_C_CVV, cvv);
values.put(ConstantsCard.BC_C_EXPIRY, expiry);
values.put(ConstantsCard.BC_C_IMAGE, image);
values.put(ConstantsCard.BC_C_ADD_TIMESTAMP, addTimestamp);
values.put(ConstantsCard.BC_C_UPDATE_TIMESTAMP, updateTimestamp);
db.update(ConstantsCard.BC_TABLE_NAME, values, ConstantsCard.BC_C_ID + " = ?", new String[]{BCid});
db.close();
}
public void deleteInfo(String BCid) {
SQLiteDatabase db = getWritableDatabase();
db.delete(ConstantsCard.BC_TABLE_NAME, ConstantsCard.BC_C_ID + " = ? ", new String[]{BCid});
db.close();
}
public void testDelete() {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(ConstantsCard.BC_TABLE_NAME,null,null);
db.execSQL("delete from "+ ConstantsCard.BC_TABLE_NAME);
db.execSQL("TRUNCATE table " + ConstantsCard.BC_TABLE_NAME);
db.close();
}
public void delete(String BCid)
{
String[] args={BCid};
getWritableDatabase().delete("texts", "_ID=?", args);
}
public ArrayList<CardModel> getAllBCdata(String orderByBC) {
ArrayList<CardModel> ArrayListCard = new ArrayList<>();
String selectQuery = "SELECT * FROM " + ConstantsCard.BC_TABLE_NAME + " ORDER BY " + orderByBC;
SQLiteDatabase BCdb = this.getWritableDatabase();
Cursor CardCursor = BCdb.rawQuery(selectQuery, null);
if (CardCursor.moveToNext()) {
do {
CardModel cardModel = new CardModel(
""+CardCursor.getInt(CardCursor.getColumnIndex(ConstantsCard.BC_C_ID)),
""+CardCursor.getString(CardCursor.getColumnIndex(ConstantsCard.BC_C_IMAGE)),
""+CardCursor.getString(CardCursor.getColumnIndex(ConstantsCard.BC_C_NUMBER)),
""+CardCursor.getString(CardCursor.getColumnIndex(ConstantsCard.BC_C_CVV)),
""+CardCursor.getString(CardCursor.getColumnIndex(ConstantsCard.BC_C_EXPIRY)),
""+CardCursor.getString(CardCursor.getColumnIndex(ConstantsCard.BC_C_ADD_TIMESTAMP)),
""+CardCursor.getString(CardCursor.getColumnIndex(ConstantsCard.BC_C_UPDATE_TIMESTAMP))
);
ArrayListCard.add(cardModel);
} while (CardCursor.moveToNext());
}
BCdb.close();
return ArrayListCard;
}
}
HERE IS MY ADAPTER CLASS
package com.ixidev.simplenotepad;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.arch.core.executor.TaskExecutor;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class CardAdapter extends RecyclerView.Adapter<CardAdapter.Holder> {
private Context CardContext;
private ArrayList<CardModel> CardArrayList;
CardsDatabaseHelper cardsDatabaseHelper;
public CardAdapter(Context cardContext, ArrayList<CardModel> cardArrayList) {
CardContext = cardContext;
CardArrayList = cardArrayList;
cardsDatabaseHelper = new CardsDatabaseHelper(CardContext);
}
#NonNull
#Override
public Holder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View viewBC = LayoutInflater.from(CardContext).inflate(R.layout.bc_row, parent, false);
return new Holder(viewBC);
}
#Override
public void onBindViewHolder(#NonNull Holder holder, int position) {
CardModel cardModel = CardArrayList.get(position);
final String BCid = cardModel.getBCid();
final String BCimage = cardModel.getImageBC();
final String BCnumber = cardModel.getNumber();
final String BCcvv = cardModel.getCvv();
final String BCexpiry = cardModel.getExpiryBC();
final String addTimeStampBC = cardModel.getAddTimeStampBC();
final String updateTimeStampBC = cardModel.getUpdateTimeStampBC();
holder.profileIvBC.setImageURI(Uri.parse(BCimage));
holder.number.setText(BCnumber);
holder.cvv.setText(BCcvv);
holder.expiryBC.setText(BCexpiry);
holder.editButtonBC.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
editDialog(
""+position,
""+BCid,
""+BCnumber,
""+BCcvv,
""+BCexpiry,
""+BCimage,
""+addTimeStampBC,
""+updateTimeStampBC
);
}
});
holder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
deleteDialog(
""+BCid
);
return false;
}
});
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(CardContext, "Clicked", Toast.LENGTH_SHORT).show();
cardsDatabaseHelper.testDelete();
cardsDatabaseHelper.delete(BCid);
}
});
}
private void deleteDialog(final String BCid) {
AlertDialog.Builder builderBC = new AlertDialog.Builder(CardContext);
builderBC.setTitle("Delete?");
builderBC.setMessage("Are you sure you want to delete this document?");
builderBC.setCancelable(false);
builderBC.setIcon(R.drawable.ic_action_delete);
builderBC.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
cardsDatabaseHelper.deleteInfo(BCid);
((ProgramActivity)CardContext).onResume();
Toast.makeText(CardContext, "Successfully deleted!", Toast.LENGTH_SHORT).show();
}
});
builderBC.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builderBC.create().show();
}
private void editDialog(String position, String BCid, String BCnumber, String BCcvv, String BCexpiry, String BCimage, String addTimeStampBC, String updateTimeStampBC) {
AlertDialog.Builder BCbuilder = new AlertDialog.Builder(CardContext);
BCbuilder.setTitle("Edit?");
BCbuilder.setMessage("Are you sure you want to edit this Bank Card?");
BCbuilder.setCancelable(false);
BCbuilder.setIcon(R.drawable.ic_action_edit);
BCbuilder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(CardContext, EditBankCardActivity.class);
intent.putExtra("BCID", BCid);
intent.putExtra("NUMBER", BCnumber);
intent.putExtra("CVV", BCcvv);
intent.putExtra("EXPIRYBC", BCexpiry);
intent.putExtra("IMAGE", BCimage);
intent.putExtra("BC_ADD_TIMESTAMP", addTimeStampBC);
intent.putExtra("BC_UPDATE_TIMESTAMP", updateTimeStampBC);
intent.putExtra("BCeditMode", true);
CardContext.startActivity(intent);
}
});
BCbuilder.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
BCbuilder.create().show();
}
#Override
public int getItemCount() {
return CardArrayList.size();
}
class Holder extends RecyclerView.ViewHolder {
ImageView profileIvBC;
TextView number, cvv, expiryBC;
ImageButton editButtonBC;
public Holder(#NonNull View itemView) {
super(itemView);
profileIvBC = itemView.findViewById(R.id.profileIvBC);
number = itemView.findViewById(R.id.number);
cvv = itemView.findViewById(R.id.cvv);
expiryBC = itemView.findViewById(R.id.expiry);
editButtonBC = itemView.findViewById(R.id.editBtnBC);
}
}
}
HERE IS MY MODEL CLASS
package com.ixidev.simplenotepad;
public class CardModel {
String BCid, imageBC, number, cvv, expiryBC, addTimeStampBC, updateTimeStampBC;
public CardModel(String BCid, String imageBC, String number, String cvv, String expiryBC, String addTimeStampBC, String updateTimeStampBC) {
this.BCid = BCid;
this.imageBC = imageBC;
this.number = number;
this.cvv = cvv;
this.expiryBC = expiryBC;
this.addTimeStampBC = addTimeStampBC;
this.updateTimeStampBC = updateTimeStampBC;
}
public String getBCid() {
return BCid;
}
public void setBCid(String BCid) {
this.BCid = BCid;
}
public String getImageBC() {
return imageBC;
}
public void setImageBC(String imageBC) {
this.imageBC = imageBC;
}
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
public String getCvv() {
return cvv;
}
public void setCvv(String cvv) {
this.cvv = cvv;
}
public String getExpiryBC() {
return expiryBC;
}
public void setExpiryBC(String expiryBC) {
this.expiryBC = expiryBC;
}
public String getAddTimeStampBC() {
return addTimeStampBC;
}
public void setAddTimeStampBC(String addTimeStampBC) {
this.addTimeStampBC = addTimeStampBC;
}
public String getUpdateTimeStampBC() {
return updateTimeStampBC;
}
public void setUpdateTimeStampBC(String updateTimeStampBC) {
this.updateTimeStampBC = updateTimeStampBC;
}
}
And here is my CONSTANTS class
package com.ixidev.simplenotepad;
public class ConstantsCard {
public static final String BC_DB_NAME = "MY_BANK_CARDS";
public static final int BC_DB_VERSION = 1;
public static final String BC_TABLE_NAME = "MY_BANK_CARDS_TABLE";
public static final String BC_C_ID = "BC_ID";
public static final String BC_C_NUMBER = "BC_NUMBER";
public static final String BC_C_CVV = "BC_CVV";
public static final String BC_C_EXPIRY = "BC_EXPIRY";
public static final String BC_C_IMAGE = "BC_IMAGE";
public static final String BC_C_ADD_TIMESTAMP = "BC_ADD_TIMESTAMP";
public static final String BC_C_UPDATE_TIMESTAMP = "BC_UPDATE_TIMESTAMP";
public static final String BC_CREATE_TABLE = "CREATE TABLE " + BC_TABLE_NAME + "("
+ BC_C_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ BC_C_NUMBER + " TEXT,"
+ BC_C_CVV + " TEXT,"
+ BC_C_EXPIRY + " TEXT,"
+ BC_C_IMAGE + " TEXT,"
+ BC_C_ADD_TIMESTAMP + " TEXT,"
+ BC_C_UPDATE_TIMESTAMP + " TEXT"
+ ");";
}
I am not getting desired output .
My code prints the whole string afterwards as a whole rather than printing in parts that are spoken by the android text to speech reader.
please help me clarify my error. And please reply soon or anyone have any github repo regarding it then please give the link.I am feeling very demotivated with such situations occuring too often to me in android studio.
here is my MainActivity.java code from android studio....
package com.example.ttsreader;
import androidx.appcompat.app.AppCompatActivity;
import android.app.Activity;
import android.graphics.Color;
import android.os.Handler;
import android.os.Message;
import android.speech.tts.TextToSpeech;
import android.os.Bundle;
import android.text.Html;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.text.DateFormat;
import java.util.Calendar;
import java.util.Locale;
import static android.widget.Toast.*;
public class MainActivity extends AppCompatActivity {
private TextToSpeech textToSpeech;
private Button btn;
private EditText editText;
private TextView txtView;
String x="";
String sss;
private static final String TAG = "UpdateUI";
private Handler handler = new Handler() {
#Override
public void handleMessage(Message msg) {
Bundle b = msg.getData();
String key = b.getString("timeKey");
tv.setText(key);
}
};
private Runnable separateThread = new Runnable() {
#Override
public void run() {
updateUI();
}
};
private TextView tv;
private String getTime() {
Calendar calendar = Calendar.getInstance();
DateFormat formatTime = DateFormat.getTimeInstance();
return formatTime.format(calendar.getTime());
}
private void updateUI(){
long endTime = System.currentTimeMillis() + 5 * 1000;
txtView.setText(x);
}
String ss;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = (Button) findViewById(R.id.btn);
txtView=(TextView)findViewById(R.id.textView3);
editText = (EditText) findViewById(R.id.et);
textToSpeech = new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
int ttsLang = textToSpeech.setLanguage(Locale.UK);
if (ttsLang == TextToSpeech.LANG_MISSING_DATA
|| ttsLang == TextToSpeech.LANG_NOT_SUPPORTED) {
Log.e("TTS", "The Language is not supported!");
} else {
Log.i("TTS", "Language Supported.");
}
Log.i("TTS", "Initialization success.");
} else {
makeText(getApplicationContext(), "TTS Initialization failed!", LENGTH_SHORT).show();
}
}
});
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
String data = editText.getText().toString();
try{
String arr[]=data.split("\\s");
for(final String s:arr)
{
x+=" ";
x+=s;
sss=s;
Thread t = new Thread(separateThread);
int speechStatus = textToSpeech.speak(sss, TextToSpeech.QUEUE_FLUSH, null);
if (speechStatus == TextToSpeech.ERROR) {
}
t.start();
Thread.sleep(300);
/* txtView.setText(x);
int speechStatus = textToSpeech.speak(s, TextToSpeech.QUEUE_ADD, null);
if (speechStatus == TextToSpeech.ERROR) {
}*/
}
}
catch(Exception e)
{
}
}
});
}
/* public void dospeak(final String s,String data)
{
String newString = data.replaceAll(s, "<font color='red'>"+s+"</font>");
ss=newString;
//extView.setBackgroundColor(Color.BLUE);
}
*/
}
I'd like to check GPS both when the app is started and when the refresh button is hit, and use those data points, in the form of mLatitude and mLongitude to call the weather api. Eventually I'm going to geocode the city but right now for debugging purposes I'm outputting the GPS coordinates to the locationLabel textview.
my MainActivity.java:
package com.example.paxie.stormy.ui;
import android.Manifest;
import android.annotation.TargetApi;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.example.paxie.stormy.GPS_Service;
import com.example.paxie.stormy.R;
import com.example.paxie.stormy.weather.Current;
import com.example.paxie.stormy.weather.Day;
import com.example.paxie.stormy.weather.Forecast;
import com.example.paxie.stormy.weather.Hour;
import com.squareup.okhttp.Call;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
public class MainActivity extends AppCompatActivity {
public static final String TAG = MainActivity.class.getSimpleName();
public static final String DAILY_FORECAST = "DAILY_FORECAST";
public static final String HOURLY_FORECAST = "HOURLY_FORECAST";
private Forecast mForecast;
private double mLatitude;
private double mLongitude;
private BroadcastReceiver broadcastReceiver;
#Bind(R.id.timeLabel)
TextView mTimeLabel;
#Bind(R.id.temperatureLabel)
TextView mTemperatureLabel;
#Bind(R.id.humidityValue)
TextView mHumidityValue;
#Bind(R.id.precipValue)
TextView mPrecipValue;
#Bind(R.id.summaryLabel)
TextView mSummaryLabel;
#Bind(R.id.iconImageView)
ImageView mIconImageView;
#Bind(R.id.refreshImageView)
ImageView mRefreshImageView;
#Bind(R.id.progressBar)
ProgressBar mProgressBar;
#Bind(R.id.locationLabel)
TextView mLocationlabel;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
mProgressBar.setVisibility(View.INVISIBLE);
mRefreshImageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getForecast();
}
});
getForecast();
Log.d(TAG, "Main UI code is running!");
}
private void getForecast() {
if(!runtime_permissions())
checkGPS();
String apiKey = "1621390f8c36997cb1904914b726df52";
String forecastUrl = "https://api.forecast.io/forecast/" + apiKey +
"/" + mLatitude + "," + mLongitude;
if (isNetworkAvailable()) {
toggleRefresh();
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(forecastUrl)
.build();
Call call = client.newCall(request);
call.enqueue(new Callback() {
#Override
public void onFailure(Request request, IOException e) {
runOnUiThread(new Runnable() {
#Override
public void run() {
toggleRefresh();
}
});
alertUserAboutError();
}
#Override
public void onResponse(Response response) throws IOException {
runOnUiThread(new Runnable() {
#Override
public void run() {
toggleRefresh();
}
});
try {
String jsonData = response.body().string();
Log.v(TAG, jsonData);
if (response.isSuccessful()) {
mForecast = parseForecastDetails(jsonData);
runOnUiThread(new Runnable() {
#Override
public void run() {
updateDisplay();
}
});
} else {
alertUserAboutError();
}
} catch (IOException e)
{
Log.e(TAG, "Exception caught: ", e);
} catch (JSONException e) {
e.printStackTrace();
}
}
});
} else {
Toast.makeText(this, "Network is currently unavailable!", Toast.LENGTH_LONG).show();
}
}
private void toggleRefresh() {
if (mProgressBar.getVisibility() == View.INVISIBLE) {
mProgressBar.setVisibility(View.VISIBLE);
mRefreshImageView.setVisibility(View.INVISIBLE);
} else {
mProgressBar.setVisibility(View.INVISIBLE);
mRefreshImageView.setVisibility(View.VISIBLE);
}
}
private void updateDisplay() {
mLocationlabel.setText(mLatitude + " " + mLongitude);
Current current = mForecast.getCurrent();
mTemperatureLabel.setText(current.getTemperature() + "");
mTimeLabel.setText("At " + current.getFormattedTime() + " it will be:");
mHumidityValue.setText(current.getHumidity() + "");
mPrecipValue.setText(current.getPrecipChance() + "%");
mSummaryLabel.setText(current.getSummary());
Drawable drawable = ContextCompat.getDrawable(this, current.getIconId());
mIconImageView.setImageDrawable(drawable);
}
private Forecast parseForecastDetails(String jsonData) throws JSONException {
Forecast forecast = new Forecast();
forecast.setCurrent(getCurrentDetails(jsonData));
forecast.setHourlyForecast(getHourlyForecast(jsonData));
forecast.setDailyForecast(getDailyForecast(jsonData));
return forecast;
}
private Day[] getDailyForecast(String jsonData) throws JSONException {
JSONObject forecast = new JSONObject(jsonData);
String timezone = forecast.getString("timezone");
JSONObject daily = forecast.getJSONObject("daily");
JSONArray data = daily.getJSONArray("data");
Day[] days = new Day[data.length()];
for (int i = 0; i < data.length(); i++) {
JSONObject jsonDay = data.getJSONObject(i);
Day day = new Day();
day.setSummary(jsonDay.getString("summary"));
day.setIcon(jsonDay.getString("icon"));
day.setTemperatureMax(jsonDay.getDouble("temperatureMax"));
day.setTime(jsonDay.getLong("time"));
day.setTimeZone(timezone);
days[i] = day;
}
return days;
}
private Hour[] getHourlyForecast(String jsonData) throws JSONException {
JSONObject forecast = new JSONObject(jsonData);
String timezone = forecast.getString("timezone");
JSONObject hourly = forecast.getJSONObject("hourly");
JSONArray data = hourly.getJSONArray("data");
Hour[] hours = new Hour[data.length()];
for (int i = 0; i < data.length(); i++) {
JSONObject jsonHour = data.getJSONObject(i);
Hour hour = new Hour();
hour.setSummary(jsonHour.getString("summary"));
hour.setTemperature(jsonHour.getDouble("temperature"));
hour.setIcon(jsonHour.getString("icon"));
hour.setTime(jsonHour.getLong("time"));
hour.setTimeZone(timezone);
hours[i] = hour;
}
return hours;
}
private Current getCurrentDetails(String jsonData) throws JSONException {
JSONObject forecast = new JSONObject(jsonData);
String timezone = forecast.getString("timezone");
Log.i(TAG, "From JSON: " + timezone);
JSONObject currently = forecast.getJSONObject("currently");
Current current = new Current();
current.setHumidity(currently.getDouble("humidity"));
current.setTime(currently.getLong("time"));
current.setIcon(currently.getString("icon"));
current.setPrecipChance(currently.getDouble("precipProbability"));
current.setSummary(currently.getString("summary"));
current.setTemperature(currently.getDouble("temperature"));
current.setTimeZone(timezone);
Log.d(TAG, current.getFormattedTime());
return current;
}
private boolean isNetworkAvailable() {
ConnectivityManager manager = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = manager.getActiveNetworkInfo();
boolean isAvailable = false;
if (networkInfo != null && networkInfo.isConnected()) {
isAvailable = true;
}
return isAvailable;
}
private void alertUserAboutError() {
AlertDialogFragment dialog = new AlertDialogFragment();
dialog.show(getFragmentManager(), "error_dialog");
}
#OnClick(R.id.dailyButton)
public void startDailyActivity(View view) {
Intent intent = new Intent(this, DailyForecastActivity.class);
intent.putExtra(DAILY_FORECAST, mForecast.getDailyForecast());
startActivity(intent);
}
#OnClick(R.id.hourlyButton)
public void startHourlyActivity(View view) {
Intent intent = new Intent(this, HourlyForecastActivity.class);
intent.putExtra(HOURLY_FORECAST, mForecast.getHourlyForecast());
startActivity(intent);
}
private void checkGPS() {
if (broadcastReceiver == null) {
broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
mLatitude = (double) intent.getExtras().get("latitude");
mLongitude = (double) intent.getExtras().get("longitude");
}
};
}
registerReceiver(broadcastReceiver, new IntentFilter("location_update"));
}
private boolean runtime_permissions() {
if (Build.VERSION.SDK_INT >= 23 && ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, 100);
return true;
}
return false;
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == 100) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_GRANTED) {
getForecast();
} else {
runtime_permissions();
}
}
}
#Override
protected void onResume() {
super.onResume();
checkGPS();
}
}
my GPSservice.java:
package com.example.paxie.stormy;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.support.annotation.Nullable;
/**
* Created by paxie on 10/27/16.
*/
public class GPS_Service extends Service {
private LocationListener listener;
private LocationManager locationManager;
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
listener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
Intent i = new Intent("location_update");
i.putExtra("coordinates",location.getLongitude()+" "+location.getLatitude());
i.putExtra("longitude", location.getLongitude());
i.putExtra("latitude", location.getLatitude());
sendBroadcast(i);
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
Intent i = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);
}
};
locationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
//noinspection MissingPermission
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,3000,0,listener);
}
#Override
public void onDestroy() {
super.onDestroy();
if(locationManager != null){
//noinspection MissingPermission
locationManager.removeUpdates(listener);
}
}
}
Here are two things you can try:
1. Please ensure you have included the ACCESS_FINE_LOCATION and ACCESS_COARSE_LOCATION permissions in your manifest. If your app targets Android API 23 and above, you will need to include runtime permission handling.
2. Instead of having a LocationListener object as a class member, you should have your Service implement it as an interface and implement its onLocationChanged() method.
Apart from this, you really should consider using the location APIs' in Google Play Services, rather than those in AOSP (i.e. android.location).
See Making Your App Location-Aware