update instant message in conversation activity - Android - android-studio

I am building an instant messaging feature in my app using retrofit 2.0,php and mysql. But i do not know how to show and update the messages received and send in the recyclerview.
conversation Activity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_conversation);
dp=findViewById(R.id.conversationUser);
back=findViewById(R.id.goBackFromCoversation);
name=findViewById(R.id.conversationUserName);
activeStatus=findViewById(R.id.conversationUserSeen);
shareTitle=findViewById(R.id.conversationStatusTitle);
typeMessage=findViewById(R.id.typeMessage);
attach=findViewById(R.id.attachFiles);
send=findViewById(R.id.sendMessage);
recyclerView=findViewById(R.id.conversationRv);
toolbar=findViewById(R.id.converationToolbar);
setSupportActionBar(toolbar);
if (SharedPrefManager.getInstance(this).contains("keyid")) {
id = SharedPrefManager.getInstance(this).getUser().getId();
Toast.makeText(this, "user id is " + id, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "no id found", Toast.LENGTH_SHORT).show();
}
getUserId= getIntent().getIntExtra("userId",0);
getUserName=getIntent().getStringExtra("userName");
getUserDp=getIntent().getStringExtra("dpUrl");
chatType=getIntent().getIntExtra("chatType",0);
if(getUserDp==null){
Toast.makeText(getApplicationContext(),"user dp is null, value is "+getUserDp,Toast.LENGTH_SHORT).show();
}else {
loadDp(getUserDp);
}
name.setText(getUserName);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(this);
((LinearLayoutManager) mLayoutManager).setOrientation(LinearLayoutManager.VERTICAL);
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setNestedScrollingEnabled(true);
fetchConversation(id,getUserId);
cla=new ConversationAdapter(this,conversation);
recyclerView.setAdapter(cla);
back.setOnClickListener(this);
name.setOnClickListener(this);
attach.setOnClickListener(this);
send.setOnClickListener(this);
}
#Override
public void onClick(View view) {
switch (view.getId()){
case R.id.goBackFromCoversation:
finish();
break;
case R.id.conversationUserName:
Intent intent= new Intent(ConversationActivity.this,ViewProfileActivity.class);
intent.putExtra("userId",getUserId);
startActivity(intent);
break;
case R.id.attachFiles:
break;
case R.id.sendMessage:
getTextMessage=typeMessage.getText().toString();
messageType=0;
sendMessage(chatType,id,getUserId,messageType,getTextMessage);
onCreate(null);
break;
}
}
private void fetchConversation(int id, int getUserId) {
Gson gson = new GsonBuilder()
.setLenient()
.create();
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(interceptor).build();
Retrofit retrofi = new Retrofit.Builder()
.baseUrl("http://192.168.56.110/app2/")
.addConverterFactory(GsonConverterFactory.create(gson))
.addConverterFactory(ScalarsConverterFactory.create())
.client(client)
.build();
RetrofitApi service = retrofi.create(RetrofitApi.class);
Call<Message> call = service.getMessages(id,getUserId);
/* Call<Message> call = RetrofitClient
.getmInstance()
.getApi()
.getMessages(id, Integer.parseInt(getUserId));*/
call.enqueue(new Callback<Message>() {
#Override
public void onResponse(Call<Message> call, Response<Message> response) {
if (response.isSuccessful()) {
if (response.body() != null) {
Message sr = response.body();
int count=sr.getConversation().toArray().length;
if(sr.getSuccess()==1){
for(int i=0;i<sr.getConversation().toArray().length;i++){
messageId=sr.getConversation().get(i).getMessageId();
fromId=sr.getConversation().get(i).getSenderId();
toId=sr.getConversation().get(i).getReceiverId();
type=sr.getConversation().get(i).getType();
timeSent=sr.getConversation().get(i).getTime_sent();
message=sr.getConversation().get(i).getMessage();
Conversation c=new Conversation(messageId,fromId,toId,type,message,timeSent);
conversation.add(c);
cla.notifyDataSetChanged();
}
}else{
Log.v(TAG,"success is not 1");
}
} else {
Log.v(TAG, "fetchConvo, response is null ");
Toast.makeText(getApplicationContext(), "resposne is null", Toast.LENGTH_SHORT).show();
}
} else {
Log.v(TAG, "fetchConvo, Something went wrong");
Toast.makeText(getApplicationContext(), "Something went wrong- ", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(Call<Message> call, Throwable t) {
Log.v(TAG, "fetchConvo, response is" + t.getMessage());
Toast.makeText(getApplicationContext(), "Failure, response is- " + t.getMessage(), Toast.LENGTH_LONG).show();
Log.v(TAG, "fetchConvo, Failed, cause is " + t.getCause());
Toast.makeText(getApplicationContext(), "Failed, cause is - " + t.getCause(), Toast.LENGTH_LONG).show();
}
});
}
private void loadDp(String getUserDp) {
String[] parts= getUserDp.split("htdocs");
String newString="http://192.168.56.110"+ parts[1];
Log.e(TAG, newString );
GlideApp.with(this).
load(newString)
.diskCacheStrategy( DiskCacheStrategy.ALL )
.into(dp);
}
private void sendMessage(int chat,int id, int getUserId, int messageType, String getTextMessage) {
Log.v(TAG,"id is"+ id);
Log.v(TAG,"userId is"+ getUserId);
Log.v(TAG,"type is"+ messageType);
Log.v(TAG,"message is"+getTextMessage);
Gson gson = new GsonBuilder()
.setLenient()
.create();
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(interceptor).build();
Retrofit retrofi = new Retrofit.Builder()
.baseUrl("http://192.168.56.110/app2/")
.addConverterFactory(GsonConverterFactory.create(gson))
.addConverterFactory(ScalarsConverterFactory.create())
.client(client)
.build();
RetrofitApi service = retrofi.create(RetrofitApi.class);
Call<com.example.user.myapplication.Model.Response> call = service.saveMessages(id,getUserId,getTextMessage,messageType);
/* Call<com.example.user.myapplication.Model.Response> call = RetrofitClient
.getmInstance()
.getApi()
.saveMessages(id,getUserId,getTextMessage,messageType);*/
call.enqueue(new Callback<com.example.user.myapplication.Model.Response>() {
#Override
public void onResponse(Call<com.example.user.myapplication.Model.Response> call, Response<com.example.user.myapplication.Model.Response> response) {
if (response.isSuccessful()) {
if (response.body() != null) {
com.example.user.myapplication.Model.Response sr = response.body();
if(sr.getSuccess()==1){
Log.v(TAG,"Response is successful");
}
} else {
Log.v(TAG, "saveMessage, response is null ");
Toast.makeText(getApplicationContext(), "resposne is null", Toast.LENGTH_SHORT).show();
}
} else {
Log.v(TAG, "saveMessage, Something went wrong");
Toast.makeText(getApplicationContext(), "Something went wrong- ", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(Call<com.example.user.myapplication.Model.Response> call, Throwable t) {
Log.v(TAG, "saveMessage, response is" + t.getMessage());
Toast.makeText(getApplicationContext(), "Failure, response is- " + t.getMessage(), Toast.LENGTH_LONG).show();
Log.v(TAG, "saveMessage, Failed, cause is " + t.getCause());
Toast.makeText(getApplicationContext(), "Failed, cause is - " + t.getCause(), Toast.LENGTH_LONG).show();
}
});
}
Conversation Adapter
public class ConversationAdapter extends RecyclerView.Adapter<ConversationAdapter.ViewHolder> {
private static final String TAG = "ChatListAdapter";
private Context context;
private ArrayList<Conversation> conversation= new ArrayList<>();
private int id;
public ConversationAdapter(Context context, ArrayList<Conversation> conversation) {
this.context = context;
this.conversation = conversation;
}
#NonNull
#Override
public ConversationAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.list_item_message, viewGroup, false);
ConversationAdapter.ViewHolder viewHolder = new ConversationAdapter.ViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(#NonNull ViewHolder viewHolder, int i) {
if (SharedPrefManager.getInstance(context).contains("keyid")) {
id = SharedPrefManager.getInstance(context).getUser().getId();
Toast.makeText(context, "user id is " + id, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(context, "no id found", Toast.LENGTH_SHORT).show();
}
if(Integer.parseInt(conversation.get(i).getSenderId())==id){
viewHolder.messageSent.setText(conversation.get(i).getMessage());
viewHolder.messaegReceievd.setVisibility(View.GONE);
}else{
viewHolder.messaegReceievd.setText(conversation.get(i).getMessage());
viewHolder.messageSent.setVisibility(View.GONE);
}
if(i==conversation.toArray().length-1) {
viewHolder.messageTime.setText(conversation.get(conversation.toArray().length- 1).getTime_sent());
}else{
viewHolder.messageTime.setVisibility(View.GONE);
}
}
#Override
public int getItemCount() {
return conversation.toArray().length;
}
public class ViewHolder extends RecyclerView.ViewHolder {
BubbleTextView messageSent,messaegReceievd;
TextView messageTime;
public ViewHolder(#NonNull View itemView) {
super(itemView);
Log.v(TAG, "ViewHolder, setting view in variables");
messageSent=itemView.findViewById(R.id.textMessageSent);
messaegReceievd=itemView.findViewById(R.id.textMessageReceived);
messageTime=itemView.findViewById(R.id.messageSentTime);
}
}
}
Whenever i send message and tries to reload the activity to show the messages received or send i start activity again and have to make network request once again which i think will take much time when real user will use it. So, therefore i want to implement something else to make it instant messaging activity.
Any help would be appreciated Thanks in advance

Related

Android Studio: How to send data from Activity to Fragment | Method invocation 'getString' may produce 'NullPointerException'

I am having a problem where in the Fragment the "getString()" says "Method invocation 'getString' may produce 'NullPointerException'" that's the only problem. The Fragment is stored in MainActivity in Navigation Window.
LoginActivity (Where MainActivity is getting the Data):
private void LoginMethod(String email, String password) {
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
String result = jsonObject.getString("success");
JSONArray jsonArray = jsonObject.getJSONArray("login");
if (result.equals("1")){
for (int i = 0; i < jsonArray.length(); i++){
JSONObject object = jsonArray.getJSONObject(i);
String username = object.getString("Username").trim();
String email = object.getString("Email").trim();
Toast.makeText(Login.this, "Login Success: " + username, Toast.LENGTH_SHORT).show();
Intent intent = new Intent(Login.this, MainActivity.class);
intent.putExtra("username", username);
intent.putExtra("email", email);
startActivity(intent);
}
}
else if (result.equals("0")) {
Toast.makeText(Login.this, "Login Failed" + result + response, Toast.LENGTH_LONG).show(); Log.e("JSON Error", response);
Log.e("Login Error", result);
}
}
catch (JSONException e){
Toast.makeText(Login.this, e.getMessage(), Toast.LENGTH_LONG).show();
Log.e("JSON Error", response);
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(Login.this, error.getMessage(), Toast.LENGTH_SHORT).show();
}
})
{
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("Email", email);
params.put("Password", password);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
**MainActivity:**
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
Toolbar toolbar;
TextView getemail, getusername;
DrawerLayout drawerLayout;
NavigationView navigationView;
View navheader;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.i("State","onCreate");
toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
drawerLayout = findViewById(R.id.drawerLayout);
navigationView = findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
navheader = navigationView.getHeaderView(0);
String getUsername = getIntent().getStringExtra("username");
String getEmail = getIntent().getStringExtra("email");
getusername = navheader.findViewById(R.id.getusername);
getemail = navheader.findViewById(R.id.getemail);
toolbar.setTitle(getUsername);
getusername.setText(getUsername);
getemail.setText(getEmail);
ActionBarDrawerToggle actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar,
R.string.nav_drawer_open, R.string.nav_drawer_close);
drawerLayout.addDrawerListener(actionBarDrawerToggle);
actionBarDrawerToggle.syncState();
if (savedInstanceState == null){
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new Home()).commit();
navigationView.setCheckedItem(R.id.home);
}
}
public void getAccountFragmentData(){
String test = "akshdasjkdhsajkdasdas";
String test2 = "wadahawawaawaww";
Bundle bundle = new Bundle();
bundle.putString("username", test);
bundle.putString("email", test2);
Account account = new Account();
account.setArguments(bundle);
Toast.makeText(this, "Account", Toast.LENGTH_SHORT).show();
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()){
case R.id.home:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new Home()).commit();
break;
case R.id.orderfood:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new FoodOrder()).commit();
break;
case R.id.account:
getAccountFragmentData();
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new Account()).commit();
break;
case R.id.settings:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new Settings()).commit();
break;
case R.id.email:
Toast.makeText(this, "Email", Toast.LENGTH_SHORT).show();
break;
case R.id.share:
Toast.makeText(this, "Share", Toast.LENGTH_SHORT).show();
break;
}
drawerLayout.closeDrawer(GravityCompat.START);
return true;
}
#Override
public void onBackPressed() {
if (drawerLayout.isDrawerOpen(GravityCompat.START)){
drawerLayout.closeDrawer(GravityCompat.START);
}
else {
super.onBackPressed();
}
}
#Override
protected void onStart() {
super.onStart();
Log.i("State","onStart");
}
#Override
protected void onResume() {
super.onResume();
Log.i("State","onResume");
}
#Override
protected void onPause() {
super.onPause();
Log.i("State","onPause");
}
#Override
protected void onStop() {
super.onStop();
Log.i("State","onStop");
}
#Override
protected void onRestart() {
super.onRestart();
Log.i("State","onRestart");
}
#Override
protected void onDestroy() {
super.onDestroy();
Log.i("State","onDestroy");
}
}
**Fragment:
**
public class Account extends Fragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_account, container, false);
TextView getUsername = v.findViewById(R.id.username);
TextView getEmail = v.findViewById(R.id.email);
Bundle bundle = this.getArguments();
String setUsername = bundle.getString("username");
String setEmail = bundle.getString("email");
getUsername.setText(setUsername);
getEmail.setText(setEmail);
Log.i("Data Sent", "Sent");
return v;
}
I want the Fragment to get the data from MainActivity.

