Android Bluetooth Discovery does not log anything - java

I have been working on an app which needs to find some discoverable Bluetooth devices. I have followed guides and looked at answers on here and followed. However I cannot seem to get the phone to start scanning.
Here is the full activity code:
public class MainActivity extends AppCompatActivity {
private TextView scanningText;
private ListView scanningListView;
private Button scanningButton;
boolean scanComplete;
private final static int REQUEST_ENABLE_BT = 1;
private ArrayList<String> mDeviceList;
private BluetoothAdapter mBluetoothAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDeviceList = new ArrayList<>();
scanningButton = (Button) findViewById(R.id.scanningButton);
scanningText = (TextView) findViewById(R.id.scanningText);
scanningListView = (ListView) findViewById(R.id.scanningList);
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter == null) {
scanningText.setText("Your device does not support Bluetooth, Sorry!");
}
else if (!mBluetoothAdapter.isEnabled()) {
scanningText.setText("You need to enable bluetooth to use this app..");
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
// Register for broadcasts when a device is discovered.
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mReceiver, filter);
scanningButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
scanningText.setText("Scanning...");
mBluetoothAdapter.startDiscovery();
}
});
}
#Override
protected void onDestroy() {
unregisterReceiver(mReceiver);
super.onDestroy();
}
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
BluetoothDevice device = intent
.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
mDeviceList.add(device.getName() + "\n" + device.getAddress());
Log.i("BT", device.getName() + "\n" + device.getAddress());
scanningListView.setAdapter(new ArrayAdapter<>(context,
android.R.layout.simple_list_item_1, mDeviceList));
}
else {
Log.i("BT", "none"+ "");
}
}
};
}
When I check the android log console, there are no logs.
Thanks
Update:
I have moved startDiscovery to the onclick listener.
Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
if (pairedDevices.size() > 0) {
// There are paired devices. Get the name and address of each paired device.
for (BluetoothDevice device : pairedDevices) {
String deviceName = device.getName();
String deviceHardwareAddress = device.getAddress(); // MAC address
}
Log.i("found", pairedDevices + "");
}
The following check takes place when i press the scan button. I am told the device is not discovering by the toast.
scanningButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
scanningText.setText("Scanning...");
mBluetoothAdapter.startDiscovery();
if (mBluetoothAdapter.isDiscovering()) {
mBluetoothAdapter.isDiscovering();
Toast toast = Toast.makeText(getApplicationContext(), "discovering", Toast.LENGTH_LONG);
toast.show();
}
else {
Toast toast = Toast.makeText(getApplicationContext(), "not discovering", Toast.LENGTH_LONG);
toast.show();
}
}
});
Entire Log:
06-14 14:50:13.356 25211-25211/? E/Zygote: v2
06-14 14:50:13.356 25211-25211/? I/libpersona: KNOX_SDCARD checking this for 10319
06-14 14:50:13.356 25211-25211/? I/libpersona: KNOX_SDCARD not a persona
06-14 14:50:13.357 25211-25211/? E/Zygote: accessInfo : 0
06-14 14:50:13.361 25211-25211/? W/SELinux: SELinux selinux_android_compute_policy_index : Policy Index[1], Con:u:r:zygote:s0 SPD:SEPF_SECMOBILE_7.0_0006 RAM:SEPF_SECMOBILE_7.0_0005, [-1 -1 0 1 0 1]
06-14 14:50:13.362 25211-25211/? I/SELinux: SELinux: seapp_context_lookup: seinfo=untrusted, level=s0:c512,c768, pkgname=com.smartscan.app.smartscanapp
06-14 14:50:13.365 25211-25211/? I/art: Late-enabling -Xcheck:jni
06-14 14:50:13.408 25211-25211/com.smartscan.app.smartscanapp W/System: ClassLoader referenced unknown path: /data/app/com.smartscan.app.smartscanapp-2/lib/arm64
06-14 14:50:13.417 25211-25211/com.smartscan.app.smartscanapp I/InstantRun: Instant Run Runtime started. Android package is com.smartscan.app.smartscanapp, real application class is null.
06-14 14:50:13.607 25211-25211/com.smartscan.app.smartscanapp W/System: ClassLoader referenced unknown path: /data/app/com.smartscan.app.smartscanapp-2/lib/arm64
06-14 14:50:13.688 25211-25211/com.smartscan.app.smartscanapp W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter android.support.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
06-14 14:50:13.770 25211-25211/com.smartscan.app.smartscanapp I/found: [C1:20:21:40:9C:65, 8C:C8:CD:BB:95:28, C9:50:76:7B:89:F2, 54:53:ED:A3:B1:70, 88:A3:F2:BE:DE:42, C4:73:1E:02:1F:6B, E4:04:39:29:74:E6]
06-14 14:50:13.826 25211-25250/com.smartscan.app.smartscanapp I/OpenGLRenderer: Initialized EGL, version 1.4
06-14 14:50:13.880 25211-25211/com.smartscan.app.smartscanapp I/InputMethodManager: [IMM] startInputInner - mService.startInputOrWindowGainedFocus
06-14 14:50:22.465 25211-25211/com.smartscan.app.smartscanapp W/System: ClassLoader referenced unknown path: /system/framework/QPerformance.jar
06-14 14:50:22.465 25211-25211/com.smartscan.app.smartscanapp E/BoostFramework: BoostFramework() : Exception_1 = java.lang.ClassNotFoundException: Didn't find class "com.qualcomm.qti.Performance" on path: DexPathList[[],nativeLibraryDirectories=[/system/lib64, /vendor/lib64]]

Try adding those permissions in the manifest :
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
Also, it's always recommended to ask the user for permissions, so here you go :
if (Build.VERSION.SDK_INT >= 23 && ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
}
if(Build.VERSION.SDK_INT >= 23 && ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, 1);
}

You should start by adding logs at every steps.
Log.i("TAG", "Message")
Does your manifest file contains the appropriate permissions?
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
Next, it seems like you do not check if the bluetooth is enabled on the device. You should use an intent to do so.
if (!mBluetoothAdapter.isEnabled()) {
Intent enableBT = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBT, REQUEST_BLUETOOTH);
}

Related

Application keep crashing

