activity crashes when going back home - java

I have an edit task activity with a single edittext view. When i click the back button on the action bar, the database is updated and the log even registers it, but the activity crashes while going back. The main activity does display the text that was added in the task activity.
Here is the code for the home button:
public class NewTask extends Activity {
protected TaskerDbHelper db;
MyAdapter adapt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_task);
db = new TaskerDbHelper(this);
setupActionBar();
}
private void setupActionBar() {
getActionBar().setDisplayHomeAsUpEnabled(true);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.new_task, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// This ID represents the Home or Up button. In the case of this
// activity, the Up button is shown. Use NavUtils to allow users
// to navigate up one level in the application structure. For
// more details, see the Navigation pattern on Android Design:
//
// http://developer.android.com/design/patterns/navigation.html#up-vs-back
//
EditText t = (EditText) findViewById(R.id.editText1);
String s = t.getText().toString();
if (s.equalsIgnoreCase("")) {
Toast.makeText(this, "enter the task description first!!",
Toast.LENGTH_LONG);
} else {
Task task = new Task(s, 0);
db.addTask(task);
Log.d("tasker", "data added");
//t.setText("");
//adapt.add(task);
adapt.notifyDataSetChanged();
}
setResult(RESULT_OK);
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
}
Whats wrong?
Here is the log:
08-16 17:56:05.117: E/AndroidRuntime(6162): FATAL EXCEPTION: main
08-16 17:56:05.117: E/AndroidRuntime(6162): java.lang.NullPointerException
08-16 17:56:05.117: E/AndroidRuntime(6162): at com.example.tasker.NewTask.onOptionsItemSelected(NewTask.java:62)
08-16 17:56:05.117: E/AndroidRuntime(6162): at android.app.Activity.onMenuItemSelected(Activity.java:2552)
08-16 17:56:05.117: E/AndroidRuntime(6162): at com.android.internal.widget.ActionBarView$3.onClick(ActionBarView.java:167)
08-16 17:56:05.117: E/AndroidRuntime(6162): at android.view.View.performClick(View.java:4204)
08-16 17:56:05.117: E/AndroidRuntime(6162): at android.view.View$PerformClick.run(View.java:17355)
08-16 17:56:05.117: E/AndroidRuntime(6162): at android.os.Handler.handleCallback(Handler.java:725)
08-16 17:56:05.117: E/AndroidRuntime(6162): at android.os.Handler.dispatchMessage(Handler.java:92)
08-16 17:56:05.117: E/AndroidRuntime(6162): at android.os.Looper.loop(Looper.java:137)
08-16 17:56:05.117: E/AndroidRuntime(6162): at android.app.ActivityThread.main(ActivityThread.java:5234)
08-16 17:56:05.117: E/AndroidRuntime(6162): at java.lang.reflect.Method.invokeNative(Native Method)
08-16 17:56:05.117: E/AndroidRuntime(6162): at java.lang.reflect.Method.invoke(Method.java:525)
08-16 17:56:05.117: E/AndroidRuntime(6162): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:799)
08-16 17:56:05.117: E/AndroidRuntime(6162): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:566)
08-16 17:56:05.117: E/AndroidRuntime(6162): at dalvik.system.NativeStart.main(Native Method)

Try checking if the adapter is null first
if(adapt != null) {
adapt.notifyDataSetChanged();
} else {
// Initialize and do other stuff with it
}
And in the declaration, declare adapt like this
public MyAdapter adapt;
I can see that your using a custom adapter class. I think the problem may also be there in the notifyDataSetChanged() method. Can you post it?

if(adapt != null) {
adapt.notifyDataSetChanged();
} else {
adapt = new Adapter();
listview.setAdapter(adapt);
}

check the answer from Noah. he is overriding the notify() to access the BaseAdapter
https://stackoverflow.com/a/5327197/2074990

Related

NullPointerException. Cannot create activity