How to make porcupine detect a wake word and then start listening for user input

I have been trying to implement a way that the application detects wake word like "Hey google" or "Jarvis". I did some research and found out porcupine helps towards solving the wake word problem but now the problem is I can't seem to trigger startRecognition() to listen again for the user input and then carry forward with it. I still tried to trigger startRecognition() but then it was asking me to do speechRecognizer.Destroy() which I tried doing with the porcupine onDestroy method but then it just stopped working. Sorry if I confused anyone, I will attach my code I will really appreciate everyone's help as I have been trying to solve this problem for a while now.
Another question is what does the following line of code do?
PendingIntent contentIntent = PendingIntent.getActivity(
this,
0,
new Intent(this, MainActivity.class), // this line ?
0);
The code currently :(
public class PorcupineService extends Service {
private static final int REQUEST_RECORD_AUDIO_PERMISSION_CODE = 1;
private SpeechRecognizer speechRecognizer;
TextToSpeech textToSpeech;
String userResponse;
Float speechRate = 2f;
private static final String CHANNEL_ID = "PorcupineServiceChannel";
private PorcupineManager porcupineManager;
private int numUtterances;
private void createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel notificationChannel = new NotificationChannel(
CHANNEL_ID,
"Porcupine",
NotificationManager.IMPORTANCE_HIGH);
NotificationManager manager = getSystemService(NotificationManager.class);
manager.createNotificationChannel(notificationChannel);
}
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
createNotificationChannel();
PendingIntent pendingIntent = PendingIntent.getActivity(
this,
0,
new Intent(this, MainActivity.class),
0);
numUtterances = 0;
Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
.setContentTitle("Wake word")
.setContentText("Service running")
.setSmallIcon(R.drawable.ic_launcher_foreground)
.setContentIntent(pendingIntent)
.build();
startForeground(1234, notification);
try {
porcupineManager = new PorcupineManager.Builder()
.setKeyword(Porcupine.BuiltInKeyword.JARVIS)
.setSensitivity(0.7f).build(
getApplicationContext(),
(keywordIndex) -> {
Log.i("YOU SAID IT!", "yesss");
textSpeechInitialize();
startRecognition();
listening();
numUtterances++;
PendingIntent contentIntent = PendingIntent.getActivity(
this,
0,
new Intent(this, MainActivity.class),
0);
final String contentText = numUtterances == 1 ? " time!" : " times!";
Notification n = new NotificationCompat.Builder(this, CHANNEL_ID)
.setContentTitle("Wake word")
.setContentText("Detected " + numUtterances + contentText)
.setSmallIcon(R.drawable.ic_launcher_background)
.setContentIntent(contentIntent)
.build();
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
assert notificationManager != null;
notificationManager.notify(1234, n);
});
porcupineManager.start();
} catch (PorcupineException e) {
Log.e("PORCUPINE", e.toString());
}
return super.onStartCommand(intent, flags, startId);
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onDestroy() {
try {
porcupineManager.stop();
porcupineManager.delete();
speechRecognizer.destroy();
} catch (PorcupineException e) {
Log.e("PORCUPINE", e.toString());
}
super.onDestroy();
}
public void listening(){
speechRecognizer = SpeechRecognizer.createSpeechRecognizer(this);
speechRecognizer.setRecognitionListener(new RecognitionListener() {
#Override
public void onReadyForSpeech(Bundle params) {
}
#Override
public void onBeginningOfSpeech() {}
#Override
public void onRmsChanged(float rmsdB) {}
#Override
public void onBufferReceived(byte[] buffer) {}
#Override
public void onEndOfSpeech() {}
#Override
public void onError(int error) {
String errorMessage = getErrorText(error);
Log.i(">>> INFO", "Failed " + errorMessage);
}
#Override
public void onResults(Bundle results) {
ArrayList<String> matches = results.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
userResponse = matches.get(0);
userResponse = userResponse.toLowerCase();
toSpeak(userResponse);
}
#Override
public void onPartialResults(Bundle partialResults) {}
#Override
public void onEvent(int eventType, Bundle params) {}
});
}
public void textSpeechInitialize(){
textToSpeech = new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS){
textToSpeech.setLanguage(Locale.getDefault());
textToSpeech.setSpeechRate(speechRate);
String greet = greetings();
toSpeak(greet);
startRecognition();
} else {
Toast.makeText(getApplicationContext(), "Feature not supported", Toast.LENGTH_SHORT).show();
}
}
});
}
public String getErrorText(int errorCode) {
String message;
switch (errorCode) {
...
}
return message;
}
public static String greetings(){
String s = "";
Calendar c = Calendar.getInstance();
int time = c.get(Calendar.HOUR_OF_DAY);
if (time >= 0 && time < 12){
s = "Good Morning sir! how can I help you today?";
} else if (time >= 12 && time < 16){
s = "Good Afternoon sir";
} else if (time >= 16 && time < 22){
s = "Good Evening sir";
}
else if (time >= 22 && time < 24){
s = "Hello sir, you need to take some rest... its getting late!";
}
return s;
}
private void startRecognition() {
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, getPackageName());
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, "en");
speechRecognizer.startListening(intent);
}
private void toSpeak(String toSpeak){
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
Log.i(">>>Voice Info", String.valueOf(textToSpeech.getVoice()));
}
try {
textToSpeech.speak(toSpeak, TextToSpeech.QUEUE_FLUSH, null);
} catch (Exception e){
e.printStackTrace();
}
}
}