I am a beginner android app user. i am trying to make a BLE scanner based on a online example. however my app keep crashing and not working at all. can anyone please help me identify the problem?
I have looked into various online solutions. the example i am following is this:
https://github.com/kaviles/BLE_Tutorials
this is my manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.ble_scanner">
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-feature android:name="android.hardware.bluetooth_le" android:required="true"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
here is my MainActivity:
public class MainActivity extends AppCompatActivity implements View.OnClickListener, AdapterView.OnItemClickListener {
private final static String TAG = MainActivity.class.getSimpleName();
public static final int REQUEST_ENABLE_BT = 1;
private HashMap<String, BTLE_Device> mBTDevicesHashMap;
private ArrayList<BTLE_Device> mBTDevicesArrayList;
private ListAdapter_BTLE_Devices adapter;
private Button btn_Scan;
private BroadcastReceiver_BTState mBTStateUpdateReceiver;
private Scanner_BTLE mBTLeScanner;
private static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
checkLocationPermission();
if(!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)){
Utils.toast(getApplicationContext(),"BLE not supported");
finish();
}
mBTStateUpdateReceiver = new BroadcastReceiver_BTState(getApplicationContext());
mBTLeScanner = new Scanner_BTLE(this,7500,-75);
mBTDevicesHashMap = new HashMap<>();
mBTDevicesArrayList = new ArrayList<>();
adapter = new ListAdapter_BTLE_Devices(this, R.layout.btle_device_list_item, mBTDevicesArrayList);
ListView listView = new ListView(this);
listView.setAdapter(adapter);
listView.setOnItemClickListener(this);
btn_Scan = (Button) findViewById(R.id.btn_scan);
((ScrollView) findViewById(R.id.scrollView)).addView(listView);
findViewById(R.id.btn_scan).setOnClickListener(this);
}
#Override
protected void onStart(){
super.onStart();
registerReceiver(mBTStateUpdateReceiver, new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED));
}
#Override
protected void onResume(){
super.onResume();
}
#Override
protected void onPause(){
super.onPause();
stopScan();
}
protected void onStop(){
super.onStop();
unregisterReceiver(mBTStateUpdateReceiver);
startScan();
}
#Override
protected void onDestroy(){
super.onDestroy();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data){
if (requestCode == REQUEST_ENABLE_BT){
if (resultCode == RESULT_OK){
Utils.toast(getApplicationContext(),"Bluetooth is ready to use");
}
else if (resultCode == RESULT_CANCELED){
Utils.toast(getApplicationContext(),"Please turn on Bluetooth");
}
}
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.btn_scan:
Utils.toast(getApplicationContext(),"Scan button pressed");
if(!mBTLeScanner.isScanning()){
startScan();
} else {
startScan();
}
break;
default:
break;
}
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
}
public void addDevice(BluetoothDevice device, int new_rssi) {
String address = device.getAddress();
if(!mBTDevicesHashMap.containsKey(address)){
BTLE_Device btle_device = new BTLE_Device(device);
btle_device.setRssi(new_rssi);
mBTDevicesHashMap.put(address, btle_device);
mBTDevicesArrayList.add(btle_device);
} else {
mBTDevicesHashMap.get(address).setRssi(new_rssi);
}
adapter.notifyDataSetChanged();
}
public void startScan(){
btn_Scan.setText("Scanning...");
mBTDevicesArrayList.clear();
mBTDevicesHashMap.clear();
adapter.notifyDataSetChanged();
mBTLeScanner.start();
}
public void stopScan() {
btn_Scan.setText("Scan Again");
mBTLeScanner.stop();
}
public boolean checkLocationPermission() {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
// Should we show an explanation?
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.ACCESS_FINE_LOCATION)) {
// Show an explanation to the user *asynchronously* -- don't block
// this thread waiting for the user's response! After the user
// sees the explanation, try again to request the permission.
new AlertDialog.Builder(this)
.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
//Prompt the user once explanation has been shown
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
}
})
.create()
.show();
} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
}
return false;
} else {
return true;
}
}
#Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_LOCATION: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted, yay! Do the
// location-related task you need to do.
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
onResume();
}
} else {
onDestroy();
}
return;
}
}
}
}
Here is the logcat:
2019-07-16 14:45:14.758 26071-26071/com.example.ble_scanner I/ple.ble_scanne: Not late-enabling -Xcheck:jni (already on)
2019-07-16 14:45:14.837 26071-26071/com.example.ble_scanner W/ple.ble_scanne: Unexpected CPU variant for X86 using defaults: x86
2019-07-16 14:45:14.935 26071-26079/com.example.ble_scanner E/ple.ble_scanne: Failed to send DDMS packet REAQ to debugger (-1 of 20): Broken pipe
2019-07-16 14:45:15.164 26071-26071/com.example.ble_scanner W/ple.ble_scanne: JIT profile information will not be recorded: profile file does not exits.
2019-07-16 14:45:15.166 26071-26071/com.example.ble_scanner I/chatty: uid=10096(com.example.ble_scanner) identical 10 lines
2019-07-16 14:45:15.166 26071-26071/com.example.ble_scanner W/ple.ble_scanne: JIT profile information will not be recorded: profile file does not exits.
2019-07-16 14:45:15.215 26071-26071/com.example.ble_scanner I/InstantRun: starting instant run server: is main process
2019-07-16 14:45:15.610 26071-26071/com.example.ble_scanner W/ple.ble_scanne: Accessing hidden method Landroid/view/View;->computeFitSystemWindows(Landroid/graphics/Rect;Landroid/graphics/Rect;)Z (light greylist, reflection)
2019-07-16 14:45:15.612 26071-26071/com.example.ble_scanner W/ple.ble_scanne: Accessing hidden method Landroid/view/ViewGroup;->makeOptionalFitsSystemWindows()V (light greylist, reflection)
2019-07-16 14:45:15.824 26071-26071/com.example.ble_scanner E/BluetoothAdapter: Bluetooth binder is null
2019-07-16 14:45:15.831 26071-26071/com.example.ble_scanner D/AndroidRuntime: Shutting down VM
2019-07-16 14:45:15.834 26071-26071/com.example.ble_scanner E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.ble_scanner, PID: 26071
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.ble_scanner/com.example.ble_scanner.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ScrollView.addView(android.view.View)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2913)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3048)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1808)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6669)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ScrollView.addView(android.view.View)' on a null object reference
at com.example.ble_scanner.MainActivity.onCreate(MainActivity.java:65)
at android.app.Activity.performCreate(Activity.java:7136)
at android.app.Activity.performCreate(Activity.java:7127)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1271)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2893)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3048) 
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78) 
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108) 
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1808) 
at android.os.Handler.dispatchMessage(Handler.java:106) 
at android.os.Looper.loop(Looper.java:193) 
at android.app.ActivityThread.main(ActivityThread.java:6669) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858) 
In your xml layout try to check if the id of ScrollView is "scrollView", if not change it to scrollView the same as how you initialize in this line.
((ScrollView) findViewById(R.id.scrollView)).addView(listView);
or check your xml layout if ScrollView widget exist.
It throws the null pointer Exception because it cannot bind the layout, the id maybe misspelled or there is no scrollview widget in your layout.
Thank you everyone for your suggestion. The issue is solved. this code has two issue for which it did not work.
1. ((ScrollView) findViewById(R.id.scrollView)).addView(listView);
in this line scrollView is the wrong ID name. it should be the ID of your scrollview which for my case is device_list. it was making the app crash.
second issue is that i didnot call call for the permission function which will not give the list of BLE devices for android 6+ devices.

