We are writing an android based Application that tracks several Mobilephone sensors now I tried compiling the code when suddenly this happend
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.max.pswi, PID: 14291
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.max.pswi/com.example.max.pswi.MainActivity}:
java.lang.ClassNotFoundException: Didn't find class "com.example.max.pswi.MainActivity" on path: DexPathList[[zip file "/data/app/com.example.max.pswi-1/base.apk"],nativeLibraryDirectories=[/vendor/lib, /system/lib]]
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2555)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2767)
at android.app.ActivityThread.access$900(ActivityThread.java:177)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1449)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:5951)
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:1388)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1183)
Caused by: java.lang.ClassNotFoundException: Didn't find class "com.example.max.pswi.MainActivity" on path: DexPathList[[zip file "/data/app/com.example.max.pswi-1/base.apk"],nativeLibraryDirectories=[/vendor/lib, /system/lib]]
at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)
at java.lang.ClassLoader.loadClass(ClassLoader.java:511)
at java.lang.ClassLoader.loadClass(ClassLoader.java:469)
at android.app.Instrumentation.newActivity(Instrumentation.java:1079)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2545)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2767)
at android.app.ActivityThread.access$900(ActivityThread.java:177)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1449)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:5951)
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:1388)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1183)
Suppressed: java.lang.ClassNotFoundException: com.example.max.pswi.MainActivity
at java.lang.Class.classForName(Native Method)
at java.lang.BootClassLoader.findClass(ClassLoader.java:781)
at java.lang.BootClassLoader.loadClass(ClassLoader.java:841)
at java.lang.ClassLoader.loadClass(ClassLoader.java:504)
... 13 more
Caused by: java.lang.NoClassDefFoundError: Class not found using the boot class loader; no stack available
I have no Idea why this error occurs
Im programming on Android Studio
Heres the MainActivity-Code that creates the error:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
setContentView(R.layout.activity_main);
int currentVersionCode = 0;
try {
currentVersionCode = this.getPackageManager().getPackageInfo(this.getPackageName(), 0).versionCode;
} catch (PackageManager.NameNotFoundException e1) {
e1.printStackTrace();
}
final ImageButton export = (ImageButton) findViewById(R.id.export);
final ImageButton clear = (ImageButton) findViewById(R.id.clear);
final ToggleButton toggle = (ToggleButton) findViewById(R.id.anaus);
final ImageButton settingsBtn = (ImageButton) findViewById(R.id.settings);
final ImageButton aktualisieren = (ImageButton) findViewById(R.id.aktualisieren);
final ListView liste = (ListView)findViewById(R.id.infos);
if (CheckIfServiceIsRunning())
toggle.setChecked(true);
Boolean status = CheckIfServiceIsRunning();
aktualisieren.setVisibility(View.VISIBLE);
export.setVisibility(View.VISIBLE);
toggle.setVisibility(View.VISIBLE);
settingsBtn.setVisibility(View.VISIBLE);
/* clear.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SensorManager.getInstance().clearValues(SensorManager.getInstance().getContext());
}
});
export.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SensorManager.getInstance().exportValues(SensorManager.getInstance().getContext());
}
});
settingsBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent("android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS");
startActivity(intent);
}
});
toggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
Boolean status = CheckIfServiceIsRunning();
ComponentName cn = new ComponentName(getApplicationContext(), NLService.class);
String flat = Settings.Secure.getString(getApplicationContext().getContentResolver(), "enabled_notification_listeners");
final boolean enabled = (flat != null && flat.contains(cn.flattenToString()));
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
// The toggle is enabled
if (!enabled) {
final AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this).create();
alertDialog.setCancelable(false);
alertDialog.setTitle("Notificationlistener aktivieren");
alertDialog.setMessage("Bitte aktivieren sie den Notificationlistener für die App PSWI");
alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "Aktivieren", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
alertDialog.cancel();
Intent intent = new Intent("android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS");
startActivity(intent);
Intent i = new Intent(getApplicationContext(), MainService.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
getApplicationContext().startService(i);
status = true;
}
});
alertDialog.setButton(AlertDialog.BUTTON_NEGATIVE, "zurueck", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
alertDialog.cancel();
}
});
alertDialog.show();
} else {
Intent i = new Intent(getApplicationContext(), MainService.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
getApplicationContext().startService(i);
status = true;
}
} else {
// The toggle is disabled
Intent i = new Intent(getApplicationContext(), MainService.class);
getApplicationContext().stopService(i);
status = false;
}
}
});
// SensorManager.getInstance().populateListView(liste);
settings = PreferenceManager.getDefaultSharedPreferences(this);
if (settings.getBoolean("first_start", true)) {
// set initial version code, set first_start true and create ID
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("first_start", false);
editor.putBoolean("SMSSensor:ObserverStarted", false);
editor.putString("CallSensor:lastIntent", null);
editor.putBoolean("serviceStarted", false);
editor.putString("version", "" + currentVersionCode);
editor.putString("ID", ""
+ ((TelephonyManager) getApplicationContext()
.getSystemService(TELEPHONY_SERVICE))
.getDeviceId().hashCode());
editor.apply();
}
// getLoaderManager().initLoader(0, null, (android.app.LoaderManager.LoaderCallbacks<Cursor>) this);
*/
}
I would be glad if someone could take a look at this I'm getting desperate
Have you declared this MainActivity in AndroidManifest file?
Check AndroidManifest.xml
You should see your activity within the application tag like so:
<activity android:name="com.example.max.pswi.MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
Related
I'm creating a tic tac toe game using android studio but my application keeps crashing
i tested this app on my emulator and copied the logcat here!
here's my code
public class LoginActivity extends AppCompatActivity {
private TextView twoPlayerLabel;
private TextView optionsLabel;
private MediaPlayer intro;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
twoPlayerLabel = (TextView) findViewById(R.id.two_player_label);
optionsLabel = (TextView) findViewById(R.id.options_label);
}
public void twoPlayer(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
LayoutInflater inflater = getLayoutInflater();
final View layout = inflater.inflate(R.layout.two_player_options, null);
final Intent twoPlayerLocal = new Intent(LoginActivity.this, TwoPlayerActivityLocal.class);
final TextView playerOneName = (TextView) layout.findViewById(R.id.player_one);
final TextView playerTwoName = (TextView) layout.findViewById(R.id.player_two);
final RadioButton localGame = (RadioButton) layout.findViewById(R.id.local_game);
final RadioButton bluetoothGame = (RadioButton) layout.findViewById(R.id.bluetooth_game);
final RadioButton oMarker = (RadioButton) layout.findViewById(R.id.o_marker);
final RadioButton xMarker = (RadioButton) layout.findViewById(R.id.x_marker);
localGame.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
playerTwoName.setVisibility(View.VISIBLE);
oMarker.setVisibility(View.VISIBLE);
xMarker.setVisibility(View.VISIBLE);
}
});
bluetoothGame.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
playerTwoName.setVisibility(View.GONE);
oMarker.setVisibility(View.GONE);
xMarker.setVisibility(View.GONE);
}
});
oMarker.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
oMarker.setBackgroundResource(R.drawable.tic_tac_toe_o_black);
xMarker.setBackgroundResource(R.drawable.tic_tac_toe_x);
}
});
xMarker.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
xMarker.setBackgroundResource(R.drawable.tic_tac_toe_x_black);
oMarker.setBackgroundResource(R.drawable.tic_tac_toe_o);
}
});
builder.setView(layout)
.setTitle("Two Player Game Options")
.setPositiveButton("Start", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
if (localGame.isChecked()) {
if ((playerOneName.getText().length() > 0) && (playerTwoName.getText().length() > 0)) {
if (oMarker.isChecked()) {
Player playerOne = new Player(playerOneName.getText().toString(), 'o', 0);
Player playerTwo = new Player(playerTwoName.getText().toString(), 'x', 0);
twoPlayerLocal.putExtra("playerOne", playerOne);
twoPlayerLocal.putExtra("playerTwo", playerTwo);
twoPlayerLocal.putExtra("isTurn", playerOne.getPlayerMarker());
startActivity(twoPlayerLocal);
} else if (xMarker.isChecked()) {
Player playerOne = new Player(playerOneName.getText().toString(), 'x', 0);
Player playerTwo = new Player(playerTwoName.getText().toString(), 'o', 0);
twoPlayerLocal.putExtra("playerOne", playerOne);
twoPlayerLocal.putExtra("playerTwo", playerTwo);
startActivity(twoPlayerLocal);
}
else {
Toast.makeText(LoginActivity.this, "Please select the starting marker", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(LoginActivity.this, "Please enter a name for the players", Toast.LENGTH_SHORT).show();
}
} else if (bluetoothGame.isChecked()) {
Intent bluetoothIntent = new Intent(LoginActivity.this, TwoPlayerActivityBluetooth.class);
String playerOne = null;
if (playerOneName.getText().length() > 0) {
playerOne = playerOneName.getText().toString();
bluetoothIntent.putExtra("playerOne", playerOne);
startActivity(bluetoothIntent);
} else {
Toast.makeText(LoginActivity.this, "Please enter a player name", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(LoginActivity.this, "Please Select a game type", Toast.LENGTH_SHORT).show();
}
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
}
});
// Create the AlertDialog object and return it
builder.create().show();
}
#Override
public void onBackPressed() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Are you sure you want to quit the game?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
builder.create().show();
}
}
and this is logcat!
2019-09-04 22:44:37.659 17644-17644/? I/ir.puzzle.douz: Not late-enabling -Xcheck:jni (already on) 2019-09-04 22:44:37.697 17644-17644/? E/ir.puzzle.douz: Unknown bits set in runtime_flags: 0x8000 2019-09-04 22:44:37.699 17644-17644/? W/ir.puzzle.douz: Unexpected CPU variant for X86 using defaults: x86 2019-09-04 22:44:38.014 17644-17670/ir.puzzle.douz D/libEGL: Emulator has host GPU support, qemu.gles is set to 1. 2019-09-04 22:44:38.036 17644-17670/ir.puzzle.douz W/libc: Unable to set property "qemu.gles" to "1": connection failed; errno=13 (Permission denied) 2019-09-04 22:44:38.023 17644-17644/ir.puzzle.douz W/RenderThread: type=1400 audit(0.0:157): avc: denied { write } for name="property_service" dev="tmpfs" ino=6800 scontext=u:r:untrusted_app:s0:c134,c256,c512,c768 tcontext=u:object_r:property_socket:s0 tclass=sock_file permissive=0 2019-09-04 22:44:38.082 17644-17670/ir.puzzle.douz D/libEGL: loaded /vendor/lib/egl/libEGL_emulation.so 2019-09-04 22:44:38.092 17644-17670/ir.puzzle.douz D/libEGL: loaded /vendor/lib/egl/libGLESv1_CM_emulation.so 2019-09-04 22:44:38.129 17644-17670/ir.puzzle.douz D/libEGL: loaded /vendor/lib/egl/libGLESv2_emulation.so 2019-09-04 22:44:38.272 17644-17644/ir.puzzle.douz W/ir.puzzle.douz: Accessing hidden method Landroid/view/View;->computeFitSystemWindows(Landroid/graphics/Rect;Landroid/graphics/Rect;)Z (greylist, reflection, allowed) 2019-09-04 22:44:38.273 17644-17644/ir.puzzle.douz W/ir.puzzle.douz: Accessing hidden method Landroid/view/ViewGroup;->makeOptionalFitsSystemWindows()V (greylist, reflection, allowed) 2019-09-04 22:44:38.412 17644-17644/ir.puzzle.douz D/AndroidRuntime: Shutting down VM 2019-09-04 22:44:38.416 17644-17644/ir.puzzle.douz E/AndroidRuntime: FATAL EXCEPTION: main
Process: ir.puzzle.douz, PID: 17644
java.lang.RuntimeException: Unable to start activity ComponentInfo{ir.puzzle.douz/ir.puzzle.douz.view.LoginActivity}: java.lang.IndexOutOfBoundsException: index=0 out of bounds (limit=0, nb=4)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3270)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3409)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2016)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7356)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
Caused by: java.lang.IndexOutOfBoundsException: index=0 out of bounds (limit=0, nb=4)
at java.nio.Buffer.checkIndex(Buffer.java:564)
at java.nio.DirectByteBuffer.getInt(DirectByteBuffer.java:570)
at android.graphics.fonts.FontFileUtil.analyzeStyle(FontFileUtil.java:94)
at android.graphics.fonts.Font$Builder.build(Font.java:364)
at android.graphics.Typeface$Builder.build(Typeface.java:596)
at android.graphics.Typeface.createFromAsset(Typeface.java:960)
at ir.puzzle.douz.view.LoginActivity.onCreate(LoginActivity.java:35)
at android.app.Activity.performCreate(Activity.java:7802)
at android.app.Activity.performCreate(Activity.java:7791)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1299)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3245)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3409)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2016)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7356)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
i can't figure out where's the problem of this code that always gets force-closed! can you tell me which part of code is problematic? and how can i fix it?
I'm working on a term project and I'm new to java and android app development. I have experience in other programming languages, though. I'm trying to reverse engineer an app to make it able to connect and send data via bluetooth. I want to make a list with all the available bluetooth devices, a button to turn on/off bluetooth, one for making the phone discoverable for other devices and another to search for unpaired devices. But every time I add an OnClickListener to the onCreate method, the app crashes before it opens. Could anyone help me out?
The source code for the app I am trying to modify can be found here:
https://github.com/pazaan/600SeriesAndroidUploader
Here is the part that seems to makes it crash:
lvNewDevices.setOnItemClickListener(MainActivity.this);
btnONOFF.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.d(TAG, "onClick: enabling/disabling bluetooth.");
enableDisableBT();
}
});
btnStartConnection.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startConnection();
}
});
btnSend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
byte[] bytes = etSend.getText().toString().getBytes(Charset.defaultCharset());
mBluetoothConnection.write(bytes);
}
});
And here is all of OnCreate:
#Override
public void onCreate(Bundle savedInstanceState) {
Log.i(TAG, "onCreate called");
super.onCreate(savedInstanceState);
Button btnONOFF = (Button) findViewById(R.id.btnONOFF);
btnEnableDisable_Discoverable = (Button) findViewById(R.id.btnDiscoverable_on_off);
lvNewDevices = (ListView) findViewById(R.id.lvNewDevices);
mBTDevices = new ArrayList<>();
btnStartConnection = (Button) findViewById(R.id.btnStartConnection);
//Broadcasts when bond state changes (ie:pairing)
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
registerReceiver(mBroadcastReceiver4, filter);
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
//FUCKUP:
lvNewDevices.setOnItemClickListener(MainActivity.this);
btnONOFF.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.d(TAG, "onClick: enabling/disabling bluetooth.");
enableDisableBT();
}
});
btnStartConnection.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startConnection();
}
});
btnSend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
byte[] bytes = etSend.getText().toString().getBytes(Charset.defaultCharset());
mBluetoothConnection.write(bytes);
}
});
mRealm = Realm.getDefaultInstance();
RealmResults<PumpStatusEvent> data = mRealm.where(PumpStatusEvent.class)
.findAllSorted("eventDate", Sort.DESCENDING);
if (data.size() > 0)
dataStore.setLastPumpStatus(data.first());
setContentView(R.layout.activity_main);
PreferenceManager.getDefaultSharedPreferences(getBaseContext()).registerOnSharedPreferenceChangeListener(this);
prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
if (!prefs.getBoolean(getString(R.string.preference_eula_accepted), false)) {
stopCgmService();
}
// setup preferences
configurationStore.setPollInterval(Long.parseLong(prefs.getString("pollInterval", Long.toString(MedtronicCnlIntentService.POLL_PERIOD_MS))));
configurationStore.setLowBatteryPollInterval(Long.parseLong(prefs.getString("lowBatPollInterval", Long.toString(MedtronicCnlIntentService.LOW_BATTERY_POLL_PERIOD_MS))));
configurationStore.setReducePollOnPumpAway(prefs.getBoolean("doublePollOnPumpAway", false));
chartZoom = Integer.parseInt(prefs.getString("chartZoom", "3"));
configurationStore.setMmolxl(prefs.getBoolean("mmolxl", false));
configurationStore.setMmolxlDecimals(prefs.getBoolean("mmolDecimals", false));
// Disable battery optimization to avoid missing values on 6.0+
// taken from https://github.com/NightscoutFoundation/xDrip/blob/master/app/src/main/java/com/eveningoutpost/dexdrip/Home.java#L277L298
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
final String packageName = getPackageName();
final PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
if (!pm.isIgnoringBatteryOptimizations(packageName)) {
Log.d(TAG, "Requesting ignore battery optimization");
try {
// ignoring battery optimizations required for constant connection
// to peripheral device - eg CGM transmitter.
final Intent intent = new Intent();
intent.setAction(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
intent.setData(Uri.parse("package:" + packageName));
startActivity(intent);
} catch (ActivityNotFoundException e) {
Log.d(TAG, "Device does not appear to support battery optimization whitelisting!");
}
}
}
LocalBroadcastManager.getInstance(this).registerReceiver(
statusMessageReceiver,
new IntentFilter(MedtronicCnlIntentService.Constants.ACTION_STATUS_MESSAGE));
LocalBroadcastManager.getInstance(this).registerReceiver(
new UpdatePumpReceiver(),
new IntentFilter(MedtronicCnlIntentService.Constants.ACTION_UPDATE_PUMP));
mEnableCgmService = Eula.show(this, prefs);
IntentFilter batteryIntentFilter = new IntentFilter();
batteryIntentFilter.addAction(Intent.ACTION_BATTERY_LOW);
batteryIntentFilter.addAction(Intent.ACTION_BATTERY_CHANGED);
batteryIntentFilter.addAction(Intent.ACTION_BATTERY_OKAY);
registerReceiver(batteryReceiver, batteryIntentFilter);
IntentFilter usbIntentFilter = new IntentFilter();
usbIntentFilter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED);
usbIntentFilter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
usbIntentFilter.addAction(MedtronicCnlIntentService.Constants.ACTION_USB_PERMISSION);
registerReceiver(usbReceiver, usbIntentFilter);
LocalBroadcastManager.getInstance(this).registerReceiver(
usbReceiver,
new IntentFilter(MedtronicCnlIntentService.Constants.ACTION_NO_USB_PERMISSION));
LocalBroadcastManager.getInstance(this).registerReceiver(
usbReceiver,
new IntentFilter(MedtronicCnlIntentService.Constants.ACTION_USB_REGISTER));
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
if (toolbar != null) {
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
getSupportActionBar().setElevation(0);
getSupportActionBar().setTitle("Nightscout");
}
final PrimaryDrawerItem itemSettings = new PrimaryDrawerItem()
.withName("Settings")
.withIcon(GoogleMaterial.Icon.gmd_settings)
.withSelectable(false);
final PrimaryDrawerItem itemRegisterUsb = new PrimaryDrawerItem()
.withName("Registered devices")
.withIcon(GoogleMaterial.Icon.gmd_usb)
.withSelectable(false);
final PrimaryDrawerItem itemStopCollecting = new PrimaryDrawerItem()
.withName("Stop collecting data")
.withIcon(GoogleMaterial.Icon.gmd_power_settings_new)
.withSelectable(false);
final PrimaryDrawerItem itemGetNow = new PrimaryDrawerItem()
.withName("Read data now")
.withIcon(GoogleMaterial.Icon.gmd_refresh)
.withSelectable(false);
final PrimaryDrawerItem itemUpdateProfile = new PrimaryDrawerItem()
.withName("Update pump profile")
.withIcon(GoogleMaterial.Icon.gmd_insert_chart)
.withSelectable(false);
final PrimaryDrawerItem itemClearLog = new PrimaryDrawerItem()
.withName("Clear log")
.withIcon(GoogleMaterial.Icon.gmd_clear_all)
.withSelectable(false);
final PrimaryDrawerItem itemCheckForUpdate = new PrimaryDrawerItem()
.withName("Check for App update")
.withIcon(GoogleMaterial.Icon.gmd_update)
.withSelectable(false);
assert toolbar != null;
new DrawerBuilder()
.withActivity(this)
.withAccountHeader(new AccountHeaderBuilder()
.withActivity(this)
.withHeaderBackground(R.drawable.drawer_header)
.build()
)
.withTranslucentStatusBar(false)
.withToolbar(toolbar)
.withActionBarDrawerToggle(true)
.withSelectedItem(-1)
.addDrawerItems(
itemSettings,
//itemUpdateProfile, // TODO - re-add when we to add Basal Profile Upload
itemRegisterUsb,
itemCheckForUpdate,
itemClearLog,
itemGetNow,
itemStopCollecting
)
.withOnDrawerItemClickListener(new Drawer.OnDrawerItemClickListener() {
#Override
public boolean onItemClick(View view, int position, IDrawerItem drawerItem) {
if (drawerItem.equals(itemSettings)) {
openSettings();
} else if (drawerItem.equals(itemRegisterUsb)) {
openUsbRegistration();
} else if (drawerItem.equals(itemStopCollecting)) {
mEnableCgmService = false;
stopCgmService();
finish();
} else if (drawerItem.equals(itemGetNow)) {
// It was triggered by user so start reading of data now and not based on last poll.
sendStatus("Requesting poll now...");
startCgmService(System.currentTimeMillis() + 1000);
} else if (drawerItem.equals(itemClearLog)) {
clearLogText();
} else if (drawerItem.equals(itemCheckForUpdate)) {
checkForUpdateNow();
}
return false;
}
})
.build();
mTextViewLog = (TextView) findViewById(R.id.textview_log);
mScrollView = (ScrollView) findViewById(R.id.scrollView);
mScrollView.setSmoothScrollingEnabled(true);
mChart = (GraphView) findViewById(R.id.chart);
// disable scrolling at the moment
mChart.getViewport().setScalable(false);
mChart.getViewport().setScrollable(false);
mChart.getViewport().setYAxisBoundsManual(true);
mChart.getViewport().setMinY(80);
mChart.getViewport().setMaxY(120);
mChart.getViewport().setXAxisBoundsManual(true);
final long now = System.currentTimeMillis(),
left = now - chartZoom * 60 * 60 * 1000;
mChart.getViewport().setMaxX(now);
mChart.getViewport().setMinX(left);
// due to bug in GraphView v4.2.1 using setNumHorizontalLabels reverted to using v4.0.1 and setOnXAxisBoundsChangedListener is n/a in this version
/*
mChart.getViewport().setOnXAxisBoundsChangedListener(new Viewport.OnXAxisBoundsChangedListener() {
#Override
public void onXAxisBoundsChanged(double minX, double maxX, Reason reason) {
double rightX = mChart.getSeries().get(0).getHighestValueX();
hasZoomedChart = (rightX != maxX || rightX - chartZoom * 60 * 60 * 1000 != minX);
}
});
*/
mChart.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
if (!mChart.getSeries().isEmpty() && !mChart.getSeries().get(0).isEmpty()) {
double rightX = mChart.getSeries().get(0).getHighestValueX();
mChart.getViewport().setMaxX(rightX);
mChart.getViewport().setMinX(rightX - chartZoom * 60 * 60 * 1000);
}
hasZoomedChart = false;
return true;
}
});
mChart.getGridLabelRenderer().setNumHorizontalLabels(6);
// due to bug in GraphView v4.2.1 using setNumHorizontalLabels reverted to using v4.0.1 and setHumanRounding is n/a in this version
// mChart.getGridLabelRenderer().setHumanRounding(false);
mChart.getGridLabelRenderer().setLabelFormatter(
new DefaultLabelFormatter() {
DateFormat mFormat = new SimpleDateFormat("HH:mm", Locale.US); // 24 hour format forced to fix label overlap
#Override
public String formatLabel(double value, boolean isValueX) {
if (isValueX) {
return mFormat.format(new Date((long) value));
} else {
return MainActivity.strFormatSGV(value);
}
}
}
);
}
Here is the logcat output:
09-26 12:38:19.826 6324-6324/? I/art: Late-enabling -Xcheck:jni
09-26 12:38:20.157 6324-6324/info.nightscout.android E/Fabric: Failure onPreExecute()
java.lang.IllegalArgumentException: Fabric could not be initialized, API key missing from AndroidManifest.xml. Add the following tag to your Application element
<meta-data android:name="io.fabric.ApiKey" android:value="YOUR_API_KEY"/>
at io.fabric.sdk.android.services.common.ApiKey.logErrorOrThrowException(ApiKey.java:110)
at io.fabric.sdk.android.services.common.ApiKey.getValue(ApiKey.java:61)
at com.crashlytics.android.core.CrashlyticsCore.onPreExecute(CrashlyticsCore.java:219)
at com.crashlytics.android.core.CrashlyticsCore.onPreExecute(CrashlyticsCore.java:207)
at io.fabric.sdk.android.InitializationTask.onPreExecute(InitializationTask.java:44)
at io.fabric.sdk.android.services.concurrency.AsyncTask.executeOnExecutor(AsyncTask.java:611)
at io.fabric.sdk.android.services.concurrency.PriorityAsyncTask.executeOnExecutor(PriorityAsyncTask.java:43)
at io.fabric.sdk.android.Kit.initialize(Kit.java:69)
at io.fabric.sdk.android.Fabric.initializeKits(Fabric.java:440)
at io.fabric.sdk.android.Fabric.init(Fabric.java:384)
at io.fabric.sdk.android.Fabric.setFabric(Fabric.java:342)
at io.fabric.sdk.android.Fabric.with(Fabric.java:313)
at info.nightscout.android.UploaderApplication.onCreate(UploaderApplication.java:32)
at android.app.Instrumentation.callApplicationOnCreate(Instrumentation.java:1046)
at android.app.ActivityThread.handleBindApplication(ActivityThread.java:5402)
at android.app.ActivityThread.-wrap2(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1541)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6123)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:757)
09-26 12:38:20.202 6324-6379/info.nightscout.android E/Fabric: Error dealing with settings
java.lang.IllegalArgumentException: Fabric could not be initialized, API key missing from AndroidManifest.xml. Add the following tag to your Application element
<meta-data android:name="io.fabric.ApiKey" android:value="YOUR_API_KEY"/>
at io.fabric.sdk.android.services.common.ApiKey.logErrorOrThrowException(ApiKey.java:110)
at io.fabric.sdk.android.services.common.ApiKey.getValue(ApiKey.java:61)
at io.fabric.sdk.android.services.settings.Settings.initialize(Settings.java:78)
at io.fabric.sdk.android.Onboarding.retrieveSettingsData(Onboarding.java:124)
at io.fabric.sdk.android.Onboarding.doInBackground(Onboarding.java:99)
at io.fabric.sdk.android.Onboarding.doInBackground(Onboarding.java:45)
at io.fabric.sdk.android.InitializationTask.doInBackground(InitializationTask.java:63)
at io.fabric.sdk.android.InitializationTask.doInBackground(InitializationTask.java:28)
at io.fabric.sdk.android.services.concurrency.AsyncTask$2.call(AsyncTask.java:311)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:428)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
at java.lang.Thread.run(Thread.java:761)
09-26 12:38:20.252 6324-6324/info.nightscout.android 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
09-26 12:38:20.349 6324-6324/info.nightscout.android I/MainActivity: onCreate called
09-26 12:38:20.652 6324-6324/info.nightscout.android D/AndroidRuntime: Shutting down VM
09-26 12:38:20.652 6324-6324/info.nightscout.android E/AndroidRuntime: FATAL EXCEPTION: main
Process: info.nightscout.android, PID: 6324
java.lang.RuntimeException: Unable to start activity ComponentInfo{info.nightscout.android/info.nightscout.android.medtronic.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.view.View.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2659)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2724)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1473)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6123)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:757)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.view.View.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at info.nightscout.android.medtronic.MainActivity.onCreate(MainActivity.java:349)
at android.app.Activity.performCreate(Activity.java:6672)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1140)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2612)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2724)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1473)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6123)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:757)
Move the code setContentView(R.layout.activity_main);
under the super.onCreate(savedInstanceState);
you are mapping the views before adding layout in your code.
your onCreate() should be
#Override
public void onCreate(Bundle savedInstanceState) {
Log.i(TAG, "onCreate called");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Do mapping all views
Your Error log is showing you your solution. The project is using Fabric API. So naturally you need to add Fabric API key to your project.
Do as suggested in Error log. Add following line in Android Manifest.
<meta-data android:name="io.fabric.ApiKey" android:value="YOUR_API_KEY"/>
For your API key, make a project using Fabric account and get your API key.
Please help! When I run my program everything works fine when I go to the second activity, but when I go back to the first it comes up with an error. Here is the full error message:
Process: com.example.android.lifeofcrime, PID: 2826
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=42, result=0, data=null} to activity {com.example.android.lifeofcrime/com.example.android.lifeofcrime.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'int android.content.Intent.getIntExtra(java.lang.String, int)' on a null object reference
at android.app.ActivityThread.deliverResults(ActivityThread.java:4053)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:4096)
at android.app.ActivityThread.-wrap20(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1516)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'int android.content.Intent.getIntExtra(java.lang.String, int)' on a null object reference
at com.example.android.lifeofcrime.MainActivity.onActivityResult(MainActivity.java:63)
at android.app.Activity.dispatchActivityResult(Activity.java:6917)
at android.app.ActivityThread.deliverResults(ActivityThread.java:4049)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:4096)
at android.app.ActivityThread.-wrap20(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1516)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
Here is the code for the first activity:
public class MainActivity extends AppCompatActivity {
int test = 5;
TextView money;
int testReturn2 = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
money = (TextView) findViewById (R.id.money);
setupWorkButton();
}
public void setupWorkButton() {
Button workButton = (Button) findViewById(R.id.workButton);
workButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, workScreen.class);
intent.putExtra("testing", test);
startActivityForResult(intent, 42);
}
});
}
// Gets called when the activity started finishes
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-Generate method stub
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case 42:
testReturn2 = data.getIntExtra("the answer", 0);
money.setText("" + testReturn2);
break;
}
}
}
And here is the code for the second activity:
public class workScreen extends AppCompatActivity {
int test;
int testReturn = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_work_screen);
Intent intent = getIntent();
test = intent.getIntExtra("testing", 0);
TextView displayTest = (TextView) findViewById(R.id.intView);
displayTest.setText("" + test);
setupCharacterButton();
}
public void setupCharacterButton() {
Button characterButton = (Button) findViewById(R.id.characterButton);
characterButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
testReturn = test * 2;
intent.putExtra("the answer", testReturn);
finish();
}
});
}
}
Your intent == null. Seems like you forgot to set the activity result in your second activity:
setResult(Activity.RESULT_OK, intent);
put this code before you finish the 2nd Activity
hi I am using google license checker on my app it works on API 19 and below but crashes on lollipop. I saw the code that has to be add to my license check code but I don't know where to put this code or what should I edit. here is my code
log:
java.lang.IllegalArgumentException: Service Intent must be explicit: Intent { act=com.android.vending.licensing.ILicensingService }
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2298)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
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:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Caused by: java.lang.IllegalArgumentException: Service Intent must be explicit: Intent { act=com.android.vending.licensing.ILicensingService }
at android.app.ContextImpl.validateServiceIntent(ContextImpl.java:1674)
at android.app.ContextImpl.bindServiceCommon(ContextImpl.java:1773)
at android.app.ContextImpl.bindService(ContextImpl.java:1751)
at android.content.ContextWrapper.bindService(ContextWrapper.java:538)
at com.google.android.vending.licensing.LicenseChecker.checkAccess(LicenseChecker.java:150)
at appinventor.ai_drsalmanshah165.Clinical_Examination.Splash.doCheck(Splash.java:103)
at appinventor.ai_drsalmanshah165.Clinical_Examination.Splash.onCreate(Splash.java:51)
at android.app.Activity.performCreate(Activity.java:5933)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2251)
... 10 more
Java code:
public class Splash extends Activity {
MyLicenseCheckerCallback mLicenseCheckerCallback;
LicenseChecker mChecker;
byte[] SALT = new byte[] {
my salt no. };
//Handler mHandler;
String BASE64_PUBLIC_KEY="MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAoxvDF3HGQtrRch14wCPN6nAxasak8X4shJM6bCumNS+6xRXTnRZOSyAvHNa1145KlE/i1sy/";
Context mContext;
IBinder serviceBinder;
String deviceId;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.splash);
mLicenseCheckerCallback = new MyLicenseCheckerCallback();
deviceId = Secure.getString(getContentResolver(), Secure.ANDROID_ID);
// Construct the LicenseChecker with a policy.
mChecker = new LicenseChecker(
this, (Policy) new ServerManagedPolicy(Splash.this, new AESObfuscator(SALT, getPackageName(), deviceId)),
BASE64_PUBLIC_KEY);
doCheck();
}
private class MyLicenseCheckerCallback implements LicenseCheckerCallback {
#Override
public void allow(int reason) {
// TODO Auto-generated method stub
if (isFinishing()) {
// Don't update UI if Activity is finishing.
return;
}
// Toast.makeText(Splash.this, "License Verified", Toast.LENGTH_SHORT).show();
Intent intent=new Intent(Splash.this,Home.class);
startActivity(intent);
finish();
// Should allow user access.
// so do nothing
}
#Override
public void dontAllow(int reason) {
// TODO Auto-generated method stub
if (isFinishing()) {
// Don't update UI if Activity is finishing.
return;
}
// Toast.makeText(Splash.this, "License Verification Failed", Toast.LENGTH_SHORT).show();
createDialog();
}
#Override
public void applicationError(int errorCode) {
// TODO Auto-generated method stub
}
}
#Override
protected void onDestroy() {
super.onDestroy();
mChecker.onDestroy();
}
private void doCheck() {
// mCheckLicenseButton.setEnabled(false);
setProgressBarIndeterminateVisibility(true);
/// mStatusText.setText(R.string.checking_license);
mChecker.checkAccess(mLicenseCheckerCallback);
}
public void createDialog(){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("PIRACY WARNING");
builder.setMessage("This application is not licensed. Please purchase it from Android Market. If you received this message in error, please contact Support.");
builder.setPositiveButton("Buy Now", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent marketIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(
"http://market.android.com/details?id=" + getPackageName()));
startActivity(marketIntent);
}
});
builder.setNegativeButton("Quit", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
}
and here is the other code which I got that this can solve my problem. but don't know where to put it.
Intent serviceIntent = new Intent(
new String(Base64.decode("Y29tLmFuZHJvaWQudmVuZGluZy5saWNlbnNpbmcuSUxpY2Vuc2luZ1NlcnZpY2U=")));
serviceIntent.setPackage("com.android.vending");
boolean bindResult = mContext
.bindService(
serviceIntent,
this, // ServiceConnection.
Context.BIND_AUTO_CREATE);
Waiting for an official solution, the current solution consists in patching Google's LicenseChecker class
com.google.android.vending.licensing.LicenseChecker.checkAccess(LicenseChecker.java:150)
like this:
new String(
- Base64.decode("Y29tLmFuZHJvaWQudmVuZGluZy5saWNlbnNpbmcuSUxpY2Vuc2luZ1NlcnZpY2U="))),
+ Base64.decode("Y29tLmFuZHJvaWQudmVuZGluZy5saWNlbnNpbmcuSUxpY2Vuc2luZ1NlcnZpY2U=")))
+ .setPackage("com.android.vending"), // this fix the 'IllegalArgumentException: Service Intent must be explicit'
this, // ServiceConnection.
Adding package name with statement setPackage("com.android.vending") makes the Intent explicit, i.e., 'safe' (as requested by Android Lollipop )
Note:
Please pay attention as after modifying LicenseChecker class you must change the min sdk version from 3 to 4 (thanks russellhoff)
Source:
https://code.google.com/p/android/issues/detail?id=78505#c19
I have been following this tutorial: AndroidHive - working with Camera API to try and enable taking photos in my app. However, I'm getting an error once I press my "take photo button".
LogCat:
09-16 11:04:00.539 19561-19561/au.gov.nsw.shellharbour.saferroadsshellharbour D/Dob_in_a_Hoon_photos﹕ Failed to create Dob_in_a_Hoon_photos directory
09-16 11:04:00.539 19561-19561/au.gov.nsw.shellharbour.saferroadsshellharbour D/AndroidRuntime﹕ Shutting down VM
09-16 11:04:00.539 19561-19561/au.gov.nsw.shellharbour.saferroadsshellharbour W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x40e21438)
09-16 11:04:00.559 19561-19561/au.gov.nsw.shellharbour.saferroadsshellharbour E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.NullPointerException: file
at android.net.Uri.fromFile(Uri.java:441)
at au.gov.nsw.shellharbour.saferroadsshellharbour.dob_in_a_hoon.getOutputMediaFileUri(dob_in_a_hoon.java:97)
at au.gov.nsw.shellharbour.saferroadsshellharbour.dob_in_a_hoon.captureImage(dob_in_a_hoon.java:89)
at au.gov.nsw.shellharbour.saferroadsshellharbour.dob_in_a_hoon.access$000(dob_in_a_hoon.java:28)
at au.gov.nsw.shellharbour.saferroadsshellharbour.dob_in_a_hoon$1.onClick(dob_in_a_hoon.java:60)
at android.view.View.performClick(View.java:4191)
at android.view.View$PerformClick.run(View.java:17229)
at android.os.Handler.handleCallback(Handler.java:615)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4963)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1038)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:805)
at dalvik.system.NativeStart.main(Native Method)
09-16 11:04:10.529 19561-19561/au.gov.nsw.shellharbour.saferroadsshellharbour I/Process﹕ Sending signal. PID: 19561 SIG: 9
Here is my .java file:
public class dob_in_a_hoon extends ActionBarActivity {
private static final int CAMERA_CAPTURE_IMAGE_REQUEST_CODE = 100;
public static final int MEDIA_TYPE_IMAGE = 1;
private static final String IMAGE_DIRECTORY_NAME = "Dob_in_a_Hoon_photos";
private Uri fileUri;
private ImageView Hoon_Image;
private Button button_take_photo;
private String driver_spinner_array[];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dob_in_a_hoon);
driver_spinner_array = new String[2];
driver_spinner_array[0] = "Yes";
driver_spinner_array[1] = "No";
Spinner Driver_spinner = (Spinner) findViewById(R.id.driver_selector);
ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_dropdown_item_1line, driver_spinner_array);
Driver_spinner.setAdapter(adapter);
Hoon_Image = (ImageView) findViewById(R.id.CapturedImage);
button_take_photo = (Button)findViewById(R.id.btn_take_photo);
button_take_photo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
captureImage();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.dob_in_a_hoon, 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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private void captureImage(){
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
startActivityForResult(intent, CAMERA_CAPTURE_IMAGE_REQUEST_CODE);
}
public Uri getOutputMediaFileUri(int type){
return Uri.fromFile(getOutputMediaFile(type));
}
private static File getOutputMediaFile(int type){
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),IMAGE_DIRECTORY_NAME);
if (!mediaStorageDir.exists()){
if (!mediaStorageDir.mkdirs()){
Log.d(IMAGE_DIRECTORY_NAME, "Failed to create " + IMAGE_DIRECTORY_NAME + " directory");
return null;
}
}
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
File mediaFile;
if (type==MEDIA_TYPE_IMAGE){
mediaFile = new File(mediaStorageDir.getPath()+File.separator+"IMG_"+timeStamp+".jpg");
}else {
return null;
}
return mediaFile;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data){
if (requestCode == CAMERA_CAPTURE_IMAGE_REQUEST_CODE){
if (resultCode==RESULT_OK){
previewCapturedImage();
}else if (resultCode == RESULT_CANCELED){
Toast.makeText(getApplicationContext(),"User Cancelled image Capture", Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(getApplicationContext(),"Failed to capture image", Toast.LENGTH_SHORT).show();
}
}
}
private void previewCapturedImage(){
try{
Hoon_Image.setVisibility(View.VISIBLE);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 8;
final Bitmap bitmap = BitmapFactory.decodeFile(fileUri.getPath(),options);
Hoon_Image.setImageBitmap(bitmap);
}catch (NullPointerException e){
e.printStackTrace();
}
}
#Override
protected void onSaveInstanceState(Bundle outState){
super .onSaveInstanceState(outState);
outState.putParcelable("file_uri", fileUri);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState){
super.onRestoreInstanceState(savedInstanceState);
fileUri = savedInstanceState.getParcelable("file_uri");
}
}
Can anybody see where I am going wrong in my code, and what I have to do to fix it?
I created a sample snippet and tested out the mkdirs as shown in your code, it causes similar exception if i removed the permissions
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
Can you please check your manifest to make sure you have these defined.
If above is not the problem, another (unlikely) source of error could be your SD card is running out of space or some permissions restrictions. In this case, i would try the app on android emulator or another device.
This should be added in Manifest to use camera feature:
<uses-feature android:name="android.hardware.camera" />
<uses-feature android:glEsVersion="0x00020000"
android:required="true"/>