I can't figure out where error is occurring. Here is the stack trace:
08-16 18:00:36.455: E/AndroidRuntime(22834): FATAL EXCEPTION: main
08-16 18:00:36.455: E/AndroidRuntime(22834): Process: org.example.calcu, PID: 22834
08-16 18:00:36.455: E/AndroidRuntime(22834): java.lang.RuntimeException: Unable to start activity ComponentInfo{org.example.calcu/org.example.calcu.Menu}: java.lang.NullPointerException
08-16 18:00:36.455: E/AndroidRuntime(22834): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2224)
08-16 18:00:36.455: E/AndroidRuntime(22834): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2283)
08-16 18:00:36.455: E/AndroidRuntime(22834): at android.app.ActivityThread.access$800(ActivityThread.java:144)
08-16 18:00:36.455: E/AndroidRuntime(22834): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1205)
08-16 18:00:36.455: E/AndroidRuntime(22834): at android.os.Handler.dispatchMessage(Handler.java:102)
08-16 18:00:36.455: E/AndroidRuntime(22834): at android.os.Looper.loop(Looper.java:136)
08-16 18:00:36.455: E/AndroidRuntime(22834): at android.app.ActivityThread.main(ActivityThread.java:5158)
08-16 18:00:36.455: E/AndroidRuntime(22834): at java.lang.reflect.Method.invokeNative(Native Method)
08-16 18:00:36.455: E/AndroidRuntime(22834): at java.lang.reflect.Method.invoke(Method.java:515)
08-16 18:00:36.455: E/AndroidRuntime(22834): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:796)
08-16 18:00:36.455: E/AndroidRuntime(22834): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:612)
08-16 18:00:36.455: E/AndroidRuntime(22834): at de.robv.android.xposed.XposedBridge.main(XposedBridge.java:132)
08-16 18:00:36.455: E/AndroidRuntime(22834): at dalvik.system.NativeStart.main(Native Method)
08-16 18:00:36.455: E/AndroidRuntime(22834): Caused by: java.lang.NullPointerException
08-16 18:00:36.455: E/AndroidRuntime(22834): at org.example.calcu.Menu.onCreate(Menu.java:79)
08-16 18:00:36.455: E/AndroidRuntime(22834): at android.app.Activity.performCreate(Activity.java:6084)
08-16 18:00:36.455: E/AndroidRuntime(22834): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
08-16 18:00:36.455: E/AndroidRuntime(22834): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2181)
08-16 18:00:36.455: E/AndroidRuntime(22834): ... 12 more
This is where I try to start activity in my MainActivity:
empty is Button (fairly long and empty - no text in it). I swipe my finger left to create new intent - Menu
empty = (Button) findViewById(R.id.empty);
empty.setOnTouchListener(new OnSwipeTouchListener(this){
#Override
public void onSwipeLeft() {
Intent ent;
ent = new Intent(MainActivity.this, Menu.class);
startActivity(ent);
}
});
This is activity that I try to create, Menu:
package org.example.calcu;
import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.os.Bundle;
import android.text.Layout;
import android.util.Log;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.Button;
public class Menu extends MainActivity{
Button blueTheme;
View menu;
class OnSwipeTouchListener implements OnTouchListener{
private final GestureDetector gestureDetector;
public OnSwipeTouchListener(Context context) {
gestureDetector = new GestureDetector(context, new GestureListener());
}
public void onSwipeLeft() {
}
public void onSwipeRight() {
}
public boolean onTouch(View v, MotionEvent event) {
return gestureDetector.onTouchEvent(event);
}
private final class GestureListener extends SimpleOnGestureListener {
private static final int SWIPE_DISTANCE_THRESHOLD = 100;
private static final int SWIPE_VELOCITY_THRESHOLD = 100;
#Override
public boolean onDown(MotionEvent e) {
return true;
}
#Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
float distanceX = e2.getX() - e1.getX();
float distanceY = e2.getY() - e1.getY();
if (Math.abs(distanceX) > Math.abs(distanceY) && Math.abs(distanceX) > SWIPE_DISTANCE_THRESHOLD && Math.abs(velocityX) > SWIPE_VELOCITY_THRESHOLD) {
if (distanceX > 0)
onSwipeRight();
else
onSwipeLeft();
return true;
}
return false;
}
}
}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d("LOG", "menu opened!");
setContentView(R.layout.menu);
menu = (View) findViewById(R.layout.menu);
menu.setOnTouchListener(new OnSwipeTouchListener(this){ /* this is line 79 */
#Override
public void onSwipeRight(){
setContentView(R.layout.activity_main);
}
});
blueTheme = (Button) findViewById(R.id.blueTheme);
blueTheme.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
one.setBackgroundColor(Color.parseColor("#90CAF9"));
}
});
}
}
Thanks for your help, and sorry I am pretty beginner in programming.
menu = (View) findViewById(R.layout.menu);
findViewById takes an id as parameter not a layout.
The could should be:
menu = (View) findViewById(R.id.menu);
but, of course you also should have a view with id menu in your xml layout.
To finish your activity and get back to the previous one:
menu.setOnTouchListener(new OnSwipeTouchListener(this){
#Override public void onSwipeRight()
{
Menu.this.finish();
}
}

Fragment is trying to cast to activity

I know this answer is probably simple but i cannot figure it out. I am modifying example code for a project and keep getting a ClassCastException when i try to launch the app. Says that ListActivityFragment cannot be cast to android.app.Activity. What im not understanding(which is probably the simple part) is why its trying to cast it onto an activity when my main is a fragmentactivity. I know the code is rough, still trying to finish it up but cant get past this.
FragmentActivity
public class MainActivity extends FragmentActivity {
private boolean isLargeScreen = true;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (findViewById(R.id.normal_screen_layout) != null) {
isLargeScreen = false;
ListActivityFragment listActivityFragment = new ListActivityFragment();
listActivityFragment.setArguments(getIntent().getExtras());
getSupportFragmentManager().beginTransaction()
.add(R.id.normal_screen_layout, listActivityFragment)
.commit();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.addItem:
ListActivityFragment newFragment = new ListActivityFragment();
FragmentTransaction transaction = getSupportFragmentManager()
.beginTransaction();
transaction.replace(R.id.normal_screen_layout, newFragment);
transaction.addToBackStack(null);
transaction.commit();
break;
default:
return super.onOptionsItemSelected(item);
}
return true;
}
}
}
ListActivity
public class ListActivityFragment extends ListFragment implements
OnClickListener {
private ArrayList<String> items = new ArrayList<String>();
private ListView listView;
private View outerView;
private Button deleteButton;
private ListActivityListener listener;
public interface ListActivityListener {
public void meetingAdded();
}
public ListActivityFragment() {
}
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
listener = (ListActivityListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnHeadlineSelectedListener");
}
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
outerView = inflater.inflate(R.layout.list_of_meetings, container,
false);
listView = (ListView) outerView.findViewById(R.id.listView1);
deleteButton = (Button) outerView.findViewById(R.id.deleteButton);
createList();
return outerView;
}
public void createList() {
items.clear();
Iterator<Items> iterator = ItemCollection.Instance().iterator();
while (iterator.hasNext()) {
items.add(iterator.next().toString());
}
listView.setAdapter(new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1, items));
}
#Override
public void onClick(DialogInterface arg0, int arg1) {
ListView listView = getListView();
for (int index = 0; index < listView.getChildCount(); index++) {
View viewGroup = listView.getChildAt(index);
CheckBox checkBox = (CheckBox) viewGroup
.findViewById(R.id.itemSelectCheckBox);
if (checkBox.isChecked()) {
TextView textView = (TextView) viewGroup
.findViewById(R.id.productTextView);
int key = (Integer) textView.getTag();
ItemCollection.Instance().delete(key);
}
}
createList();
}
#Override
public void onStart() {
super.onStart();
}
public void onListItemClick(ListView l, View v, int position, long id) {
getListView().setItemChecked(position, true);
}
}
And heres the Logcat
07-15 01:59:50.710: E/AndroidRuntime(878): FATAL EXCEPTION: main
07-15 01:59:50.710: E/AndroidRuntime(878): Process: com.example.assignment5, PID: 878
07-15 01:59:50.710: E/AndroidRuntime(878): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.assignment5/com.example.assignment5.ListActivityFragment}: java.lang.ClassCastException: com.example.assignment5.ListActivityFragment cannot be cast to android.app.Activity
07-15 01:59:50.710: E/AndroidRuntime(878): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2121)
07-15 01:59:50.710: E/AndroidRuntime(878): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
07-15 01:59:50.710: E/AndroidRuntime(878): at android.app.ActivityThread.access$800(ActivityThread.java:135)
07-15 01:59:50.710: E/AndroidRuntime(878): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
07-15 01:59:50.710: E/AndroidRuntime(878): at android.os.Handler.dispatchMessage(Handler.java:102)
07-15 01:59:50.710: E/AndroidRuntime(878): at android.os.Looper.loop(Looper.java:136)
07-15 01:59:50.710: E/AndroidRuntime(878): at android.app.ActivityThread.main(ActivityThread.java:5017)
07-15 01:59:50.710: E/AndroidRuntime(878): at java.lang.reflect.Method.invokeNative(Native Method)
07-15 01:59:50.710: E/AndroidRuntime(878): at java.lang.reflect.Method.invoke(Method.java:515)
07-15 01:59:50.710: E/AndroidRuntime(878): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
07-15 01:59:50.710: E/AndroidRuntime(878): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
07-15 01:59:50.710: E/AndroidRuntime(878): at dalvik.system.NativeStart.main(Native Method)
07-15 01:59:50.710: E/AndroidRuntime(878): Caused by: java.lang.ClassCastException: com.example.assignment5.ListActivityFragment cannot be cast to android.app.Activity
07-15 01:59:50.710: E/AndroidRuntime(878): at android.app.Instrumentation.newActivity(Instrumentation.java:1061)
07-15 01:59:50.710: E/AndroidRuntime(878): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2112)
07-15 01:59:50.710: E/AndroidRuntime(878): ... 11 more
07-15 01:59:51.160: E/NetdConnector(383): NDC Command {65 bandwidth setiquota eth0 9223372036854775807} took too long (1117ms)
Caused by: java.lang.ClassCastException:
com.example.assignment5.ListActivityFragment cannot be cast to
android.app.Activity 07-15 01:59:50.710: E/AndroidRuntime(878):
As the error says -
ListActivityFragment is not an activity. So you are trying to access it just like an activity.
Make sure you haven't declared ListActivityFragment in the manifest. In your manifest if you made an entry for the fragment then that's wrong.
Also make sure that you haven't used startActivity for the fragment. Because this is done for activity class and not for fragment class.