Android NULL Pointer Exception and Fragment data transmission [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I am a beginner at android studio, I have a mission to redesign the app. I use the Fragment. But when I run my app, it has stopped and there is no error in my Gradle. I looked for many website to solve my question, but still have no idea.
I have some questions below.
How can I fix the java.lang.RuntimeException (NULL Pointer Exception) ?
09-30 02:59:56.574 17706-17706/? E/memtrack: Couldn't load memtrack module (No such file or directory)
09-30 02:59:56.574 17706-17706/? E/android.os.Debug: failed to load memtrack module: -2
09-30 02:59:56.996 17722-17722/? E/memtrack: Couldn't load memtrack module (No such file or directory)
09-30 02:59:56.996 17722-17722/? E/android.os.Debug: failed to load memtrack module: -2
09-30 02:59:57.090 17734-17734/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: tw.com.flag.parking22, PID: 17734
java.lang.RuntimeException: Unable to start activity ComponentInfo{tw.com.flag.parking22/tw.com.flag.parking22.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2325)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
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:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
at tw.com.flag.parking22.MainActivity.init(MainActivity.java:102)
at tw.com.flag.parking22.MainActivity.onCreate(MainActivity.java:71)
at android.app.Activity.performCreate(Activity.java:5990)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387) 
at android.app.ActivityThread.access$800(ActivityThread.java:151) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:135) 
at android.app.ActivityThread.main(ActivityThread.java:5254) 
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:903) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698) 
09-30 02:59:57.211 1160-1160/? E/EGL_emulation: tid 1160: eglCreateSyncKHR(1865): error 0x3004 (EGL_BAD_ATTRIBUTE)
09-30 03:02:15.409 2159-19872/com.google.android.gms E/Herrevad: [350] RemoteReportsRefreshChimeraService.a: want to send authenticated request, but no Google account on device
09-30 03:02:15.445 1998-2721/com.google.android.gms.persistent E/SQLiteLog: (2067) abort at 31 in [INSERT INTO pending_ops(source,tag,requires_charging,target_package,source_version,required_network_type,flex_time,target_class,runtime,retry_strategy,last_runtime,period,task_type,job_id,user_
09-30 03:02:15.445 1998-2721/com.google.android.gms.persistent E/SQLiteDatabase: Error inserting source=4 tag=NetworkReportService requires_charging=0 target_package=com.google.android.gms source_version=11509000 required_network_type=2 flex_time=3600000 target_class=com.google.android.gms.common.stats.net.NetworkReportService runtime=1506742923454 retry_strategy={"maximum_backoff_seconds":{"3600":0},"initial_backoff_seconds":{"30":0},"retry_policy":{"0":0}} last_runtime=0 period=7200000 task_type=1 job_id=-1 user_id=0
android.database.sqlite.SQLiteConstraintException: UNIQUE constraint failed: pending_ops.tag, pending_ops.target_class, pending_ops.target_package, pending_ops.user_id (code 2067)
at android.database.sqlite.SQLiteConnection.nativeExecuteForLastInsertedRowId(Native Method)
at android.database.sqlite.SQLiteConnection.executeForLastInsertedRowId(SQLiteConnection.java:782)
at android.database.sqlite.SQLiteSession.executeForLastInsertedRowId(SQLiteSession.java:788)
at android.database.sqlite.SQLiteStatement.executeInsert(SQLiteStatement.java:86)
at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1471)
at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1341)
at swi.a(:com.google.android.gms#11509280:208)
at sxo.a(:com.google.android.gms#11509280:64)
at sxp.handleMessage(:com.google.android.gms#11509280:29)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.os.HandlerThread.run(HandlerThread.java:61)
09-30 03:02:15.446 1998-2721/com.google.android.gms.persistent E/NetworkScheduler: Error persisting task: com.google.android.gms/.common.stats.net.NetworkReportService{u=0 tag="NetworkReportService" trigger=window{period=7200s,flex=3600s,earliest=5988s,latest=9588s} requirements=[NET_ANY] attributes=[PERSISTED,RECURRING] scheduled=2388s last_run=N/A jid=N/A status=PENDING retries=0}
09-30 03:02:15.474 1170-1578/? E/Drm: Failed to find drm plugin
09-30 03:02:15.563 2159-2680/com.google.android.gms E/Volley: [129] BasicNetwork.performRequest: Unexpected response code 307 for https://android.googleapis.com/nova/herrevad/network_quality_info
09-30 03:02:15.888 1998-2721/com.google.android.gms.persistent E/SQLiteLog: (2067) abort at 31 in [INSERT INTO pending_ops(source,tag,requires_charging,target_package,source_version,required_network_type,flex_time,target_class,runtime,retry_strategy,last_runtime,period,task_type,job_id,user_
09-30 03:02:15.888 1998-2721/com.google.android.gms.persistent E/SQLiteDatabase: Error inserting source=4 tag=AggregationTaskTag requires_charging=0 target_package=com.google.android.gms source_version=11509000 required_network_type=2 flex_time=600000 target_class=com.google.android.gms.checkin.EventLogService runtime=1506741123628 retry_strategy={"maximum_backoff_seconds":{"3600":0},"initial_backoff_seconds":{"30":0},"retry_policy":{"0":0}} last_runtime=0 period=1800000 task_type=1 job_id=-1 user_id=0
android.database.sqlite.SQLiteConstraintException: UNIQUE constraint failed: pending_ops.tag, pending_ops.target_class, pending_ops.target_package, pending_ops.user_id (code 2067)
at android.database.sqlite.SQLiteConnection.nativeExecuteForLastInsertedRowId(Native Method)
at android.database.sqlite.SQLiteConnection.executeForLastInsertedRowId(SQLiteConnection.java:782)
at android.database.sqlite.SQLiteSession.executeForLastInsertedRowId(SQLiteSession.java:788)
at android.database.sqlite.SQLiteStatement.executeInsert(SQLiteStatement.java:86)
at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1471)
at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1341)
at swi.a(:com.google.android.gms#11509280:208)
at sxo.a(:com.google.android.gms#11509280:64)
at sxp.handleMessage(:com.google.android.gms#11509280:29)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.os.HandlerThread.run(HandlerThread.java:61)
09-30 03:02:15.888 1998-2721/com.google.android.gms.persistent E/NetworkScheduler: Error persisting task: com.google.android.gms/.checkin.EventLogService{u=0 tag="AggregationTaskTag" trigger=window{period=1800s,flex=600s,earliest=1787s,latest=2387s} requirements=[NET_ANY] attributes=[PERSISTED,RECURRING] scheduled=587s last_run=N/A jid=N/A status=PENDING retries=0}
09-30 03:03:37.417 1170-1578/? E/audio_hw_generic: Error opening input stream format 1, channel_mask 0010, sample_rate 16000
09-30 03:30:15.406 2159-21157/com.google.android.gms E/Herrevad: [355] RemoteReportsRefreshChimeraService.a: want to send authenticated request, but no Google account on device
09-30 03:30:15.511 2159-21162/com.google.android.gms E/ZappConnFactory: Unable to bind to PlayStore
09-30 03:30:15.518 2159-21168/com.google.android.gms E/ZappLogOperation: Unable to bind to Phonesky
09-30 03:30:15.526 2159-21162/com.google.android.gms E/ZappConnFactory: Unable to bind to PlayStore
09-30 03:30:15.526 2159-21162/com.google.android.gms E/ZappConnFactory: Unable to bind to PlayStore
09-30 03:30:15.551 2159-2678/com.google.android.gms E/Volley: [127] BasicNetwork.performRequest: Unexpected response code 307 for https://android.googleapis.com/nova/herrevad/network_quality_info
09-30 03:30:15.572 1170-1578/? E/Drm: Failed to find drm plugin
09-30 03:30:22.524 2159-2159/com.google.android.gms E/ActivityThread: Service com.google.android.gms.chimera.GmsIntentOperationService has leaked ServiceConnection ctn#2f714ea6 that was originally bound here
android.app.ServiceConnectionLeaked: Service com.google.android.gms.chimera.GmsIntentOperationService has leaked ServiceConnection ctn#2f714ea6 that was originally bound here
at android.app.LoadedApk$ServiceDispatcher.<init>(LoadedApk.java:1077)
at android.app.LoadedApk.getServiceDispatcher(LoadedApk.java:971)
at android.app.ContextImpl.bindServiceCommon(ContextImpl.java:1774)
at android.app.ContextImpl.bindService(ContextImpl.java:1757)
at android.content.ContextWrapper.bindService(ContextWrapper.java:539)
at android.content.ContextWrapper.bindService(ContextWrapper.java:539)
at android.content.ContextWrapper.bindService(ContextWrapper.java:539)
at android.content.ContextWrapper.bindService(ContextWrapper.java:539)
at com.google.android.gms.chimera.container.zapp.ZappLogOperation.onHandleIntent(:com.google.android.gms#11509280:1)
at com.google.android.chimera.IntentOperation.onHandleIntent(:com.google.android.gms#11509280:2)
at bwy.run(:com.google.android.gms#11509280:10)
at bwv.run(:com.google.android.gms#11509280:14)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:818)
09-30 03:44:15.607 1998-2721/com.google.android.gms.persistent E/SQLiteLog: (2067) abort at 31 in [INSERT INTO pending_ops(source,tag,requires_charging,target_package,source_version,required_network_type,flex_time,target_class,runtime,retry_strategy,last_runtime,period,task_type,job_id,user_
09-30 03:44:15.607 1998-2721/com.google.android.gms.persistent E/SQLiteDatabase: Error inserting source=4 tag=AggregationTaskTag requires_charging=0 target_package=com.google.android.gms source_version=11509000 required_network_type=2 flex_time=600000 target_class=com.google.android.gms.checkin.EventLogService runtime=1506743055606 retry_strategy={"maximum_backoff_seconds":{"3600":0},"initial_backoff_seconds":{"30":0},"retry_policy":{"0":0}} last_runtime=0 period=1800000 task_type=1 job_id=-1 user_id=0
android.database.sqlite.SQLiteConstraintException: UNIQUE constraint failed: pending_ops.tag, pending_ops.target_class, pending_ops.target_package, pending_ops.user_id (code 2067)
at android.database.sqlite.SQLiteConnection.nativeExecuteForLastInsertedRowId(Native Method)
at android.database.sqlite.SQLiteConnection.executeForLastInsertedRowId(SQLiteConnection.java:782)
at android.database.sqlite.SQLiteSession.executeForLastInsertedRowId(SQLiteSession.java:788)
at android.database.sqlite.SQLiteStatement.executeInsert(SQLiteStatement.java:86)
at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1471)
at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1341)
at swi.a(:com.google.android.gms#11509280:208)
at sxo.a(:com.google.android.gms#11509280:64)
at sxp.handleMessage(:com.google.android.gms#11509280:29)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.os.HandlerThread.run(HandlerThread.java:61)
09-30 03:44:15.607 1998-2721/com.google.android.gms.persistent E/NetworkScheduler: Error persisting task: com.google.android.gms/.checkin.EventLogService{u=0 tag="AggregationTaskTag" trigger=window{period=1800s,flex=600s,earliest=1199s,latest=1799s} requirements=[NET_ANY] attributes=[PERSISTED,RECURRING] scheduled=0s last_run=N/A jid=N/A status=PENDING retries=0}
09-30 03:44:15.637 2159-21184/com.google.android.gms E/Herrevad: [371] RemoteReportsRefreshChimeraService.a: want to send authenticated request, but no Google account on device
09-30 03:44:15.755 2159-2676/com.google.android.gms E/Volley: [126] BasicNetwork.performRequest: Unexpected response code 307 for https://android.googleapis.com/nova/herrevad/network_quality_info
09-30 03:46:13.425 1171-1171/? E/installd: eof
09-30 03:46:13.425 1171-1171/? E/installd: failed to read size
Here is the main activity code
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewPager =(ViewPager) findViewById(R.id.pager);
PagerAdapter padapter = new PagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(padapter);
//--------------------------------------------------------------------
init();
Action();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
if(newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
}
else {
}
}
private void init(){
System.out.println("start---------------------");
textView_userIDVal = (TextView) findViewById(R.id.textView_userIDVal);
textView_parkingNoVal = (TextView) findViewById(R.id.textView_parkingNoVal);
textView_pillarNoVal = (TextView) findViewById(R.id.textView_pillarNoVal);
textView_colorVal = (TextView) findViewById(R.id.textView_colorVal);
imageView = (ImageView) findViewById(R.id.imageView);
button_space = (Button) findViewById(R.id.button_space);
button_scan = (Button) findViewById(R.id.button_scan);
button_find = (Button) findViewById(R.id.button_find);
simpleDateFormat = new SimpleDateFormat("MM/dd 'at' HH");
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
userID = Build.SERIAL;
//-------------error start next----------------
textView_userIDVal.setText("User ID : " + userID);
}
if(ContextCompat.checkSelfPermission(this, android.Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.CAMERA}, 200);
}
sharedPreferences = getSharedPreferences("Data", 0);
if(sharedPreferences.contains("parkingNum") && sharedPreferences.contains("time")) {
parkingNumtmp = sharedPreferences.getString("parkingNum", "");
textView_parkingNoVal.setText("Parking No. : " + parkingNumtmp + "\t(" + sharedPreferences.getString("time", "") + ")");
}
builder = new AlertDialog.Builder(this);
builder.setCancelable(false);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
builder_timeout = new AlertDialog.Builder(this);
builder_timeout.setTitle("REMIND");
builder_timeout.setMessage("Do you find your car ?");
builder_timeout.setCancelable(false);
builder_timeout.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
try {
json_data = new JSONObject();
json_data.put("MT", "timeout");
json_data.put("PlaceMac", parkingNumtmp);
json_data.put("UserMac", userID);
json_write = new JSONObject();
json_write.put("Data", json_data);
json_write.put("Read", false);
isCloseScreen = false;
} catch (JSONException e) {
e.printStackTrace();
}
thread = new Thread(TCP);
thread.start();
timer_count = 0;
startFlag = false;
}
});
builder_timeout.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
maxTime = 10;
maxTime = maxTime / 2;
timer_count = 0;
startFlag = true;
}
});
}
private void Action(){
button_space.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
json_data = new JSONObject();
json_data.put("MT", "count");
json_write = new JSONObject();
json_write.put("Data", json_data);
json_write.put("Read", true);
//System.out.println(json_write + "\n");
} catch (JSONException e) {
e.printStackTrace();
}
thread = new Thread(TCP);
thread.start();
/*builder.setTitle("INFORMATION");
builder.setMessage("All : " + "\nNow : " );
AlertDialog alertDialog = builder.create();
alertDialog.show();*/
}
});
button_scan.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, ScanActivity.class);
startActivityForResult(intent, REQUEST_CODE);
}
});
button_find.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(parkingNumtmp != null) {
try {
maxTime = 10;
json_data = new JSONObject();
json_data.put("MT", "search");
json_data.put("PlaceMac", parkingNumtmp);
json_data.put("UserMac", userID);
json_write = new JSONObject();
json_write.put("Data", json_data);
json_write.put("Read", true);
//System.out.println(json_write + "\n");
} catch (JSONException e) {
e.printStackTrace();
}
Toast.makeText(getApplicationContext(), "Don't close the screen before you find your car ! ", Toast.LENGTH_LONG).show();
thread = new Thread(TCP);
thread.start();
}
else {
builder.setTitle("WARNING");
builder.setMessage("Please scan QRcode first!");
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == REQUEST_CODE && resultCode == RESULT_OK) {
if(data != null) {
final Barcode barcode = data.getParcelableExtra("barcode");
parkingNumtmp = barcode.displayValue;
Date date = new Date();
final String time = simpleDateFormat.format(date);
sharedPreferences.edit().putString("parkingNum", parkingNumtmp).putString("time", time).commit();
textView_parkingNoVal.post(new Runnable() {
#Override
public void run() {
textView_parkingNoVal.setText("Parking No. : " + parkingNumtmp + "\t(" + time +")");
}
});
}
}
}
About Fragment. Is there any setting I have to do when I receive data form sever?
I want to put the received data to TextView in the another view .
Your init() function is probably try to find views inside fragments in view pager. However, at that moment, the fragments are not inflated yet, so your views in the activity are null and trying to do operation on them gives NPE. You should use onCreateView() of Fragment classes to find those views. Then you may notify main activity via callback mechanism.
For example, create FirstFragment as follows:
public class FirstFragment extends Fragment {
private OnFirstFragmentReadyListener callback;
#Override
public void onAttach(Context context) {
super.onAttach(context);
// This makes sure that the container activity has implemented the callback.
try {
callback = (OnFirstFragmentReadyListener) context;
} catch (ClassCastException e) {
throw new ClassCastException(context.toString()
+ " must implement OnFirstFragmentReadyListener");
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_first, container, false);
return rootView;
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// Notify the parent activity that the fragment is inflated.
callback.onFirstFragmentReady();
}
public interface OnFirstFragmentReadyListener {
void onFirstFragmentReady();
}
}
Let the layout of FirstFragment as follows (referenced above as fragment_first):
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/first_label"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</RelativeLayout>
Assume we created two more similar fragment classes named as SecondFragment and ThirdFragment. Then the activity should be like this:
public class MainActivity extends AppCompatActivity implements FirstFragment.OnFirstFragmentReadyListener,
SecondFragment.OnSecondFragmentReadyListener, ThirdFragment.OnThirdFragmentReadyListener {
...
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewPager =(ViewPager) findViewById(R.id.pager);
PagerAdapter pagerAdapter = new PagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(pagerAdapter);
// Don't call these functions here, spread them into callbacks.
// init();
// Action();
}
#Override
public void onFirstFragmentReady() {
TextView firstTextView = (TextView) findViewById(R.id.first_label);
...
// Now you have the views from FirstFragment instance.
// You can now call setText() or setOnClickListener() here.
}
#Override
public void onSecondFragmentReady() {
TextView secondTextView = (TextView) findViewById(R.id.second_label);
...
// Now you have the views from SecondFragment instance.
// You can now call setText() or setOnClickListener() here.
}
#Override
public void onThirdFragmentReady() {
TextView thirdTextView = (TextView) findViewById(R.id.third_label);
...
// Now you have the views from ThirdFragment instance.
// You can now call setText() or setOnClickListener() here.
}
}
Although this code works, this may not be the best way. I think it is better to do operations on views like setting texts or assigning OnClickListeners in fragments itself. If you need to notify a fragment after an action happened in the parent activity, you can implement public methods inside fragments and you can call them from the parent activity when needed.
In fragment you should call the function in onCreateView function(reason as mention by #Mehmed) which is something like below:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.your_fragment, container, false);
//all findViewById;
TextView yourTextView = (Text)view.findViewById(R.id.yourTextView);
//here call for your function
init();
// any other function goes here
return view;
}