Print from another activity

I managed to establish a bluetooth connection from my main activity but i want to print from another activity.
How can I do this?
Main Activity Where I Start A connection to a bluetooth printer
protected static final String TAG = "TAG";
private static final int REQUEST_ENABLE_BT = 2;
private static final int REQUEST_CONNECT_DEVICE = 1;
private ProgressDialog BluetoothConnectProgressDialog;
Button button_connect_to_bluetooth_printer;
private UUID applicationUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
private BluetoothAdapter bluetoothAdapter;
private BluetoothSocket bluetoothSocket;
private BluetoothDevice bluetoothDevice;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button_connect_to_bluetooth_printer = findViewById(R.id.btn_connect_bluetooth);
button_connect_to_bluetooth_printer.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (!bluetoothAdapter.isEnabled())
{
Intent enableBluetooth = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBluetooth, REQUEST_ENABLE_BT);
}
else
{
ListPairedDevices();
Intent connectIntent = new Intent(MainActivity.this, BluetoothDeviceListActivity.class);
startActivityForResult(connectIntent,
REQUEST_CONNECT_DEVICE);
}
}
});
}
private void ListPairedDevices()
{
Set<BluetoothDevice> PairedDevices = bluetoothAdapter.getBondedDevices();
if (PairedDevices.size() > 0)
{
for (BluetoothDevice mDevice : PairedDevices)
{
Log.v(TAG, "PairedDevices: " + mDevice.getName() + mDevice.getAddress());
}
}
}
public void onActivityResult(int RequestCode, int ResultCode, Intent DataIntent)
{
super.onActivityResult(RequestCode, ResultCode, DataIntent);
switch (RequestCode)
{
case REQUEST_CONNECT_DEVICE:
if (ResultCode == Activity.RESULT_OK)
{
Bundle mExtra = DataIntent.getExtras();
String mDeviceAddress = mExtra.getString("DeviceAddress");
Log.v(TAG, "Coming incoming address " + mDeviceAddress);
bluetoothDevice = bluetoothAdapter
.getRemoteDevice(mDeviceAddress);
BluetoothConnectProgressDialog = ProgressDialog.show(this, "Connecting...", bluetoothDevice.getName() + " : " + bluetoothDevice.getAddress(), true, true);
Thread mBlutoothConnectThread = new Thread(this);
mBlutoothConnectThread.start();
// pairToDevice(mBluetoothDevice); This method is replaced by
// progress dialog with thread
}
break;
case REQUEST_ENABLE_BT:
if (ResultCode == Activity.RESULT_OK) {
ListPairedDevices();
Intent connectIntent = new Intent(MainActivity.this,
BluetoothDeviceListActivity.class);
startActivityForResult(connectIntent, REQUEST_CONNECT_DEVICE);
} else {
Toast.makeText(MainActivity.this, "Message", Toast.LENGTH_SHORT).show();
}
break;
}
}
public void run()
{
try
{
bluetoothSocket = bluetoothDevice.createRfcommSocketToServiceRecord(applicationUUID);
bluetoothAdapter.cancelDiscovery();
bluetoothSocket.connect();
handler.sendEmptyMessage(0);
}
catch (IOException eConnectException)
{
Log.d(TAG, "CouldNotConnectToSocket", eConnectException);
closeSocket(bluetoothSocket);
return;
}
}
#SuppressLint("HandlerLeak")
private Handler handler = new Handler() {
#Override
public void handleMessage(Message msg)
{
BluetoothConnectProgressDialog.dismiss();
}
};
private void closeSocket(BluetoothSocket nOpenSocket)
{
try
{
nOpenSocket.close();
Log.d(TAG, "SocketClosed");
}
catch (IOException ex)
{
Log.d(TAG, "CouldNotCloseSocket");
}
}
this is my device list activity
protected static final String TAG = "TAG";
private BluetoothAdapter bluetoothAdapter;
private ArrayAdapter<String> paired_devices_list;
#Override
protected void onCreate(Bundle mSavedInstanceState)
{
super.onCreate(mSavedInstanceState);
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setContentView(R.layout.activity_bluetooth_device_list);
setResult(Activity.RESULT_CANCELED);
paired_devices_list = new ArrayAdapter<>(this, R.layout.bluetooth_device_name);
ListView PairedListDevices = findViewById(R.id.paired_devices);
PairedListDevices.setAdapter(paired_devices_list);
PairedListDevices.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l)
{
try
{
bluetoothAdapter.cancelDiscovery();
String mdeviceInfo = ((TextView) view).getText().toString();
String deviceAddress = mdeviceInfo.substring(mdeviceInfo.length() - 17);
Log.v(TAG, "Device_Address " + deviceAddress);
Bundle bundle = new Bundle();
bundle.putString("DeviceAddress", deviceAddress);
Intent mBackIntent = new Intent();
mBackIntent.putExtras(bundle);
setResult(Activity.RESULT_OK, mBackIntent);
finish();
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
});
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
Set<BluetoothDevice> PairedDevices = bluetoothAdapter.getBondedDevices();
if (PairedDevices.size() > 0)
{
findViewById(R.id.title_paired_devices).setVisibility(View.VISIBLE);
for (BluetoothDevice mDevice : PairedDevices)
{
paired_devices_list.add(mDevice.getName() + "\n" + mDevice.getAddress());
}
}
else
{
String NoDevices = "None Paired";
paired_devices_list.add(NoDevices);
}
}
#Override
protected void onDestroy()
{
super.onDestroy();
if (bluetoothAdapter != null)
{
bluetoothAdapter.cancelDiscovery();
}
}
And this my print activity
public void print()
{
Thread t = new Thread()
{
public void run()
{
try
{
OutputStream os = bluetoothSocket.getOutputStream();
String account_no;
account_no_value = ""+ Account_No.getText().toString()+"\n";
os.write(account_no.getBytes());
}
catch (Exception e)
{
Log.e("PrintActivity", "Exe ", e);
}
}
};
t.start();
}
E/PrintActivity: Exe
java.lang.NullPointerException: Attempt to invoke virtual method 'java.io.OutputStream android.bluetooth.BluetoothSocket.getOutputStream()' on a null object reference
at com.vicjames.qiimeterreader.PrintBill$6.run(PrintBill.java:1635)
how can I fix this?? The app is not crashing but it wont print either.