Cant start a dialog activity from a button in another activity

I am trying to start a new activity as a Dialog Activity putting a Intent on a button from another activity. Whenever I try and press the button, the activity unfotunately closes.
Main Activity.java
public class MainActivity extends FragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button ab = (Button) findViewById(R.id.button1);
ab.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent intent = new Intent(MainActivity.this, NewDialog.class);
startActivity(intent);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void side(View view){
android.support.v4.app.FragmentManager fm1 = getSupportFragmentManager();
NewDialog newdialog = new NewDialog();
newdialog.show(fm1, "SideDialog");
}
#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);
}
/**
* A placeholder fragment containing a simple view.
*/
}
NewDialog.java
public class NewDialog extends DialogFragment{
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState){
final View view = inflater.inflate(R.layout.activity_new_dialog, container);
getDialog().requestWindowFeature(Window.FEATURE_NO_TITLE);
return view;
}
}
Added Logcat:
05-29 22:37:36.472: D/dalvikvm(26806): Late-enabling CheckJNI
05-29 22:37:36.762: D/ActivityThread(26806): setTargetHeapUtilization:0.25
05-29 22:37:36.762: D/ActivityThread(26806): setTargetHeapIdealFree:8388608
05-29 22:37:36.762: D/ActivityThread(26806): setTargetHeapConcurrentStart:2097152
05-29 22:37:39.172: D/libEGL(26806): loaded /system/lib/egl/libEGL_adreno200.so
05-29 22:37:39.222: D/libEGL(26806): loaded /system/lib/egl/libGLESv1_CM_adreno200.so
05-29 22:37:39.322: D/libEGL(26806): loaded /system/lib/egl/libGLESv2_adreno200.so
05-29 22:37:39.362: I/Adreno200-EGL(26806): <qeglDrvAPI_eglInitialize:299>: EGL 1.4 QUALCOMM build: AU_LINUX_ANDROID_JB_REL_2.0.3.1_RB1.04.01.01.45.000_msm8625_JB_REL_2.0.3.1_Merge_release_AU (Merge)
05-29 22:37:39.362: I/Adreno200-EGL(26806): Build Date: 03/28/13 Thu
05-29 22:37:39.362: I/Adreno200-EGL(26806): Local Branch:
05-29 22:37:39.362: I/Adreno200-EGL(26806): Remote Branch: m/jb_rel_2.0.3.1
05-29 22:37:39.362: I/Adreno200-EGL(26806): Local Patches: NONE
05-29 22:37:39.362: I/Adreno200-EGL(26806): Reconstruct Branch: NOTHING
05-29 22:37:39.452: D/OpenGLRenderer(26806): Enabling debug mode 0
05-29 22:37:43.822: D/AndroidRuntime(26806): Shutting down VM
05-29 22:37:43.822: W/dalvikvm(26806): threadid=1: thread exiting with uncaught exception (group=0x40fd4438)
05-29 22:37:44.022: E/AndroidRuntime(26806): FATAL EXCEPTION: main
05-29 22:37:44.022: E/AndroidRuntime(26806): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.createdialog/com.example.createdialog.NewDialog}: java.lang.ClassCastException: com.example.createdialog.NewDialog cannot be cast to android.app.Activity
05-29 22:37:44.022: E/AndroidRuntime(26806): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2038)
05-29 22:37:44.022: E/AndroidRuntime(26806): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2139)
05-29 22:37:44.022: E/AndroidRuntime(26806): at android.app.ActivityThread.access$700(ActivityThread.java:143)
05-29 22:37:44.022: E/AndroidRuntime(26806): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1241)
05-29 22:37:44.022: E/AndroidRuntime(26806): at android.os.Handler.dispatchMessage(Handler.java:99)
05-29 22:37:44.022: E/AndroidRuntime(26806): at android.os.Looper.loop(Looper.java:137)
05-29 22:37:44.022: E/AndroidRuntime(26806): at android.app.ActivityThread.main(ActivityThread.java:4963)
05-29 22:37:44.022: E/AndroidRuntime(26806): at java.lang.reflect.Method.invokeNative(Native Method)
05-29 22:37:44.022: E/AndroidRuntime(26806): at java.lang.reflect.Method.invoke(Method.java:511)
05-29 22:37:44.022: E/AndroidRuntime(26806): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1038)
05-29 22:37:44.022: E/AndroidRuntime(26806): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:805)
05-29 22:37:44.022: E/AndroidRuntime(26806): at dalvik.system.NativeStart.main(Native Method)
05-29 22:37:44.022: E/AndroidRuntime(26806): Caused by: java.lang.ClassCastException: com.example.createdialog.NewDialog cannot be cast to android.app.Activity
05-29 22:37:44.022: E/AndroidRuntime(26806): at android.app.Instrumentation.newActivity(Instrumentation.java:1068)
05-29 22:37:44.022: E/AndroidRuntime(26806): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2029)
05-29 22:37:44.022: E/AndroidRuntime(26806): ... 11 more
I might be wrong here, but as far as I know, you can't start an Intent passing a DialogFragment, you should pass an Activity. Here's what's wrong:
Intent intent = new Intent(MainActivity.this, NewDialog.class);
startActivity(intent);
Since NewDialog is declared as a DialogFragment and not as an Activity subclass.
If what you are trying to do is show the dialog, then you should do:
NewDialog dialog = NewDialog();
// use getSupportFragmentManager() if using support fragments instead of native fragments, or
// use getChildFragmentManager() if this code is inside a fragment rather than an activity
dialog.show(getFragmentManager(), "pass-any-string-here");
Without a logcat stacktrace to look at, I am assuming that your issue has to do with variable scope (here is an example explanation on the topic).
What you need to do is declare your button as a class level variable because right now it is a method variable and as such ceases to exist once your onCreate method has finished executing.
public class MainActivity extends FragmentActivity {
private Button myButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myButton = (Button) findViewById(R.id.button1);
myButton.setOnClickListener(...);
...
}
}