No Permissions Pop Up Anymore?

So I am creating an app that requests permission to a users google account. I used mine to test and so I gave it permission and then removed it to see if it would ask for it again. It was still using the token it got so I deleted the app from my phone and reinstalled it. I didn't change any code and now all of a sudden it only shows the account page (to select which account) and then once I press ok, nothing shows to give it permission. In my run console I get the following:
$ adb push C:\Users\James Singleton\AndroidStudioProjects\ChffrAPI\app\build\outputs\apk\app-debug.apk /data/local/tmp/com.example.jamessingleton.chffrapi
$ adb shell pm install -r "/data/local/tmp/com.example.jamessingleton.chffrapi"
pkg: /data/local/tmp/com.example.jamessingleton.chffrapi
Success
$ adb shell am start -n "com.example.jamessingleton.chffrapi/com.example.jamessingleton.chffrapi.MainActivity" -a android.intent.action.MAIN -c android.intent.category.LAUNCHER
Connected to process 25029 on device samsung-sm_g935v-0d75cc0d
E/Zygote: v2
W/SELinux: Function: selinux_compare_spd_ram, index[1], priority [2], priority version is VE=SEPF_SECMOBILE_6.0.1_0010
E/Zygote: accessInfo : 0
I/libpersona: KNOX_SDCARD checking this for 10269
I/libpersona: KNOX_SDCARD not a persona
W/SELinux: SELinux: seapp_context_lookup: seinfo=default, level=s0:c512,c768, pkgname=com.example.jamessingleton.chffrapi
I/art: Late-enabling -Xcheck:jni
D/ActivityThread: Added TimaKeyStore provider
D/RelationGraph: garbageCollect()
I/InjectionManager: Inside getClassLibPath + mLibMap{0=, 1=}
D/ContextRelationManager: ContextRelationManager() : FEATURE_ENABLED=true
W/ResourcesManager: getTopLevelResources: /data/app/com.example.jamessingleton.chffrapi-2/base.apk / 1.0 running in com.example.jamessingleton.chffrapi rsrc of package com.example.jamessingleton.chffrapi
D/ResourcesManager: For user 0 new overlays fetched Null
I/InjectionManager: Inside getClassLibPath caller
W/System: ClassLoader referenced unknown path: /data/app/com.example.jamessingleton.chffrapi-2/lib/arm64
W/art: Failed to open zip archive '/system/framework/dpmapi.jar': I/O Error
W/System: ClassLoader referenced unknown path: /data/app/com.example.jamessingleton.chffrapi-2/lib/arm64
I/FirebaseInitProvider: FirebaseApp initialization unsuccessful
D/InjectionManager: InjectionManager
D/InjectionManager: fillFeatureStoreMap com.example.jamessingleton.chffrapi
I/InjectionManager: Constructor com.example.jamessingleton.chffrapi, Feature store :{}
I/InjectionManager: featureStore :{}
D/RelationGraph: garbageCollect()
W/ResourcesManager: getTopLevelResources: /data/app/com.example.jamessingleton.chffrapi-2/base.apk / 1.0 running in com.example.jamessingleton.chffrapi rsrc of package com.example.jamessingleton.chffrapi
W/ResourcesManager: getTopLevelResources: /data/app/com.example.jamessingleton.chffrapi-2/base.apk / 1.0 running in com.example.jamessingleton.chffrapi rsrc of package com.example.jamessingleton.chffrapi
W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter android.support.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
W/ResourcesManager: getTopLevelResources: /data/app/com.google.android.gms-2/base.apk / 1.0 running in com.example.jamessingleton.chffrapi rsrc of package com.google.android.gms
I/InjectionManager: Inside getClassLibPath caller
D/ResourcesManager: For user 0 new overlays fetched Null
D/ChimeraCfgMgr: Reading stored module config
W/System: ClassLoader referenced unknown path: /data/user/0/com.google.android.gms/app_chimera/m/00000007/n/arm64-v8a
D/ChimeraFileApk: Primary ABI of requesting process is arm64-v8a
D/ChimeraFileApk: Classloading successful. Optimized code found.
D/Activity: performCreate Call Injection manager
I/InjectionManager: dispatchOnViewCreated > Target : com.example.jamessingleton.chffrapi.WifivsDataDialog isFragment :true
D/ViewRootImpl: #1 mView = com.android.internal.policy.PhoneWindow$DecorView{3c6164c V.E...... R.....I. 0,0-0,0}
D/OpenGLRenderer: Use EGL_SWAP_BEHAVIOR_PRESERVED: true
D/SecWifiDisplayUtil: Metadata value : SecSettings2
I/InjectionManager: dispatchOnViewCreated > Target : com.example.jamessingleton.chffrapi.MainActivity isFragment :false
D/ViewRootImpl: #1 mView = com.android.internal.policy.PhoneWindow$DecorView{ead695 I.E...... R.....ID 0,0-0,0}
I/Adreno: QUALCOMM build : c0299d7, I241dab1ec4
Build Date : 01/25/16
OpenGL ES Shader Compiler Version: XE031.06.00.05
Local Branch :
Remote Branch : refs/tags/AU_LINUX_ANDROID_LA.HB.1.1.1.06.00.01.063.117
Remote Branch : NONE
Reconstruct Branch : NOTHING
D/libEGL: eglInitialize EGLDisplay = 0x7f62194188
I/OpenGLRenderer: Initialized EGL, version 1.4
I/InjectionManager: dispatchCreateOptionsMenu :com.example.jamessingleton.chffrapi.MainActivity
I/InjectionManager: dispatchPrepareOptionsMenu :com.example.jamessingleton.chffrapi.MainActivity
W/DisplayListCanvas: DisplayListCanvas is started on unbinded RenderNode (without mOwningView)
D/libGLESv1: DTS_GLAPI : DTS is not allowed for Package : com.example.jamessingleton.chffrapi
W/DisplayListCanvas: DisplayListCanvas is started on unbinded RenderNode (without mOwningView)
D/ViewRootImpl: MSG_RESIZED_REPORT: ci=Rect(0, 0 - 0, 0) vi=Rect(0, 0 - 0, 0) or=1
D/ViewRootImpl: MSG_RESIZED_REPORT: ci=Rect(0, 96 - 0, 0) vi=Rect(0, 96 - 0, 0) or=1
I/Timeline: Timeline: Activity_idle id: android.os.BinderProxy#7d80ce5 time:2598350
D/ViewRootImpl: ViewPostImeInputStage processPointer 0
D/ViewRootImpl: ViewPostImeInputStage processPointer 1
I/WifiManager: isAllowWifiWarning() -> isCscWifiEnableWarning : false ChinaNalSecurityType :
D/ViewRootImpl: #3 mView = null
E/ViewRootImpl: sendUserActionEvent() mView == null
D/ViewRootImpl: MSG_RESIZED: ci=Rect(0, 96 - 0, 1128) vi=Rect(0, 96 - 0, 1128) or=1
D/ViewRootImpl: ViewPostImeInputStage processPointer 0
D/ViewRootImpl: ViewPostImeInputStage processPointer 1
I/Timeline: Timeline: Activity_launch_request id:android time:2603031
D/ViewRootImpl: MSG_RESIZED: ci=Rect(0, 96 - 0, 0) vi=Rect(0, 96 - 0, 0) or=1
V/ActivityThread: updateVisibility : ActivityRecord{65ce05f token=android.os.BinderProxy#7d80ce5 {com.example.jamessingleton.chffrapi/com.example.jamessingleton.chffrapi.MainActivity}} show : true
I/Timeline: Timeline: Activity_idle id: android.os.BinderProxy#7d80ce5 time:2605454
V/ActivityThread: updateVisibility : ActivityRecord{65ce05f token=android.os.BinderProxy#7d80ce5 {com.example.jamessingleton.chffrapi/com.example.jamessingleton.chffrapi.MainActivity}} show : false
Application terminated.
Nothing changed in my code so I have no idea why I am not getting the pop up to allow me to give the app permission.
Here is my MainActivity
public class MainActivity extends AppCompatActivity {
Context mContext = MainActivity.this;
private AccountManager mAccountManager;
private AuthPreferences authPreferences;
EditText emailText;
TextView responseView;
ProgressBar progressBar;
static final String API_KEY = "";
static final String API_URL = "https://api.comma.ai/v1/auth/?access_token=";
static final String ClientId = "45471411055-m902j8c6jo4v6mndd2jiuqkanjsvcv6j.apps.googleusercontent.com";
static final String ClientSecret = "";
static final String SCOPE = "https://www.googleapis.com/auth/userinfo.email";
private static final int AUTHORIZATION_CODE = 1993;
private static final int ACCOUNT_CODE = 1601;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
responseView = (TextView) findViewById(R.id.responseView);
emailText = (EditText) findViewById(R.id.emailText);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
final Context context = this;
mAccountManager = AccountManager.get(this);
authPreferences = new AuthPreferences(this);
SignInButton signInButton = (SignInButton) findViewById(R.id.sign_in_button);
signInButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (authPreferences.getUser() != null && authPreferences.getToken() != null) {
doCoolAuthenticatedStuff();
new RetrieveFeedTask().execute();
} else {
chooseAccount();
}
}
});
// Button queryButton = (Button) findViewById(R.id.queryButton);
//
// queryButton.setOnClickListener(new View.OnClickListener() {
// #Override
// public void onClick(View v) {
// if (isNetworkAvailable() == true) {
// new RetrieveFeedTask().execute();
// Intent intent = new Intent(context, NavDrawerActivity.class);
// startActivity(intent);
// } else {
// Toast.makeText(MainActivity.this, "No Network Service, please check your WiFi or Mobile Data Connection", Toast.LENGTH_SHORT).show();
// }
// }
// });
SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
boolean dontShowDialog = sharedPref.getBoolean("DONT_SHOW_DIALOG", false);
if (!dontShowDialog) {
WifivsDataDialog myDiag = new WifivsDataDialog();
myDiag.show(getFragmentManager(), "WiFi");
myDiag.setCancelable(false);
}
}
private void doCoolAuthenticatedStuff() {
Log.e("AuthApp", authPreferences.getToken());
}
private void chooseAccount() {
Intent intent = AccountManager.newChooseAccountIntent(null, null, new String[]{"com.google"}, false, null, null, null, null);
startActivityForResult(intent, ACCOUNT_CODE);
}
public void requestToken() {
Account userAccount = null;
String user = authPreferences.getUser();
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.GET_ACCOUNTS) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
for (Account account : mAccountManager.getAccountsByType(GoogleAuthUtil.GOOGLE_ACCOUNT_TYPE)) {
if (account.name.equals(user)) {
userAccount = account;
break;
}
}
mAccountManager.getAuthToken(userAccount, "oauth2:" + SCOPE, null, this, new OnTokenAcquired(), null);
}
private void invalidateToken() {
AccountManager mAccountManager = AccountManager.get(this);
mAccountManager.invalidateAuthToken("com.google", authPreferences.getToken());
authPreferences.setToken(null);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == AUTHORIZATION_CODE) {
requestToken();
} else if (requestCode == ACCOUNT_CODE) {
String accountName = data.getStringExtra(AccountManager.KEY_ACCOUNT_NAME);
authPreferences.setUser(accountName);
// invalidate old tokens which might be cached. we want a fresh
// one, which is guaranteed to work
invalidateToken();
requestToken();
}
}
}
public class OnTokenAcquired implements AccountManagerCallback<Bundle> {
#Override
public void run(AccountManagerFuture<Bundle> result) {
try {
Bundle bundle = result.getResult();
Intent launch = (Intent) bundle.get(AccountManager.KEY_INTENT);
if (launch != null) {
startActivityForResult(launch, AUTHORIZATION_CODE);
} else {
String token = bundle.getString(AccountManager.KEY_AUTHTOKEN);
authPreferences.setToken(token);
System.out.println(authPreferences);
doCoolAuthenticatedStuff();
}
} catch (Exception e) {
Log.e("ERROR", e.getMessage(), e);
}
}
}
public boolean isNetworkAvailable() {
ConnectivityManager cm = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = cm.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
Log.e("Network Testing", "Available");
return true;
}
Log.e("Network Testing", "Not Available");
return false;
}
class RetrieveFeedTask extends AsyncTask<Void, Void, String> {
private Exception exception;
protected void onPreExecute() {
progressBar.setVisibility(View.VISIBLE);
responseView.setText("");
}
protected String doInBackground(Void... urls) {
// Do some validation here
try {
URL url = new URL(API_URL + authPreferences.getToken());
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setRequestProperty("User-Agent", "Mozilla/5.0");
int responseCode = urlConnection.getResponseCode();
System.out.println("GET Response code:" + responseCode);
// urlConnection.addRequestProperty("client_id", ClientId);
// urlConnection.addRequestProperty("client_secret", ClientSecret);
// urlConnection.setRequestProperty("Authorization", "JWT " + authPreferences);
Log.i("URL", url.toString());
try {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
StringBuilder stringBuilder = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line).append("\n");
}
bufferedReader.close();
return stringBuilder.toString();
} finally {
urlConnection.disconnect();
}
} catch (Exception e) {
Log.e("ERROR", e.getMessage(), e);
return null;
}
}
protected void onPostExecute(String response) {
if (response == null) {
response = "THERE WAS AN ERROR";
}
progressBar.setVisibility(View.GONE);
Log.i("INFO", response);
responseView.setText(response);
//
// TODO: check this.exception
// TODO: do something with the feed
// try {
// JSONObject object = (JSONObject) new JSONTokener(response).nextValue();
// String requestID = object.getString("requestId");
// int likelihood = object.getInt("likelihood");
// JSONArray photos = object.getJSONArray("photos");
// .
// .
// .
// .
// } catch (JSONException e) {
// e.printStackTrace();
// }
}
}}
And then here is my AuthPreferences.java
public class AuthPreferences {
private static final String KEY_USER = "user";
private static final String KEY_TOKEN = "token";
private SharedPreferences preferences;
public AuthPreferences(Context context) {
preferences = context
.getSharedPreferences("auth", Context.MODE_PRIVATE);
}
public void setUser(String user) {
Editor editor = preferences.edit();
editor.putString(KEY_USER, user);
editor.commit();
}
public void setToken(String password) {
Editor editor = preferences.edit();
editor.putString(KEY_TOKEN, password);
editor.commit();
}
public String getUser() {
return preferences.getString(KEY_USER, null);
}
public String getToken() {
return preferences.getString(KEY_TOKEN, null);
}
}

