I have a Custom List View which is loaded in Oncreate of my activity but in Async Task. I want to display the activity screen initially with a loader while the list is populated.
Activity OnCreate
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_word);
viewFlipper = new ViewFlipper(this);
viewFlipper.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
TextView txt = (TextView) findViewById(R.id.phraseListHeading);
Typeface font = Typeface.createFromAsset(WordActivity.this.getAssets(), "fonts/NotoSans-Regular.ttf");
String categoryName = getIntent().getExtras().getString("categoryName").toUpperCase();
category_obj = (categories) getIntent().getSerializableExtra("category_obj");
asyncLoadWordList task2 = new asyncLoadWordList(getApplicationContext());
task2.execute();}
My Async Task Class
public class asyncLoadWordList extends AsyncTask<ArrayList<word>, Void, ArrayList<word>>{
private Context mContext;
public asyncLoadWordList(Context context) {
mContext = context;
}
protected void onPreExecute() {
//Start the splash screen dialog
if (pleaseWaitDialog == null)
pleaseWaitDialog= ProgressDialog.show(WordActivity.this,
"PLEASE WAIT",
"Getting results...",
false);
}
#Override
protected ArrayList<word> doInBackground(ArrayList<word>... params) {
wordDb = new wordDB(mContext);
category_obj = (categories) getIntent().getSerializableExtra("category_obj");
ArrayList<word> words = new ArrayList<word>();
Cursor row = wordDb.selectWordList(category_obj.getCsvCategoryId().toString());
words.add(new word("-1", "-1", "", "", "", "", "", "", "x.mp3", ""));
words.add(new word("-2", "-2", "", "", "", "", "", "", "x.mp3", ""));
row.moveToFirst();
while (!row.isAfterLast()) {
//Log.d("Data id: ", row.getString(2));
words.add( new word(row.getString(0),row.getString(1),row.getString(2),row.getString(3),row.getString(4),row.getString(5),row.getString(6),row.getString(7),row.getString(8),row.getString(9)));
row.moveToNext();
}
row.close();
return words;
}
protected void onPostExecute(ArrayList<word> result) {
adapter = new WordAdapter(WordActivity.this, result);
ListView listView = (ListView) findViewById(R.id.list_view_word);
listView.setAdapter(adapter);
if (pleaseWaitDialog != null) {
pleaseWaitDialog.dismiss();
pleaseWaitDialog = null;
}
asyncFlipperView task = new asyncFlipperView(getApplicationContext());
task.execute(new String[]{category_obj.getCsvCategoryId().toString()});
}
}
I am getting
04-04 14:10:41.889 31208-31208/thai.phrasi.ctech.com.phrasi E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: thai.phrasi.ctech.com.phrasi, PID: 31208
java.lang.RuntimeException: Unable to start activity ComponentInfo{thai.phrasi.ctech.com.phrasi/thai.phrasi.ctech.com.phrasi.WordActivity}: android.view.WindowManager$BadTokenException: Unable to add window -- token android.app.LocalActivityManager$LocalActivityRecord#42169328 is not valid; is your activity running?
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2184)
at android.app.ActivityThread.startActivityNow(ActivityThread.java:2024)
at android.app.LocalActivityManager.moveToState(LocalActivityManager.java:135)
at android.app.LocalActivityManager.startActivity(LocalActivityManager.java:347)
at thai.phrasi.ctech.com.phrasi.CategoryActivity$1.onItemClick(CategoryActivity.java:95)
at android.widget.AdapterView.performItemClick(AdapterView.java:299)
at android.widget.AbsListView.performItemClick(AbsListView.java:1113)
at android.widget.AbsListView$PerformClick.run(AbsListView.java:2911)
at android.widget.AbsListView$3.run(AbsListView.java:3645)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5001)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)
Caused by: android.view.WindowManager$BadTokenException: Unable to add window -- token android.app.LocalActivityManager$LocalActivityRecord#42169328 is not valid; is your activity running?
at android.view.ViewRootImpl.setView(ViewRootImpl.java:532)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:259)
at
How do I show the initial Screen with loader???
First of all you are setting a context of a class which is not initialize:
adapter = new WordAdapter(WordActivity.this, result);
Second you shouldn't manipulate views in a different thread.
To solved It you could create a handler to send the data to the uithread:
public class YourHandler extends Handler {
public YourHandler() {
super();
}
public synchronized void handleMessage(Message msg) {
ArrayList<word> data = (ArrayList<word> )msg.obj;
adapter = new WordAdapter(mContext, data);
ListView listView = (ListView) findViewById(R.id.list_view_word);
listView.setAdapter(adapter);
listView.notifyDataSetChanged();
}
}
And Send the data from onpostexecute:
protected void onPostExecute(ArrayList<word> result) {
msg = Message.obtain();
msg.obj = mResponse;
mYourHandler.sendMessage(msg);
}
THe handler is a inner class inside the activity, and don't forget to create mContext variable in your activity:
private Context mContext = this;
try to use this intead of getApplicationContext()
asyncLoadWordList task2 = new asyncLoadWordList(this);
Related
Can you please find out what is wrong with this code?
public class NewMessageActivity extends AppCompatActivity {
private DatabaseReference mDatabaseReference;
String mDisplayName = "John";
EditText mNewMessageField;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final EditText mNewMessageField = (EditText) findViewById(R.id.newMessageText);
setContentView(R.layout.activity_new_message);
ImageButton mSendButton = (ImageButton) findViewById(R.id.sendButton);
mSendButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sendMessage();
finish();
}
});
}
private void sendMessage(){
mDatabaseReference= FirebaseDatabase.getInstance().getReference();
String input = mNewMessageField.getText().toString();
SingleMessage singleMessage = new SingleMessage(input, mDisplayName);
mDatabaseReference.child("messages").push().setValue(singleMessage);
}
}
Immediately after I press the send button, the app stops working and I get this error message:
FATAL EXCEPTION: main
java.lang.NullPointerException
at com..NewMessageActivity.sendMessage(NewMessageActivity.java:42)
at com..NewMessageActivity.access$000(NewMessageActivity.java:14)
at com.***.NewMessageActivity$1.onClick(NewMessageActivity.java:33)
at android.view.View.performClick(View.java:4209)
at android.view.View$PerformClick.run(View.java:17457)
at android.os.Handler.handleCallback(Handler.java:725)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:153)
at android.app.ActivityThread.main(ActivityThread.java:5341)
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:929)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:696)
at dalvik.system.NativeStart.main(Native Method)
11-28 20:05:51.566 508-527/? E/AppErrorDialog: Failed to get ILowStorageHandle instance
You need to call setContentView() before you search for the EditText widget. You also must use the instance of mNewMessageField declared at package level. Don't declare a new instance in onCreate().
setContentView(R.layout.activity_new_message);
mNewMessageField = (EditText) findViewById(R.id.newMessageText); // <= CHANGED
if (mNewMessageField == null) {
System.out.println("mNewMessageField is NULL");
}
To get more clues, add this debug output:
private void sendMessage(){
mDatabaseReference= FirebaseDatabase.getInstance().getReference();
if (mNewMessageField == null) {
System.out.println("mNewMessageField is NULL");
}
Editable ed = mNewMessageField.getText();
if (ed == null) {
System.out.println("Editable is NULL");
}
String input = mNewMessageField.getText().toString();
System.out.println("input=" + input);
SingleMessage singleMessage = new SingleMessage(input, mDisplayName);
mDatabaseReference.child("messages").push().setValue(singleMessage);
}
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.
I wanted to test my code on another device than my physical one, so I launched the app in GenyMotion emulator with a Samsung Galaxy S3 (API 18), but it keeps throwing a NoClassDefFoundError Exception in my class "SlidingMenuUtil" (a customized drawer menu) which is called on startup by my MainActivity.
Here is code from my onCreate in MainActivity:
#Bind(R.id.viewContentFullScreen) RelativeLayout viewContentFullScreen;
#Bind(R.id.viewContentTopBar) RelativeLayout viewContentTopBar;
#Bind(R.id.topBarWrapper) RelativeLayout topbarView;
private ViewContainer viewContainer;
private SlidingMenuUtil leftMenu;
private Bundle bundle;
private MessageHandler messageHandler;
private GoBackFunction currentGoBackFunction;
private CallbackManager callbackManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
bundle = savedInstanceState;
setContentView(R.layout.activity_main);
leftMenu = new SlidingMenuUtil(this, SlidingMenuUtil.MenuType.LEFT, R.layout.drawer_menu, (int)(LayoutUtil.getScreenWidth(this) * 0.75), false);
populateMenu();
ButterKnife.bind(this);
messageHandler = new MessageHandler(this, findViewById(R.id.spinner));
FacebookSdk.sdkInitialize(getApplicationContext());
callbackManager = CallbackManager.Factory.create();
}
The problem occurs in the SlidingMenuUtil class on line: 67. Here is the constructor for the class:
public SlidingMenuUtil(Activity activity, MenuType menuType, int menuLayout, int shownMenuWidth, boolean fadeEffectOn) {
this.activity = activity;
this.menuType = menuType;
this.shownMenuWidth = shownMenuWidth;
this.fadeEffectOn = fadeEffectOn;
this.screenWidth = LayoutUtil.getScreenWidth(activity);
this.rootView = (ViewGroup)((ViewGroup)activity.findViewById(android.R.id.content)).getChildAt(0);
this.activityWrapper = new RelativeLayout(activity);
this.activityWrapper.setLayoutParams(this.rootView.getLayoutParams());
this.overlay = new RelativeLayout(activity);
this.overlay.setLayoutParams(new ViewGroup.LayoutParams(-1, -1));
this.overlay.setBackgroundColor(Color.parseColor("#000000"));
this.overlay.setAlpha(0.0F);
this.overlay.setVisibility(View.GONE);
this.overlay.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (menuOpen) {
toggle(new ToggleMenu() {
#Override
public void animationDone() {
}
});
}
}
});
this.rootView.addView(this.overlay);
this.menu = (LinearLayout)activity.getLayoutInflater().inflate(menuLayout, (ViewGroup) null, false);
this.menu.setLayoutParams(new ViewGroup.LayoutParams(shownMenuWidth, -1));
if (menuType == MenuType.LEFT) {
this.menu.setTranslationX((float)(-shownMenuWidth));
} else {
this.menu.setTranslationX((float)(screenWidth));
}
this.rootView.addView(this.menu);
this.menuOpen = false;
}
lin 67 is:
this.overlay.setOnClickListener(new View.OnClickListener() {
As mentioned before the problem only occurs in the emulator.
Here is the log:
812-812/? E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.NoClassDefFoundError: nightout.dk.nightoutandroid.utils.SlidingMenuUtil$1
at nightout.dk.nightoutandroid.utils.SlidingMenuUtil.<init>(SlidingMenuUtil.java:67)
at nightout.dk.nightoutandroid.MainActivity.onCreate(MainActivity.java:40)
at android.app.Activity.performCreate(Activity.java:5133)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
at android.app.ActivityThread.access$600(ActivityThread.java:141)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5103)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
I hope somone can help me out.
Any help will be gratly appreciated
I have a alert dialog in android that called from javascript interface.
In alert dialog I have two button that when you click on the one of them I want start other alert dialog that include list.but when I click app crashed.
this is my java code :
public void SaveDialog(final String SaveID) {
final SQLiteDatabase mydatabase1 = openOrCreateDatabase("CopyCollection", MODE_PRIVATE, null);
Cursor c = mydatabase1.rawQuery("SELECT * FROM Details WHERE ID="+SaveID+";", null);
if(c.moveToFirst()) {
do {
appName = c.getString(1);
txtClip = c.getString(2);
text_Date = c.getString(3);
} while (c.moveToNext());
}
AlertDialog.Builder myDialog = new AlertDialog.Builder(AndroidHTMLActivity.this);
myDialog.setTitle("ذخیره");
myDialog.setPositiveButton("ذخیره", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//======================================================
String names[] ={"A","B","C","D"};
final AlertDialog.Builder alertDialog = new AlertDialog.Builder(AndroidHTMLActivity.this);
LayoutInflater inflater = getLayoutInflater();
View convertView = (View) inflater.inflate(R.layout.main, null);
alertDialog.setView(convertView);
alertDialog.setTitle("List");
ListView lv = (ListView) convertView.findViewById(R.id.listView1);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(AndroidHTMLActivity.this,android.R.layout.simple_list_item_1,names);
lv.setAdapter(adapter);
alertDialog.show();
}
});
myDialog.setNegativeButton("اشتراک گذاری", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
sharingIntent.setType("text/plain");
String shareBody = txtClip;
sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Subject");
sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, shareBody);
startActivity(Intent.createChooser(sharingIntent, "Share via"));
}
});
myDialog.show();
}
and this is logcat :
03-24 02:22:58.146 5499-5499/com.exercise.AndroidHTML W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0xb0cf3b20)03-24 02:22:58.156 5499-5499/com.exercise.AndroidHTML E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.exercise.AndroidHTML, PID: 5499
java.lang.IllegalStateException: Calling View methods on another thread than the UI thread.
at com.android.webview.chromium.WebViewChromium.createThreadException(WebViewChromium.java:268)
at com.android.webview.chromium.WebViewChromium.checkThread(WebViewChromium.java:284)
at com.android.webview.chromium.WebViewChromium.setLayoutParams(WebViewChromium.java:1618)
at android.webkit.WebView.setLayoutParams(WebView.java:2099)
at android.view.ViewGroup.addViewInner(ViewGroup.java:3577)
at android.view.ViewGroup.addView(ViewGroup.java:3415)
at android.view.ViewGroup.addView(ViewGroup.java:3391)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:759)
at android.view.LayoutInflater.inflate(LayoutInflater.java:492)
at android.view.LayoutInflater.inflate(LayoutInflater.java:397)
at android.view.LayoutInflater.inflate(LayoutInflater.java:353)
at com.exercise.AndroidHTML.AndroidHTMLActivity$MyJavaScriptInterface.SaveDialog(AndroidHTMLActivity.java:198)
at com.android.org.chromium.base.SystemMessageHandler.nativeDoRunLoopOnce(Native Method)
at com.android.org.chromium.base.SystemMessageHandler.handleMessage(SystemMessageHandler.java:27)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.os.HandlerThread.run(HandlerThread.java:61)
JavaScript runs on a separate thread other than main thread, which you can't show dialog directly on. Instead, you can show your dialog as following:
First, add a method to your MyJavaScriptInterface class:
public void showDialog(final String SaveID){
// create a Handler with the main Looper and
// post the dialog showing work to main thread.
new Handler(Looper.getMainLooper()).post(new Runnable(){
SaveDialog(SaveID);
});
}
Then, call showDialog() method instead of SaveDialog().
New to Android here. I've made a new Fragments app, and I'm having trouble accessing the database from the Fragment.
Here's the class:
public class ShopListActivity extends FragmentActivity {
SectionsPagerAdapter mSectionsPagerAdapter;
ViewPager mViewPager;
DatabaseHelper db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_shoplist);
db = new DatabaseHelper(this); // tried getApplicationContext(), and getBaseContext() as well
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
}
public void onClickAddProduct(View view) {
TextView productName = (TextView) findViewById(R.id.add_product_text);
SQLiteDatabase dbWritable = db.getWritableDatabase(); // <-- crashes here
ContentValues values = new ContentValues();
values.put("Name", (String) productName.getText());
dbWritable.insert("Lists", "Name", values);
}
All the other solutions I found on SO didn't help.
DatabaseHelper is a very basic DB Helper class:
public DatabaseHelper(Context context) {
super(context, dbName, null, dbVersion);
}
public void onCreate(SQLiteDatabase db) {
db.execSQL(SQL_CREATE_TABLES);
db.execSQL("INSERT INTO Lists (Name) VALUES('Test')");
}
Here's the Logcat:
07-07 21:03:24.351 9641-9641/com.chas.shopforme E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.IllegalStateException: Could not execute method of the activity
at android.view.View$1.onClick(View.java:3606)
at android.view.View.performClick(View.java:4211)
at android.view.View$PerformClick.run(View.java:17362)
at android.os.Handler.handleCallback(Handler.java:725)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5227)
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:795)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:562)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at android.view.View$1.onClick(View.java:3601)
... 11 more
Caused by: java.lang.NullPointerException
at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:224)
at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:164)
at com.chas.shopforme.ShopListActivity.onClickAddProduct(ShopListActivity.java:69)
... 14 more
Note: I know there are more questions like this, but their solutions didn't work for me.
try this
db = new DatabaseHelper(this.getApplicationContext());
I tried adding this as a comment to your question, but nasty things happen to code in comments.
Assuming you've tried a) in the comment above, and it didn't work, an example of b) follows:
protected void onCreate(Bundle savedInstanceState) {
...
Handler hand = new Handler();
hand.post(new Runnable() {
public void run() {
dbInit();
}
});
}
public void dbInit() {
db = new DatabaseHelper(this);
}
This allows the fragment manager to finish setting up the fragment before you try to use it. What it is doing is sending a message to itself which is processed when the fragment's message handler loop is running.