Google Analytics Android error java.lang.NullPointerException

I'm trying to work on Google Analytics for Androi. I get the message, and I'm following the advanced configuration of Android Analytics in Google Android SDK.
java.lang.RuntimeException: Unable to start activity
ComponentInfo{com.example.secondapp/com.example.secondapp.MainActivity}:
java.lang.NullPointerException
And I get this error:
01-02 15:39:38.410: D/AndroidRuntime(1338): Shutting down VM
01-02 15:39:38.410: W/dalvikvm(1338): threadid=1: thread exiting with uncaught exception (group=0xb1ab7ba8)
01-02 15:39:38.420: E/AndroidRuntime(1338): FATAL EXCEPTION: main
01-02 15:39:38.420: E/AndroidRuntime(1338): Process: com.example.secondapp, PID: 1338
01-02 15:39:38.420: E/AndroidRuntime(1338): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.secondapp/com.example.secondapp.MainActivity}: java.lang.NullPointerException
01-02 15:39:38.420: E/AndroidRuntime(1338): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
01-02 15:39:38.420: E/AndroidRuntime(1338): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
01-02 15:39:38.420: E/AndroidRuntime(1338): at android.app.ActivityThread.access$800(ActivityThread.java:135)
01-02 15:39:38.420: E/AndroidRuntime(1338): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
01-02 15:39:38.420: E/AndroidRuntime(1338): at android.os.Handler.dispatchMessage(Handler.java:102)
01-02 15:39:38.420: E/AndroidRuntime(1338): at android.os.Looper.loop(Looper.java:136)
01-02 15:39:38.420: E/AndroidRuntime(1338): at android.app.ActivityThread.main(ActivityThread.java:5017)
01-02 15:39:38.420: E/AndroidRuntime(1338): at java.lang.reflect.Method.invokeNative(Native Method)
01-02 15:39:38.420: E/AndroidRuntime(1338): at java.lang.reflect.Method.invoke(Method.java:515)
01-02 15:39:38.420: E/AndroidRuntime(1338): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
01-02 15:39:38.420: E/AndroidRuntime(1338): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
01-02 15:39:38.420: E/AndroidRuntime(1338): at dalvik.system.NativeStart.main(Native Method)
01-02 15:39:38.420: E/AndroidRuntime(1338): Caused by: java.lang.NullPointerException
01-02 15:39:38.420: E/AndroidRuntime(1338): at com.example.secondapp.MainActivity.onCreate(MainActivity.java:24)
01-02 15:39:38.420: E/AndroidRuntime(1338): at android.app.Activity.performCreate(Activity.java:5231)
01-02 15:39:38.420: E/AndroidRuntime(1338): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
01-02 15:39:38.420: E/AndroidRuntime(1338): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
01-02 15:39:38.420: E/AndroidRuntime(1338): ... 11 more
Here is my code for SecondAppApplication, which has similarities to the android docs:
public class SecondAppApplication extends Application {
private static GoogleAnalytics mGa;
private static Tracker mTracker;
private static final String GA_PROPERTY_ID = "UA-XXXXXXXX-1";
private static final int GA_DISPATCH_PERIOD = 30;
private static final boolean GA_IS_DRY_RUN = false;
private static final LogLevel GA_LOG_VERBOSITY = LogLevel.INFO;
private static final String TRACKING_PREF_KEY = "trackingPreferences";
#SuppressWarnings("deprecation")
private void initializeGa() {
mGa = GoogleAnalytics.getInstance(this);
mTracker = mGa.getTracker(GA_PROPERTY_ID);
GAServiceManager.getInstance().setLocalDispatchPeriod(GA_DISPATCH_PERIOD);
mGa.setDryRun(GA_IS_DRY_RUN);
mGa.getLogger().setLogLevel(GA_LOG_VERBOSITY);
SharedPreferences userPrefs = PreferenceManager.getDefaultSharedPreferences(this);
userPrefs.registerOnSharedPreferenceChangeListener(new SharedPreferences.OnSharedPreferenceChangeListener() {
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
if (key.equals(TRACKING_PREF_KEY)) {
GoogleAnalytics.getInstance(getApplicationContext()).setAppOptOut(sharedPreferences.getBoolean(key, false));
}
}
});
}
#Override
public void onCreate() {
super.onCreate();
initializeGa();
}
public static Tracker getGaTracker() {
return mTracker;
}
public static GoogleAnalytics getGaInstance() {
return mGa;
}
}
Here is my MainActivity class:
public class MainActivity extends Activity {
public static final String EXTRA_MESSAGE = "com.example.myfirstapp.MESSAGE";
private static final String SCREEN_LABEL = "Main Screen";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SecondAppApplication.getGaTracker().set(Fields.SCREEN_NAME,SCREEN_LABEL);
setContentView(R.layout.main);
}
#Override
public void onStart() {
super.onStart();
SecondAppApplication.getGaTracker().send(MapBuilder.createAppView().build());
}
#Override
public void onStop() {
super.onStop();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()) {
case R.id.action_search:
openSearch();
return true;
case R.id.action_settings:
openSettings();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void openSearch() {
}
public void openSettings() {
}
public void sendMessage(View view) {
Intent intent = new Intent(this,DisplayMessageActivity.class);
EditText editText = (EditText) findViewById(R.id.edit_message);
String message = editText.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message);
startActivity(intent);
}
}
Why does java.lang.NullPointerException exists, and/or how would I solve this?
Do I need to declare initializeGa() again inside MainActivity or AndroidManifest.xml?
It looks to me like:
SecondAppApplication.getGaTracker().set(Fields.SCREEN_NAME,SCREEN_LABEL);
Is probably calling the set method on a null object, because your accessing statically without initializing it first. This almost looks like you were trying to do a singleton or something...
I would change your code to:
public static Tracker getGaTracker() {
if(mTracker ==null) {
initialize();
}
return mTracker;
}
The problem of course being that since you're doing this statically you wont have a context to pass.... I think you may need to reorganize the project a bit.
Check out this:
Android: Persist object across activities
I found out that the AndroidManifest.xml application should contain the correct android.name.
In this case, android.name="com.example.secondapplication.SecondAppApplication"