Android Studio In App Billing How To Verify Purchase On Device?

I've been working with Android Studio for a short time and this is my first project. I don't know a lot of points, and I apologize for my complex code. There are only 1 consumable product in my app and gives the user 20 lives. I succeeded in adding in-app purchase to my application as a result of long efforts. In my application I was able to make purchases with google test cards with my own product ID. I did not have any problems up to here. Since I don't have a server, I have to do the purchase verification on the device. I wrote all purchase and verification codes in an activity. I think it might sound a bit silly, but I don't know where to make the confirmation of the purchase. My application accepts verification even if it is an incorrect signature. What is the point I missed in my codes?
public class MagazaActivity extends AppCompatActivity {
Button baslik, buy_button;
Can hak;
int can;
private BillingClient mBillingClient;
private final List<Purchase> mPurchases = new ArrayList<>();
private static final String BASE_64_ENCODED_PUBLIC_KEY = "XXXXX";
private static final String TAG = "IABUtil/Security";
private static final String KEY_FACTORY_ALGORITHM = "RSA";
private static final String SIGNATURE_ALGORITHM = "SHA1withRSA";
String canfiyat;
mBillingClient =BillingClient.newBuilder(MagazaActivity.this).
setListener(new PurchasesUpdatedListener() {
#Override
public void onPurchasesUpdated ( int responseCode,
#Nullable List<Purchase> purchases){
if (responseCode == BillingClient.BillingResponse.OK
&& purchases != null) {
for (final Purchase purchase : purchases) {
ConsumeResponseListener listener = new
ConsumeResponseListener() {
#Override
public void
onConsumeResponse(#BillingClient.BillingResponse int responseCode, String
outToken) {
if (responseCode ==
BillingClient.BillingResponse.OK) {
handlePurchase(purchase);
}
}
};
mBillingClient.consumeAsync(purchase.getPurchaseToken(), listener);
}
} else if (responseCode ==
BillingClient.BillingResponse.USER_CANCELED) {
billingCanceled();
}
else {
AlertDialog.Builder builder2 = new
AlertDialog.Builder(MagazaActivity.this, R.style.AlertDialogCustom);
builder2.setMessage("Billing System İs İnvalid");
builder2.setCancelable(true);
LayoutInflater factory =
LayoutInflater.from(MagazaActivity.this);
final View view = factory.inflate(R.layout.sample4,
null);
builder2.setView(view);
builder2.setPositiveButton(
"OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
dialog.cancel();
}
});
AlertDialog alert11 = builder2.create();
alert11.show();
}
}
}).
build();
buy_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mBillingClient.startConnection(new BillingClientStateListener()
{
#Override
public void
onBillingSetupFinished(#BillingClient.BillingResponse int
billingResponseCode) {
if (billingResponseCode ==
BillingClient.BillingResponse.OK) {
final List<String> skuList = new ArrayList<>();
skuList.add("XXX");
SkuDetailsParams skuDetailsParams =
SkuDetailsParams.newBuilder()
.setSkusList(skuList).setType(BillingClient.SkuType.INAPP).build();
mBillingClient.querySkuDetailsAsync(skuDetailsParams,
new SkuDetailsResponseListener() {
#Override
public void onSkuDetailsResponse(int
responseCode,
List<SkuDetails> skuDetailsList) {
BillingFlowParams flowParams =
BillingFlowParams.newBuilder()
.setSkuDetails(skuDetailsList.get(0))
.build();
int billingResponseCode =
mBillingClient.launchBillingFlow(MagazaActivity.this, flowParams);
if (billingResponseCode ==
BillingClient.BillingResponse.OK) {
for (SkuDetails skuDetails :
skuDetailsList) {
String sku =
skuDetails.getSku();
String price =
skuDetails.getPrice();
if ("XXX".equals(sku)) {
canfiyat = price;
}
}
}
}
});
}
}
#Override
public void onBillingServiceDisconnected() {
AlertDialog.Builder builder = new
AlertDialog.Builder(MagazaActivity.this);
builder.setMessage("Connection Error")
.setCancelable(false)
.setPositiveButton("Retry", new
DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
});
}
});
}
#Override
public void onBackPressed() {
Intent intentLayout8 = new Intent(MagazaActivity.this,
MainActivity.class);
startActivity(intentLayout8);
MagazaActivity.this.finish();
}
private void billingCanceled() {
AlertDialog.Builder builder = new
AlertDialog.Builder(MagazaActivity.this);
builder.setMessage("Purchase Canceled")
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
public static PublicKey generatePublicKey(String encodedPublicKey) {
try {
byte[] decodedKey = Base64.decode(encodedPublicKey,
Base64.DEFAULT);
KeyFactory keyFactory =
KeyFactory.getInstance(KEY_FACTORY_ALGORITHM);
return keyFactory.generatePublic(new
X509EncodedKeySpec(decodedKey));
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
} catch (InvalidKeySpecException e) {
Log.e(TAG, "Invalid key specification.");
throw new IllegalArgumentException(e);
}
}
public static boolean verifyPurchase(String base64PublicKey, String
signedData, String signature) {
if (TextUtils.isEmpty(signedData) || TextUtils.isEmpty(base64PublicKey)
||
TextUtils.isEmpty(signature)) {
Log.e("HATA", "Purchase verification failed");
return false;
}
PublicKey key = MagazaActivity.generatePublicKey(base64PublicKey);
return MagazaActivity.verify(key, signedData, signature);
}
public static boolean verify(PublicKey publicKey, String signedData, String
signature) {
byte[] signatureBytes;
try {
signatureBytes = Base64.decode(signature, Base64.DEFAULT);
} catch (IllegalArgumentException e) {
Log.e(TAG, "Base64 decoding failed.");
return false;
}
try {
Signature sig = Signature.getInstance(SIGNATURE_ALGORITHM);
sig.initVerify(publicKey);
sig.update(signedData.getBytes());
if (!sig.verify(signatureBytes)) {
Log.e(TAG, "Signature verification failed.");
return false;
}
return true;
} catch (NoSuchAlgorithmException e) {
Log.e(TAG, "NoSuchAlgorithmException.");
} catch (InvalidKeyException e) {
Log.e(TAG, "Invalid key specification.");
} catch (SignatureException e) {
Log.e(TAG, "Signature exception.");
}
return false;
}
private boolean verifyValidSignature(String signedData, String signature) {
try {
return MagazaActivity.verifyPurchase(BASE_64_ENCODED_PUBLIC_KEY,
signedData, signature);
} catch (Exception e) {
Log.e(TAG, "Got an exception trying to validate a purchase: " + e);
return false;
}
}
public void handlePurchase(Purchase purchase) {
if (!verifyValidSignature(purchase.getOriginalJson(),
purchase.getSignature())) {
Log.i("Warning", "Purchase: " + purchase + "; signature
failure...");
return;
}
Log.d("MESAJ", "Got a verified purchase: " + purchase);
hak.cancan = hak.cancan + 20;
SharedPreferences pref =
getApplicationContext().getSharedPreferences("MyPref", MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.putInt("kalp", hak.cancan);
editor.apply();
mPurchases.add(purchase);
}
public void onResume() {
super.onResume();
}
}

I am getting the following Error

I am getting the following Error: java.lang.NullPointerException: Attempt to invoke virtual method 'double android.location.Location.getLatitude()' on a null object reference
this the Logcat
java.lang.NullPointerException: Attempt to invoke virtual method 'double android.location.Location.getLatitude()' on a null object reference
at com.example.shibli.luxuryrider.Home.requestPickupHere(Home.java:338)
at com.example.shibli.luxuryrider.Home.access$000(Home.java:96)
at com.example.shibli.luxuryrider.Home$2.onClick(Home.java:217)
at android.view.View.performClick(View.java:4848)
at android.view.View$PerformClick.run(View.java:20300)
at android.os.Handler.handleCallback(Handler.java:815)
at android.os.Handler.dispatchMessage(Handler.java:104)
at android.os.Looper.loop(Looper.java:194)
at android.app.ActivityThread.main(ActivityThread.java:5682)
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:963)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:758)
and this the code .. any help please
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mService = Common.getFCMService();
fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
//init storage
storage = FirebaseStorage.getInstance();
storageReference = storage.getReference();
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
View navigationHeaderView = navigationView.getHeaderView(0);
txtRiderName = navigationHeaderView.findViewById(R.id.txtRiderName);
txtRiderName.setText(String.format("%s", Common.currentUser.getName()));
txtStars = navigationHeaderView.findViewById(R.id.txtStars);
txtStars.setText(String.format("%s", Common.currentUser.getRates()));
imageAvatar = navigationHeaderView.findViewById(R.id.imageAvatar);
//Load avatar
if (Common.currentUser.getAvatarUrl() != null && !TextUtils.isEmpty(Common.currentUser.getAvatarUrl())) {
Picasso.with(this)
.load(Common.currentUser.getAvatarUrl())
.into(imageAvatar);
}
//Maps
mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
//Geo Fire
ref = FirebaseDatabase.getInstance().getReference("Drivers");
geoFire = new GeoFire(ref);
//init View
imgExpandable = (ImageView)findViewById(R.id.imgExpandable);
mBottomSheet = BottomSheetRiderFragment.newInstance("Rider bottom sheet");
imgExpandable.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mBottomSheet.show(getSupportFragmentManager(),mBottomSheet.getTag());
}
});
btnPickupRequest = (Button) findViewById(R.id.btnPickupRequest);
btnPickupRequest.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (!Common.isDriverFound)
requestPickupHere(FirebaseAuth.getInstance().getCurrentUser().getUid());
else
sendRequestToDriver(Common.driverId);
}
});
place_destination = (PlaceAutocompleteFragment) getFragmentManager().findFragmentById(R.id.place_destination);
place_location = (PlaceAutocompleteFragment) getFragmentManager().findFragmentById(R.id.place_location);
typeFilter = new AutocompleteFilter.Builder()
.setTypeFilter(AutocompleteFilter.TYPE_FILTER_ADDRESS)
.setTypeFilter(3)
.build();
//Event
place_location.setOnPlaceSelectedListener(new PlaceSelectionListener() {
#Override
public void onPlaceSelected(Place place) {
mPlaceLocation = place.getAddress().toString();
//Remove Old Marker
mMap.clear();
//Add Marker at New Location
mUserMarker = mMap.addMarker(new MarkerOptions().position(place.getLatLng())
.icon(BitmapDescriptorFactory.fromResource(R.drawable.marker))
.title("Pickup Here"));
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(place.getLatLng(), 15.0f));
}
#Override
public void onError(Status status) {
}
});
place_destination.setOnPlaceSelectedListener(new PlaceSelectionListener() {
#Override
public void onPlaceSelected(Place place) {
mPlaceDestination = place.getAddress().toString();
//Add New destination Marker
mMap.addMarker(new MarkerOptions()
.position(place.getLatLng())
.icon(BitmapDescriptorFactory.fromResource(R.drawable.destination_marker))
.title("Destination"));
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(place.getLatLng(), 15.0f));
// Show information in bottom
BottomSheetRiderFragment mBottomsheet = BottomSheetRiderFragment.newInstance(mPlaceLocation);
mBottomsheet.show(getSupportFragmentManager(), mBottomsheet.getTag());
}
#Override
public void onError(Status status) {
}
});
setUpLocation();
updateFirebaseToken();
}
private void updateFirebaseToken() {
FirebaseDatabase db = FirebaseDatabase.getInstance();
DatabaseReference tokens = db.getReference(Common.token_tb1);
Token token = new Token(FirebaseInstanceId.getInstance().getToken());
tokens.child(FirebaseAuth.getInstance().getCurrentUser().getUid())
.setValue(token);
}
private void sendRequestToDriver(String driverId) {
DatabaseReference tokens = FirebaseDatabase.getInstance().getReference(Common.token_tb1);
tokens.orderByKey().equalTo(driverId)
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot postSnapShot : dataSnapshot.getChildren()) {
Token token = postSnapShot.getValue(Token.class);
//Make raw payload
String json_lat_lng = new Gson().toJson(new LatLng(mLastLocation.getLatitude(), mLastLocation.getLongitude()));
String riderToken = FirebaseInstanceId.getInstance().getToken();
Notification data = new Notification(riderToken, json_lat_lng);
Sender content = new Sender(token.getToken(), data);
mService.sendMessage(content)
.enqueue(new Callback<FCMResponse>() {
#Override
public void onResponse(Call<FCMResponse> call, Response<FCMResponse> response) {
if (response.body().success == 1)
Toast.makeText(Home.this, "Request sent", Toast.LENGTH_SHORT).show();
else
Toast.makeText(Home.this, "Failed", Toast.LENGTH_SHORT).show();
}
#Override
public void onFailure(Call<FCMResponse> call, Throwable t) {
Log.e("ERROR", t.getMessage());
}
});
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void requestPickupHere(String uid) {
DatabaseReference dbRequest = FirebaseDatabase.getInstance().getReference(Common.pickup_request_tb1);
GeoFire mGeoFire = new GeoFire(dbRequest);
mGeoFire.setLocation(uid, new GeoLocation(mLastLocation.getLatitude(), mLastLocation.getLongitude()));
if (mUserMarker.isVisible())
mUserMarker.remove();
//Add new Marker
mUserMarker = mMap.addMarker(new MarkerOptions()
.title("Pickup Here")
.snippet("")
.position(new LatLng(mLastLocation.getLatitude(), mLastLocation.getLongitude()))
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED)));
mUserMarker.showInfoWindow();
btnPickupRequest.setText("Getting your Driver...");
findDriver();
}
private void findDriver() {
final DatabaseReference drivers = FirebaseDatabase.getInstance().getReference(Common.driver_tb1);
GeoFire gfDrivers = new GeoFire(drivers);
final GeoQuery geoQuery = gfDrivers.queryAtLocation(new GeoLocation(mLastLocation.getLatitude(), mLastLocation.getLongitude()), radius);
geoQuery.removeAllListeners();
geoQuery.addGeoQueryEventListener(new GeoQueryEventListener() {
#Override
public void onKeyEntered(String key, GeoLocation location) {
// if found
if (!Common.isDriverFound) {
Common.isDriverFound = true;
Common.driverId = key;
btnPickupRequest.setText("CALL DRIVER");
Toast.makeText(Home.this, ""+key, Toast.LENGTH_SHORT).show();
}
}
#Override
public void onKeyExited(String key) {
}
#Override
public void onKeyMoved(String key, GeoLocation location) {
}
#Override
public void onGeoQueryReady() {
//if still not found driver , increase distance
if (!Common.isDriverFound && radius < LIMIT) {
radius++;
findDriver();
} else {
if (!Common.isDriverFound) {
Toast.makeText(Home.this, "No available any driver near you", Toast.LENGTH_SHORT).show();
btnPickupRequest.setText("REQUEST PICKUP");
geoQuery.removeAllListeners();
}
}
}
#Override
public void onGeoQueryError(DatabaseError error) {
}
});
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode) {
case MY_PERMISSION_REQUEST_CODE:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
setUpLocation();
}
break;
}
}
private void setUpLocation() {
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
//Request runtime permission
ActivityCompat.requestPermissions(this, new String[]{
android.Manifest.permission.ACCESS_COARSE_LOCATION,
android.Manifest.permission.ACCESS_FINE_LOCATION
}, MY_PERMISSION_REQUEST_CODE);
} else {
buildLocationCallBack();
createLocationRequest();
displayLocation();
}
}
private void buildLocationCallBack() {
locationCallback = new LocationCallback() {
#Override
public void onLocationResult(LocationResult locationResult) {
Common.mLastLocation = locationResult.getLocations().get(locationResult.getLocations().size() - 1);
displayLocation();
}
};
}
private void displayLocation() {
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
fusedLocationProviderClient.getLastLocation().addOnSuccessListener(new OnSuccessListener<Location>() {
#Override
public void onSuccess(Location location) {
Common.mLastLocation = location;
if (Common.mLastLocation != null) {
LatLng center = new LatLng(Common.mLastLocation.getLatitude(), Common.mLastLocation.getLongitude());
LatLng northSide = SphericalUtil.computeOffset(center, 100000, 0);
LatLng southSide = SphericalUtil.computeOffset(center, 100000, 180);
LatLngBounds bounds = LatLngBounds.builder()
.include(northSide)
.include(southSide)
.build();
place_location.setBoundsBias(bounds);
place_location.setFilter(typeFilter);
place_destination.setBoundsBias(bounds);
place_location.setFilter(typeFilter);
driversAvailable = FirebaseDatabase.getInstance().getReference(Common.driver_tb1);
driversAvailable.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
LoadAllAvailableDriver(new LatLng(Common.mLastLocation.getLatitude(), Common.mLastLocation.getLongitude()));
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
final double latitude = Common.mLastLocation.getLatitude();
final double longitude = Common.mLastLocation.getLongitude();
LoadAllAvailableDriver(new LatLng(Common.mLastLocation.getLatitude(), Common.mLastLocation.getLongitude()));
Log.d("EDMTDEV", String.format("Your location was changed: %f / %f", latitude, longitude));
} else {
Log.d("ERROR", "Cannot get your location");
}
}
});
}
private void LoadAllAvailableDriver(final LatLng location) {
//Add Marker
mMap.clear();
mUserMarker = mMap.addMarker(new MarkerOptions()
.icon(BitmapDescriptorFactory.fromResource(R.drawable.marker))
.position(location)
.title("You'r Location"));
//Move Camera to this position
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(location, 15.0f));
//Load all available Driver in distance 3km
DatabaseReference driverLocation = FirebaseDatabase.getInstance().getReference(Common.driver_tb1);
GeoFire gf = new GeoFire(driverLocation);
GeoQuery geoQuery = gf.queryAtLocation(new GeoLocation(location.latitude, location.longitude), distance);
geoQuery.removeAllListeners();
geoQuery.addGeoQueryEventListener(new GeoQueryEventListener() {
#Override
public void onKeyEntered(String key, final GeoLocation location) {
FirebaseDatabase.getInstance().getReference(Common.user_driver_tb1)
.child(key)
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Rider rider = dataSnapshot.getValue(Rider.class);
//Add Driver to map
mMap.addMarker(new MarkerOptions()
.position(new LatLng(location.latitude, location.longitude))
.flat(true)
.title(rider.getName())
.snippet("Phone : "+rider.getPhone())
.icon(BitmapDescriptorFactory.fromResource(R.drawable.car)));
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
#Override
public void onKeyExited(String key) {
}
#Override
public void onKeyMoved(String key, GeoLocation location) {
}
#Override
public void onGeoQueryReady() {
if (distance <= LIMIT) // distance just find for 3 km
{
distance++;
LoadAllAvailableDriver(location);
}
}
#Override
public void onGeoQueryError(DatabaseError error) {
}
});
}
private void createLocationRequest() {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(UPDATE_INTERVAL);
mLocationRequest.setFastestInterval(FATEST_INTERVAL);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setSmallestDisplacement(DISPLACEMENT);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.home, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_signOut) {
signout();
} else if (id == R.id.nav_updateInformation) {
showUpdateInformationDialog();
}
return true;
}
private void showUpdateInformationDialog() {
AlertDialog.Builder alertdialog = new AlertDialog.Builder(Home.this);
alertdialog.setTitle("Update Information");
alertdialog.setMessage("Please Enter Your New data");
LayoutInflater inflater = this.getLayoutInflater();
View update_info_layout = inflater.inflate(R.layout.layout_update_information, null);
final MaterialEditText edtName = update_info_layout.findViewById(R.id.edtName);
final MaterialEditText edtPhone = update_info_layout.findViewById(R.id.edtPhone);
final ImageView imgAvatar = update_info_layout.findViewById(R.id.imgAvatar);
alertdialog.setView(update_info_layout);
imgAvatar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
chooseImageAndUpload();
}
});
alertdialog.setView(update_info_layout);
//set Button
alertdialog.setPositiveButton("UPDATE", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
final android.app.AlertDialog waitingDialog = new SpotsDialog(Home.this);
waitingDialog.show();
String name = edtName.getText().toString();
String phone = edtPhone.getText().toString();
Map<String, Object> update = new HashMap<>();
if (!TextUtils.isEmpty(name))
update.put("name", name);
if (!TextUtils.isEmpty(phone))
update.put("phone", phone);
//update
DatabaseReference riderInformation = FirebaseDatabase.getInstance().getReference(Common.user_rider_tb1);
riderInformation.child(FirebaseAuth.getInstance().getCurrentUser().getUid())
.updateChildren(update).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
waitingDialog.dismiss();
if (task.isSuccessful())
Toast.makeText(Home.this, "Information Updated", Toast.LENGTH_SHORT).show();
else
Toast.makeText(Home.this, "Information Not Update", Toast.LENGTH_SHORT).show();
}
});
}
});
alertdialog.setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
});
//show Dialog
alertdialog.show();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == Common.PICK_IMAGE_RECUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
Uri saveUri = data.getData();
if (saveUri != null) {
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Uploading...");
progressDialog.show();
String imageName = UUID.randomUUID().toString();
final StorageReference imageFolder = storageReference.child("images/" + imageName);
imageFolder.putFile(saveUri)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
progressDialog.dismiss();
imageFolder.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
Map<String, Object> update = new HashMap<>();
update.put("avatarUrl", uri.toString());
DatabaseReference riderInformation = FirebaseDatabase.getInstance().getReference(Common.user_rider_tb1);
riderInformation.child(FirebaseAuth.getInstance().getCurrentUser().getUid())
.updateChildren(update).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful())
Toast.makeText(Home.this, "Avatar Was Upoload", Toast.LENGTH_SHORT).show();
else
Toast.makeText(Home.this, "Avatar Not Update", Toast.LENGTH_SHORT).show();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(Home.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
});
}
})
.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
double progress = (100.0 * taskSnapshot.getBytesTransferred() / taskSnapshot.getTotalByteCount());
progressDialog.setMessage("Uploaded" + progress + "%");
}
});
}
}
}
private void chooseImageAndUpload() {
//start intent to chose image
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), Common.PICK_IMAGE_RECUEST);
}
#Override
public void onMapReady(GoogleMap googleMap) {
try {
boolean isSuccess = googleMap.setMapStyle(
MapStyleOptions.loadRawResourceStyle(this, R.raw.uber_style_map)
);
if (!isSuccess)
Log.e("ERROR", "Map Style Load Failed !!!");
} catch (Resources.NotFoundException ex) {
ex.printStackTrace();
}
mMap = googleMap;
mMap.getUiSettings().setZoomControlsEnabled(true);
mMap.getUiSettings().setZoomGesturesEnabled(true);
mMap.setInfoWindowAdapter(new CustomInfoWindow(this));
mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
#Override
public void onMapClick(LatLng latLng) {
if (markerDestination != null)
markerDestination.remove();
markerDestination = mMap.addMarker(new MarkerOptions()
.icon(BitmapDescriptorFactory.fromResource(R.drawable.destination_marker))
.position(latLng)
.title("Destination"));
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 15.0f));
BottomSheetRiderFragment mBottomsheet = BottomSheetRiderFragment.newInstance(String.format("%f,%f", mLastLocation.getLatitude(), mLastLocation.getLongitude())
);
mBottomsheet.show(getSupportFragmentManager(), mBottomsheet.getTag());
}
});
if (ActivityCompat.checkSelfPermission(Home.this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(Home.this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
fusedLocationProviderClient.requestLocationUpdates(mLocationRequest, locationCallback, Looper.myLooper());
}
}
THE SOLUTION IS THIS:
IN sendRequestToDriver(String driverId)
change:
this:Token token = postSnapShot.getValue(Token.class);
into this: Token token = new Token(postSnapShot.getValue(String.class));

Resources