Android - App crashes only on first launch but works the second time

I am having a problem with my Android Flashlight App. The app crashes when I try to press the home button of the device while the app is opened then resuming (by clicking the app icon on home screen not recent apps button). After I terminate the app from the recent apps list then opening again, it does not crash anymore using the same instructions above.
Please see code below.
public class MainActivity extends Settings {
public Camera camera;
public Camera.Parameters parameters;
public ImageButton flashLightButton;
boolean isFlashLightOn = false;
MediaPlayer mySound;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
flashLightButton = (ImageButton)findViewById(R.id.flashlight_button);
flashLightButton.setOnClickListener(new FlashOnOffListener());
registerReceiver(mBatInfoReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
mySound = MediaPlayer.create(this, R.raw.balloon_snap);
if (isFlashSupported()) {
camera = Camera.open();
parameters = camera.getParameters();
} else {
showNoFlashAlert();
}
Settings.active = false;
//super.onCreate(savedInstanceState);
//Set layout we created
//setContentView(R.layout.activity_main);
//Register the receiver which triggers event
//when battery charge is changed
}
public void settings(View view)
{
Intent intent = new Intent(MainActivity.this, Settings.class);
startActivity(intent);
this.finish();
}
private BroadcastReceiver mBatInfoReceiver = new BroadcastReceiver() {
#Override
//When Event is published, onReceive method is called
public void onReceive(Context c, Intent i) {
//Get Battery %
int level = i.getIntExtra("level", 0);
//Find the progressbar creating in main.xml
ProgressBar pb = (ProgressBar) findViewById(R.id.progressbar);
//Set progress level with battery % value
pb.setProgress(level);
//Find textview control created in main.xml
TextView tv = (TextView) findViewById(R.id.textfield);
//Set TextView with text
tv.setText("" + Integer.toString(level) + "");
}
};
public class FlashOnOffListener implements View.OnClickListener{
SharedPreferences sharedPrefs = getSharedPreferences("VibrateSettings", MODE_PRIVATE);
Boolean vibration = sharedPrefs.getBoolean("VibrateSet", false);
SharedPreferences sharedPrefs2 = getSharedPreferences("SoundSettings", MODE_PRIVATE);
Boolean sound = sharedPrefs2.getBoolean("SoundSet", false);
#Override
public void onClick(View v) {
if(isFlashLightOn){
flashLightButton.setImageResource(R.drawable.flashlight_off);
parameters.setFlashMode(Parameters.FLASH_MODE_OFF);
camera.setParameters(parameters);
camera.stopPreview();
isFlashLightOn = false;
if(vibration == true){
// Get instance of Vibrator from current Context
Vibrator vib = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
// Vibrate for 400 milliseconds
vib.vibrate(20);
}
else {
// Get instance of Vibrator from current Context
Vibrator vib = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
// Vibrate for 400 milliseconds
vib.vibrate(00);
}
if (sound == true){
mySound.start();
}
}else{
flashLightButton.setImageResource(R.drawable.flashlight_on);
parameters.setFlashMode(Parameters.FLASH_MODE_TORCH);
camera.setParameters(parameters);
camera.startPreview();
isFlashLightOn = true;
if(vibration == true){
// Get instance of Vibrator from current Context
Vibrator vib = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
// Vibrate for 400 milliseconds
vib.vibrate(20);
}
else {
// Get instance of Vibrator from current Context
Vibrator vib = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
// Vibrate for 400 milliseconds
vib.vibrate(00);
}
if (sound == true){
mySound.start();
}
}
}
}
private void showNoFlashAlert() {
new AlertDialog.Builder(this)
.setMessage("Your device hardware does not support flashlight!")
.setIcon(android.R.drawable.ic_dialog_alert).setTitle("Error")
.setPositiveButton("Ok", new OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
finish();
}
}).show();
}
private boolean isFlashSupported() {
PackageManager pm = getPackageManager();
return pm.hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);
}
#Override
protected void onDestroy() {
if(camera != null){
camera.stopPreview();
camera.release();
camera = null;
}
super.onDestroy();
}}
AndroidManifest.xml
<uses-sdk
android:minSdkVersion="14"
android:targetSdkVersion="19" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />
<uses-permission android:name="android.permission.BATTERY_STATS"/>
<uses-permission android:name="android.permission.BROADCAST_STICKY"/>
<uses-permission android:name="android.permission.VIBRATE"/>
<application
android:allowBackup="true"
android:icon="#drawable/btn_switch_on"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".Settings"
android:label="#string/app_name">
</activity>
</application>
logcat
E/AndroidRuntime(22941): FATAL EXCEPTION: main
E/AndroidRuntime(22941): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.johncarlo.flashlight/com.example.johncarlo.flashlight.MainActivity}: java.lang.RuntimeException: Fail to connect to camera service
E/AndroidRuntime(22941): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2186)
E/AndroidRuntime(22941): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2236)
E/AndroidRuntime(22941): at android.app.ActivityThread.access$600(ActivityThread.java:145)
E/AndroidRuntime(22941): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1238)
E/AndroidRuntime(22941): at android.os.Handler.dispatchMessage(Handler.java:99)
E/AndroidRuntime(22941): at android.os.Looper.loop(Looper.java:137)
E/AndroidRuntime(22941): at android.app.ActivityThread.main(ActivityThread.java:5099)
E/AndroidRuntime(22941): at java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime(22941): at java.lang.reflect.Method.invoke(Method.java:511)
E/AndroidRuntime(22941): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:803)
E/AndroidRuntime(22941): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:570)
E/AndroidRuntime(22941): at dalvik.system.NativeStart.main(Native Method)
E/AndroidRuntime(22941): Caused by: java.lang.RuntimeException: Fail to connect to camera service
E/AndroidRuntime(22941): at android.hardware.Camera.native_setup(Native Method)
E/AndroidRuntime(22941): at android.hardware.Camera.<init>(Camera.java:365)
E/AndroidRuntime(22941): at android.hardware.Camera.open(Camera.java:338)
E/AndroidRuntime(22941): at com.example.johncarlo.flashlight.MainActivity.onCreate(MainActivity.java:49)
E/AndroidRuntime(22941): at android.app.Activity.performCreate(Activity.java:5117)
E/AndroidRuntime(22941): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1081)
E/AndroidRuntime(22941): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2150)
E/AndroidRuntime(22941): ... 11 more
W/ActivityManager( 786): Force finishing activity com.example.johncarlo.flashlight/.MainActivity
Remove below line from onCreate and write it in onResume and it might not crash after doing so.
#Override
protected void onResume() {
super.onResume();
registerReceiver(mBatInfoReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
}

Request location in android

I have this code to request someones location in Android, can someone explain to me why it isnt working, After the location request it sets two EditText fields as he latitude and Longitude values
package com.datapost.location;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.widget.EditText;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationServices;
public class Main extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
private GoogleApiClient mGoogleApiClient;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Create an instance of GoogleAPIClient.
if (mGoogleApiClient == null) {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
onStart();
}
protected void onStart() {
mGoogleApiClient.connect();
super.onStart();
}
protected void onStop() {
mGoogleApiClient.disconnect();
super.onStop();
}
#Override
public void onConnected(Bundle bundle) {
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
Location mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
mGoogleApiClient);
if (mLastLocation != null) {
EditText mLatitudeText = (EditText) findViewById(R.id.lat);
EditText mLongitudeText = (EditText) findViewById(R.id.lon);
String s = String.valueOf(mLastLocation.getLatitude());
String f = String.valueOf(mLastLocation.getLongitude());
mLatitudeText.setText(s);
mLongitudeText.setText(f);
}
}
#Override
public void onConnectionSuspended(int i) {
return;
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
connectionResult.getErrorCode();
return;
}
}
I dont know why it wont work, tried everything seems like a basicjob to do however it just does not want to work, do I have to have an API key or something, do I need one just to get a persons location from their phone.
Any help appreciated with this
I can also post the error mess message I got
Error
06-13 15:54:56.311 11320-11320/com.datapost.location W/System: ClassLoader referenced unknown path: /data/app/com.datapost.location-1/lib/x86_64
06-13 15:54:56.339 11320-11320/com.datapost.location I/FirebaseInitProvider: FirebaseApp initialization unsuccessful
06-13 15:54:56.906 11320-11320/com.datapost.location W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter android.support.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
06-13 15:54:57.032 11320-11366/com.datapost.location D/OpenGLRenderer: Use EGL_SWAP_BEHAVIOR_PRESERVED: true
[ 06-13 15:54:57.041 11320:11320 D/ ]
HostConnection::get() New Host Connection established 0x7f6d81a1a480, tid 11320
[ 06-13 15:54:57.093 11320:11366 D/ ]
HostConnection::get() New Host Connection established 0x7f6d85b50840, tid 11366
06-13 15:54:57.109 11320-11366/com.datapost.location I/OpenGLRenderer: Initialized EGL, version 1.4
I changed the code to this for that If statement
#Override
public void onConnected(Bundle bundle) {
if(ContextCompat.checkSelfPermission(this,android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
Location mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
mGoogleApiClient);
if (mLastLocation != null) {
EditText mLatitudeText = (EditText) findViewById(R.id.lat);
EditText mLongitudeText = (EditText) findViewById(R.id.lon);
String s = String.valueOf(mLastLocation.getLatitude());
String f = String.valueOf(mLastLocation.getLongitude());
mLatitudeText.setText(s);
mLongitudeText.setText(f);
}
}
}
You need to enable geoLocation API from your google console and create a key and use that key in your app menifest like this :
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="YOUR_API_KEY"/>
also check for runtime permission for android M+

Categories