BadTokenException even after referring to Activity and not the application context

android.view.WindowManager$BadTokenException: Unable to add window -- token android.os.BinderProxy#406a6678 is not valid; is your activity running?
at android.view.ViewRoot.setView(ViewRoot.java:528)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:177)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:91)
at android.view.Window$LocalWindowManager.addView(Window.java:424)
at android.app.Dialog.show(Dialog.java:241)
at android.app.Activity.showDialog(Activity.java:2569)
at android.app.Activity.showDialog(Activity.java:2527)
at MyCode$8$4.run(MyCode.java:557)
at android.os.Handler.handleCallback(Handler.java:587)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:130)
at android.app.ActivityThread.main(ActivityThread.java:3683)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:507)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:878)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:636)
at dalvik.system.NativeStart.main(Native Method)
I am getting above exception when following code is executed. This file dialog will shown once the processing is done and progressbar reaches 100%. FileSaveDialog extends Dialog and implements OnCompletionListener
runOnUiThread(new Runnable() {
#Override
public void run() {
showDialog(error.Code());//Line 557
}
});
#Override
protected Dialog onCreateDialog(int id) {
Dialog dialog;
AlertDialog.Builder builder;
final ScrollView scrollView = new ScrollView(this);
final TextView textView = new TextView(this);
switch (id) {
// Other cases are here
case 4:
File playFile = new File(mediaPath, TEMP_WAV_FILE_NAME);
dialog = new FileSaveDialog(this, getResources(),
playFile.getAbsolutePath(), saveDiscardHandler);
dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
// do whatever you want the back key to do
cleanUp();
}
});
break;
// Other cases are here
default:
dialog = null;
}
return dialog;
}
You must check activity isFinishing() If the activity is finishing, returns true; else returns false.

Categories