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.
Related
i am tried to stream video from uvc camera with agora video call api. but it doesn't work . but the uvc camera preview show proferly on '''''' .
public class VideoChatViewActivity extends AppCompatActivity implements CameraDialog.CameraDialogParent, CameraViewInterface.Callback{
private static final String TAG = VideoChatViewActivity.class.getSimpleName();
private static final int PERMISSION_REQ_ID = 22;
// Permission WRITE_EXTERNAL_STORAGE is not mandatory
// for Agora RTC SDK, just in case if you wanna save
// logs to external sdcard.
private static final String[] REQUESTED_PERMISSIONS = {
Manifest.permission.RECORD_AUDIO,
Manifest.permission.CAMERA
};
private RtcEngine mRtcEngine;
private boolean mCallEnd;
private boolean mMuted;
private FrameLayout mLocalContainer;
private RelativeLayout mRemoteContainer;
private VideoCanvas mLocalVideo;
private VideoCanvas mRemoteVideo;
private ImageView mCallBtn;
private ImageView mMuteBtn;
private ImageView mSwitchCameraBtn;
// Customized logger view
private LoggerRecyclerView mLogView;
private final IRtcEngineEventHandler mRtcEventHandler = new IRtcEngineEventHandler() {
#Override
public void onJoinChannelSuccess(String channel, final int uid, int elapsed) {
runOnUiThread(new Runnable() {
#Override
public void run() {
mLogView.logI("Join channel success, uid: " + (uid & 0xFFFFFFFFL));
}
});
}
#Override
public void onUserJoined(final int uid, int elapsed) {
runOnUiThread(new Runnable() {
#Override
public void run() {
mLogView.logI("First remote video decoded, uid: " + (uid & 0xFFFFFFFFL));
setupRemoteVideo(uid);
}
});
}
#Override
public void onUserOffline(final int uid, int reason) {
runOnUiThread(new Runnable() {
#Override
public void run() {
mLogView.logI("User offline, uid: " + (uid & 0xFFFFFFFFL));
onRemoteUserLeft(uid);
}
});
}
};
private void setupRemoteVideo(int uid) {
ViewGroup parent = mRemoteContainer;
if (parent.indexOfChild(mLocalVideo.view) > -1) {
parent = mLocalContainer;
}
if (mRemoteVideo != null) {
return;
}
SurfaceView view = RtcEngine.CreateRendererView(getBaseContext());
view.setZOrderMediaOverlay(parent == mLocalContainer);
parent.addView(view);
mRemoteVideo = new VideoCanvas(view, VideoCanvas.RENDER_MODE_HIDDEN, uid);
// Initializes the video view of a remote user.
mRtcEngine.setupRemoteVideo(mRemoteVideo);
}
private void onRemoteUserLeft(int uid) {
if (mRemoteVideo != null && mRemoteVideo.uid == uid) {
removeFromParent(mRemoteVideo);
// Destroys remote view
mRemoteVideo = null;
}
}
//usb
private static final int DEFAULT_CAPTURE_WIDTH = 1280;
private static final int DEFAULT_CAPTURE_HEIGHT = 720;
#BindView(R.id.camer_view)
public View mTextureView;
private static final String TAG1 = "Debug";
private UVCCameraHelper mCameraHelper;
private CameraViewInterface mUVCCameraView;
private AlertDialog mDialog;
private boolean isRequest;
private boolean isPreview;
private UVCCameraHelper.OnMyDevConnectListener listener = new UVCCameraHelper.OnMyDevConnectListener() {
#Override
public void onAttachDev(UsbDevice device) {
// request open permission
if (!isRequest) {
isRequest = true;
if (mCameraHelper != null) {
mCameraHelper.requestPermission(0);
}
}
}
#Override
public void onDettachDev(UsbDevice device) {
// close camera
if (isRequest) {
isRequest = false;
mCameraHelper.closeCamera();
showShortMsg(device.getDeviceName() + " is out");
}
}
#Override
public void onConnectDev(UsbDevice device, boolean isConnected) {
if (!isConnected) {
showShortMsg("fail to connect,please check resolution params");
isPreview = false;
} else {
isPreview = true;
showShortMsg("connecting");
// initialize seekbar
// need to wait UVCCamera initialize over
new Thread(new Runnable() {
#Override
public void run() {
try {
Thread.sleep(2500);
} catch (InterruptedException e) {
e.printStackTrace();
}
Looper.prepare();
if(mCameraHelper != null && mCameraHelper.isCameraOpened()) {
}
Looper.loop();
}
}).start();
}
}
#Override
public void onDisConnectDev(UsbDevice device) {
showShortMsg("disconnecting");
}
};
//usb
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_video_chat_view);
ButterKnife.bind(this);//uvc
initUI();
mUVCCameraView = (CameraViewInterface) mTextureView;
mUVCCameraView.setCallback(this);
//mLocalContainer.setCallback(this);
mCameraHelper = UVCCameraHelper.getInstance();
mCameraHelper.setDefaultPreviewSize(1280,720);
mCameraHelper.initUSBMonitor(this, mUVCCameraView, listener);
mCameraHelper.setOnPreviewFrameListener(new AbstractUVCCameraHandler.OnPreViewResultListener() {
#Override
public void onPreviewResult(byte[] bytes) {
try {
AgoraVideoFrame frame = new AgoraVideoFrame();
frame.buf = bytes;
frame.format = AgoraVideoFrame.FORMAT_NV21;
frame.stride = DEFAULT_CAPTURE_WIDTH;
frame.height = DEFAULT_CAPTURE_HEIGHT;
frame.timeStamp = System.currentTimeMillis();
mRtcEngine.pushExternalVideoFrame(frame);
}catch (Exception e){
e.printStackTrace();
}
}
});
// Ask for permissions at runtime.
// This is just an example set of permissions. Other permissions
// may be needed, and please refer to our online documents.
if (checkSelfPermission(REQUESTED_PERMISSIONS[0], PERMISSION_REQ_ID) &&
checkSelfPermission(REQUESTED_PERMISSIONS[1], PERMISSION_REQ_ID)) {
initEngineAndJoinChannel();
}
}
private void initUI() {
mLocalContainer = findViewById(R.id.local_video_view_container);
mRemoteContainer = findViewById(R.id.remote_video_view_container);
mCallBtn = findViewById(R.id.btn_call);
mMuteBtn = findViewById(R.id.btn_mute);
mSwitchCameraBtn = findViewById(R.id.btn_switch_camera);
mLogView = findViewById(R.id.log_recycler_view);
// Sample logs are optional.
showSampleLogs();
}
private void showSampleLogs() {
mLogView.logI("Welcome to Agora 1v1 video call");
mLogView.logW("You will see custom logs here");
mLogView.logE("You can also use this to show errors");
}
private boolean checkSelfPermission(String permission, int requestCode) {
if (ContextCompat.checkSelfPermission(this, permission) !=
PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, REQUESTED_PERMISSIONS, requestCode);
return false;
}
return true;
}
#Override
public void onRequestPermissionsResult(int requestCode,
#NonNull String[] permissions, #NonNull int[] grantResults) {
if (requestCode == PERMISSION_REQ_ID) {
if (grantResults[0] != PackageManager.PERMISSION_GRANTED ||
grantResults[1] != PackageManager.PERMISSION_GRANTED ||
grantResults[2] != PackageManager.PERMISSION_GRANTED) {
showLongToast("Need permissions " + Manifest.permission.RECORD_AUDIO +
"/" + Manifest.permission.CAMERA);
finish();
return;
}
// Here we continue only if all permissions are granted.
// The permissions can also be granted in the system settings manually.
initEngineAndJoinChannel();
}
}
private void showLongToast(final String msg) {
this.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
}
});
}
private void initEngineAndJoinChannel() {
initializeEngine();
setupVideoConfig();
setupLocalVideo();
joinChannel();
}
private void initializeEngine() {
try {
mRtcEngine = RtcEngine.create(getBaseContext(), getString(R.string.agora_app_id), mRtcEventHandler);
} catch (Exception e) {
Log.e(TAG, Log.getStackTraceString(e));
throw new RuntimeException("NEED TO check rtc sdk init fatal error\n" + Log.getStackTraceString(e));
}
}
private void setupVideoConfig() {
mRtcEngine.enableVideo();
mRtcEngine.setVideoEncoderConfiguration(new VideoEncoderConfiguration(
VideoEncoderConfiguration.VD_640x360,
VideoEncoderConfiguration.FRAME_RATE.FRAME_RATE_FPS_15,
VideoEncoderConfiguration.STANDARD_BITRATE,
VideoEncoderConfiguration.ORIENTATION_MODE.ORIENTATION_MODE_FIXED_PORTRAIT));
}
private void setupLocalVideo() {
.
SurfaceView view = RtcEngine.CreateRendererView(getBaseContext());
view.setZOrderMediaOverlay(true);
mLocalContainer.addView(view);
mLocalVideo = new VideoCanvas(view, VideoCanvas.RENDER_MODE_HIDDEN, 0);
mRtcEngine.setupLocalVideo(mLocalVideo);
}
private void joinChannel() {
String token = getString(R.string.agora_access_token);
if (TextUtils.isEmpty(token) || TextUtils.equals(token, "#YOUR ACCESS TOKEN#")) {
token = null; // default, no token
}
mRtcEngine.joinChannel(token, "streaming", "Extra Optional Data", 0);
}
#Override
protected void onDestroy() {
super.onDestroy();
if (!mCallEnd) {
leaveChannel();
}
RtcEngine.destroy();
}
private void leaveChannel() {
mRtcEngine.leaveChannel();
}
public void onLocalAudioMuteClicked(View view) {
mMuted = !mMuted;
mRtcEngine.muteLocalAudioStream(mMuted);
int res = mMuted ? R.drawable.btn_mute : R.drawable.btn_unmute;
mMuteBtn.setImageResource(res);
}
public void onSwitchCameraClicked(View view) {
mRtcEngine.switchCamera();
}
public void onCallClicked(View view) {
if (mCallEnd) {
startCall();
mCallEnd = false;
mCallBtn.setImageResource(R.drawable.btn_endcall);
} else {
endCall();
mCallEnd = true;
mCallBtn.setImageResource(R.drawable.btn_startcall);
}
showButtons(!mCallEnd);
}
private void startCall() {
setupLocalVideo();
joinChannel();
}
private void endCall() {
removeFromParent(mLocalVideo);
mLocalVideo = null;
removeFromParent(mRemoteVideo);
mRemoteVideo = null;
leaveChannel();
}
private void showButtons(boolean show) {
int visibility = show ? View.VISIBLE : View. SurfaceView view .GONE;
mMuteBtn.setVisibility(visibility);
mSwitchCameraBtn.setVisibility(visibility);
}
private ViewGroup removeFromParent(VideoCanvas canvas) {
if (canvas != null) {
ViewParent parent = canvas.view.getParent();
if (parent != null) {
ViewGroup group = (ViewGroup) parent;
group.removeView(canvas.view);
return group;
}
}
return null;
}
private void switchView(VideoCanvas canvas) {
ViewGroup parent = removeFromParent(canvas);
if (parent == mLocalContainer) {
if (canvas.view instanceof SurfaceView) {
((SurfaceView) canvas.view).setZOrderMediaOverlay(false);
}
mRemoteContainer.addView(canvas.view);
} else if (parent == mRemoteContainer) {
if (canvas.view instanceof SurfaceView) {
((SurfaceView) canvas.view).setZOrderMediaOverlay(true);
}
mLocalContainer.addView(canvas.view);
}
}
public void onLocalContainerClick(View view) {
switchView(mLocalVideo);
switchView(mRemoteVideo);
}
///uvc
#Override
protected void onStart() {
super.onStart();
// step.2 register USB event broadcast
if (mCameraHelper != null) {
mCameraHelper.registerUSB();
}
}
#Override
protected void onStop() {
super.onStop();
// step.3 unregister USB event broadcast
if (mCameraHelper != null) {
mCameraHelper.unregisterUSB();
}
}
private void showShortMsg(String msg) {
//
Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
}
#Override
public USBMonitor getUSBMonitor(){ return mCameraHelper.getUSBMonitor();
}
#Override
public void onDialogResult(boolean canceled) {
if (canceled) {
showShortMsg("cancel");
}
}
#Override
public void onSurfaceCreated(CameraViewInterface cameraViewInterface, Surface surface) {
if (!isPreview && mCameraHelper.isCameraOpened()) {
mCameraHelper.startPreview(mUVCCameraView);
isPreview = true;
}
}
#Override
public void onSurfaceChanged(CameraViewInterface cameraViewInterface, Surface surface, int i, int i1) {
}
#Override
public void onSurfaceDestroy(CameraViewInterface cameraViewInterface, Surface surface) {
if (isPreview && mCameraHelper.isCameraOpened()) {
mCameraHelper.stopPreview();
isPreview = false;
}
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_video_chat_view);
initUI();
// Ask for permissions at runtime.
// This is just an example set of permissions. Other permissions
// may be needed, and please refer to our online documents.
if (checkSelfPermission(REQUESTED_PERMISSIONS[0], PERMISSION_REQ_ID) &&
checkSelfPermission(REQUESTED_PERMISSIONS[1], PERMISSION_REQ_ID)) {
initEngineAndJoinChannel();
}
//xiaobing add
final View view = findViewById(R.id.camera_view);
mUVCCameraView = (CameraViewInterface)view;
mUSBMonitor = new USBMonitor(this, mOnDeviceConnectListener);
mUVCCameraView.setAspectRatio(previewWidth / (float)previewHeight);
mCameraHandler = UVCCameraHandler.createHandler(this,
mUVCCameraView, previewWidth,
previewHeight, BANDWIDTH_FACTORS[0],
firstDataCallBack);
}
//xiaobing add
private void startPreview() {
final SurfaceTexture st = mUVCCameraView.getSurfaceTexture();
mCameraHandler.startPreview(new Surface(st));
}
//xiaobing add
UvcCameraDataCallBack firstDataCallBack = new UvcCameraDataCallBack() {
#Override
public void getData(byte[] data) {
if (DEBUG) {
Log.v(TAG, "data callback:" + data.length);
}
AgoraVideoFrame frame = new AgoraVideoFrame();
frame.buf = data;
frame.format = AgoraVideoFrame.FORMAT_NV12;
frame.stride = previewWidth;
frame.height = previewHeight;
frame.timeStamp = System.currentTimeMillis();
mRtcEngine.pushExternalVideoFrame(frame);
}
};
//xiaobing add
#Override
protected void onStart() {
super.onStart();
if (DEBUG) Log.v(TAG, "onStart:");
mUSBMonitor.register();
if (mUVCCameraView != null)
mUVCCameraView.onResume();
if (!mCameraHandler.isOpened()) {
UsbManager um = (UsbManager) (getSystemService(Context.USB_SERVICE));
HashMap<String, UsbDevice> map = um.getDeviceList();
ArrayList<String> names = new ArrayList<>();
final ArrayList<UsbDevice> devices = new ArrayList<>();
for(Map.Entry<String, UsbDevice> item : map.entrySet()) {
String name = item.getValue().getProductName();
String vid = Integer.toHexString(item.getValue().getVendorId());
String pid = Integer.toHexString(item.getValue().getProductId());
String all = "" + name + " VID:" + vid
+ " PID:" + pid;
Log.v("xiaobing", "all:" + all);
names.add(all);
devices.add(item.getValue());
if(item.getValue().getProductId()==1383 && (item.getValue().getVendorId() == 3034)){
mDev = item.getValue();
mUSBMonitor.requestPermission(mDev);
//为了同时支持手机和眼镜,只有获得了眼镜的设备才选择本地视频
mRtcEngine.setExternalVideoSource(true, true, true);
mLogView.logI("使用USB摄像头!");
break;
}
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
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();
}
}
}
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: 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));
New to Nokia development. I am trying to write a hello world for get GPS coordinates of my current location. What am I doing wrong here ?
public class HomeScreen extends MIDlet {
public HomeScreen() {
}
protected void destroyApp(boolean arg0) throws MIDletStateChangeException {
}
protected void pauseApp() {
}
protected void startApp() throws MIDletStateChangeException {
Displayable current = Display.getDisplay(this).getCurrent() ;
if (current == null) {
UpdateJourney updateJourney = new UpdateJourney(this) ;
Display.getDisplay(this).setCurrent(updateJourney) ;
}
}
}
public class UpdateJourney extends Form implements CommandListener, Runnable {
private LocationProvider myLocation;
private Criteria myCriteria;
private Location myCurrentLocation;
private HomeScreen helloScreen;
private Command exitCommand;
private Thread getLocationThread = new Thread(this);;
public UpdateJourney(HomeScreen helloScreen) {
super("Taxeeta");
StringItem helloText = new StringItem("", "Taxeeta");
super.append(helloText);
this.helloScreen = helloScreen;
getLocationThread.start();
}
public double getMyLatitude() {
return myCurrentLocation.getQualifiedCoordinates().getLatitude();
}
public double getMyLongitude() {
return myCurrentLocation.getQualifiedCoordinates().getLongitude();
}
public void commandAction(Command command, Displayable arg1) {
if (command == exitCommand) {
helloScreen.notifyDestroyed();
}
}
public void run() {
myCriteria = new Criteria();
myCriteria.setHorizontalAccuracy(500);
try {
myLocation = LocationProvider.getInstance(myCriteria);
myCurrentLocation = myLocation.getLocation(60);
} catch (LocationException e) {
e.printStackTrace();
System.out
.println("Error : Unable to initialize location provider");
return;
} catch (InterruptedException e) {
e.printStackTrace();
System.out.println("Error: Waited enough for location to return");
return;
}
System.out.println("Location returned Lat:"
+ myCurrentLocation.getQualifiedCoordinates().getLatitude()
+ " Lng:"
+ myCurrentLocation.getQualifiedCoordinates().getLongitude());
exitCommand = new Command("Location returned Lat:"
+ myCurrentLocation.getQualifiedCoordinates().getLatitude()
+ " Lng:"
+ myCurrentLocation.getQualifiedCoordinates().getLongitude(),
Command.EXIT, 1);
addCommand(exitCommand);
setCommandListener(this);
}
}
In the application descriptor I had UpdateJourney as the MIDlet, I changed it to HomeScreen and it worked.