I have the following Fragment. It works completely fine, until I rotate my device. It then crashes with errors about the RadarSelectionFragment failing to Instantiate. The code for the FragmentPagerAdapter and the Fragment in question are below:
#SuppressLint("DefaultLocale")
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter() {
// Do some stuff
}
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
if (position == 0) {
Fragment fragment = new RadarSelectionFragment();
Bundle args = new Bundle();
args.putInt(RadarSelectionFragment.ARG_SECTION_NUMBER, position + 1);
fragment.setArguments(args);
return fragment;
} else if (position == 1) {
Fragment fragment = new WeatherMapDisplayFragment();
Bundle args = new Bundle();
args.putInt(WeatherMapDisplayFragment.ARG_SECTION_NUMBER, position + 1);
fragment.setArguments(args);
return fragment;
} else {
Fragment tf = new RadarSelectionFragment();
return tf;
}
}
#Override
public int getCount() {
return 2;
}
#SuppressLint("DefaultLocale")
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return getString(R.string.title_section1).toUpperCase();
case 1:
return getString(R.string.title_section2).toUpperCase();
}
return null;
}
}
public static class RadarSelectionFragment extends Fragment {
public static final String ARG_SECTION_NUMBER = "section_number";
public RadarSelectionFragment() {}
#Override
public final View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
if (getArguments().getInt(ARG_SECTION_NUMBER) == 1) {
return inflater.inflate(R.layout.radars, container, false);
} else {
return container;
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setRetainInstance(true);
...
}
public void onNothingSelected(AdapterView<?> parent) {
// Another interface callback
}
});
}
}
public class WeatherMapDisplayFragment extends Fragment {
public static final String ARG_SECTION_NUMBER = "section_number";
public WeatherMapDisplayFragment() {
}
#Override
public final View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
if (getArguments().getInt(ARG_SECTION_NUMBER) == 2) {
return inflater.inflate(R.layout.display, container, false);
} else {
return container;
}
}
}
I have tried Googling the problem, but all I keep turning up are various solutions pertaining to ensuring that the Fragment Class is static (Which I've done).
I am relatively new to Android programming, so if you answer, could you please either post an example and/or link to other examples if you have the time.
Thanks in advance!
EDIT 1: Stacktrace
01-21 13:46:31.907: E/AndroidRuntime(1101): FATAL EXCEPTION: main
01-21 13:46:31.907: E/AndroidRuntime(1101): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.radarau/com.example.radarau.MainActivity}: android.support.v4.app.Fragment$InstantiationException: Unable to instantiate fragment com.example.radarau.MainActivity$WeatherMapDisplayFragment: make sure class name exists, is public, and has an empty constructor that is public
01-21 13:46:31.907: E/AndroidRuntime(1101): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
01-21 13:46:31.907: E/AndroidRuntime(1101): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
01-21 13:46:31.907: E/AndroidRuntime(1101): at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:3692)
01-21 13:46:31.907: E/AndroidRuntime(1101): at android.app.ActivityThread.access$700(ActivityThread.java:141)
01-21 13:46:31.907: E/AndroidRuntime(1101): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1240)
01-21 13:46:31.907: E/AndroidRuntime(1101): at android.os.Handler.dispatchMessage(Handler.java:99)
01-21 13:46:31.907: E/AndroidRuntime(1101): at android.os.Looper.loop(Looper.java:137)
01-21 13:46:31.907: E/AndroidRuntime(1101): at android.app.ActivityThread.main(ActivityThread.java:5039)
01-21 13:46:31.907: E/AndroidRuntime(1101): at java.lang.reflect.Method.invokeNative(Native Method)
01-21 13:46:31.907: E/AndroidRuntime(1101): at java.lang.reflect.Method.invoke(Method.java:511)
01-21 13:46:31.907: E/AndroidRuntime(1101): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
01-21 13:46:31.907: E/AndroidRuntime(1101): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
01-21 13:46:31.907: E/AndroidRuntime(1101): at dalvik.system.NativeStart.main(Native Method)
01-21 13:46:31.907: E/AndroidRuntime(1101): Caused by: android.support.v4.app.Fragment$InstantiationException: Unable to instantiate fragment com.example.radarau.MainActivity$WeatherMapDisplayFragment: make sure class name exists, is public, and has an empty constructor that is public
01-21 13:46:31.907: E/AndroidRuntime(1101): at android.support.v4.app.Fragment.instantiate(Fragment.java:405)
01-21 13:46:31.907: E/AndroidRuntime(1101): at android.support.v4.app.FragmentState.instantiate(Fragment.java:97)
01-21 13:46:31.907: E/AndroidRuntime(1101): at android.support.v4.app.FragmentManagerImpl.restoreAllState(FragmentManager.java:1767)
01-21 13:46:31.907: E/AndroidRuntime(1101): at android.support.v4.app.FragmentActivity.onCreate(FragmentActivity.java:208)
01-21 13:46:31.907: E/AndroidRuntime(1101): at com.example.radarau.MainActivity.onCreate(MainActivity.java:35)
01-21 13:46:31.907: E/AndroidRuntime(1101): at android.app.Activity.performCreate(Activity.java:5104)
01-21 13:46:31.907: E/AndroidRuntime(1101): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
01-21 13:46:31.907: E/AndroidRuntime(1101): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
01-21 13:46:31.907: E/AndroidRuntime(1101): ... 12 more
01-21 13:46:31.907: E/AndroidRuntime(1101): Caused by: java.lang.InstantiationException: can't instantiate class com.example.radarau.MainActivity$WeatherMapDisplayFragment; no empty constructor
01-21 13:46:31.907: E/AndroidRuntime(1101): at java.lang.Class.newInstanceImpl(Native Method)
01-21 13:46:31.907: E/AndroidRuntime(1101): at java.lang.Class.newInstance(Class.java:1319)
01-21 13:46:31.907: E/AndroidRuntime(1101): at android.support.v4.app.Fragment.instantiate(Fragment.java:394)
01-21 13:46:31.907: E/AndroidRuntime(1101): ... 19 more
Your logcat says
Caused by: android.support.v4.app.Fragment$InstantiationException: Unable to instantiate fragment com.example.radarau.MainActivity$WeatherMapDisplayFragment: make sure class name exists, is public, and has an empty constructor that is public
You should provide a public Default constructor for that
public WeatherMapDisplayFragment() {
// Do some stuff
}
If that class is nested, make that class to static class and provide a public default constructor or move that fragment into a new java file.
Related
When I call .notifyDataSetChanged() in my constructor after I set my ArrayList my app still crashes, the same as when I call it before I call .setAdapter, it's been bothering me for hours, would love any kind of help, thanks!
public class CustomSwipeAdapter extends PagerAdapter {
private ArrayList<String> image_resources = new ArrayList<>();
private Context mContext;
private LayoutInflater mLayoutInflater;
private ImageLoader mImageLoader;
public CustomSwipeAdapter(Context context, ArrayList<String> images){
this.mContext = context;
this.image_resources = images;
}
#Override
public int getCount() {
return image_resources.size();
}
#Override
public boolean isViewFromObject(View view, Object object) {
return (view == (LinearLayout)object);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
mLayoutInflater = (LayoutInflater) mContext.getSystemService(mContext.LAYOUT_INFLATER_SERVICE);
View item_view = mLayoutInflater.inflate(R.layout.swipe_layout, container, false);
final ImageView imageView = (ImageView) item_view.findViewById(R.id.imageView);
if (image_resources.get(position) != null || !image_resources.get(position).isEmpty()) {
mImageLoader.get(image_resources.get(position), new ImageLoader.ImageListener() {
#Override
public void onResponse(ImageLoader.ImageContainer response, boolean isImmediate) {
imageView.setImageBitmap(response.getBitmap());
}
#Override
public void onErrorResponse(VolleyError error) {
imageView.setBackgroundColor(Color.CYAN);
}
});
}
container.addView(item_view);
return item_view;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((LinearLayout) object);
super.destroyItem(container, position, object);
}
}
Where I set my Adapter (in my Activity's onCreate()), it's most basic activity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_page);
mViewPager = (ViewPager) findViewById(R.id.view_pager);
mVolleySingleton = VolleySingleton.getInstance();
mRequestQueue = mVolleySingleton.getRequestQueue();
sendAPIRequest();
//after you get the images
mCustomSwipeAdapter = new CustomSwipeAdapter(this, images);
mViewPager.setAdapter(mCustomSwipeAdapter);
}
Stack Trace:
java.lang.IllegalStateException: The application's PagerAdapter changed the adapter's contents without calling PagerAdapter#notifyDataSetChanged! Expected adapter item count: 0, found: 4 Pager id: sobmad.com.gamingreminder:id/view_pager Pager class: class android.support.v4.view.ViewPager Problematic adapter: class sobmad.com.gamingreminder.GamePage.CustomSwipeAdapter
at android.support.v4.view.ViewPager.populate(ViewPager.java:967)
at android.support.v4.view.ViewPager.populate(ViewPager.java:919)
at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1441)
at android.view.View.measure(View.java:15848)
at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:728)
at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:477)
at android.view.View.measure(View.java:15848)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5012)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
at android.view.View.measure(View.java:15848)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5012)
at android.support.v7.internal.widget.ActionBarOverlayLayout.onMeasure(ActionBarOverlayLayout.java:453)
at android.view.View.measure(View.java:15848)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5012)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
at android.view.View.measure(View.java:15848)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5012)
at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1404)
at android.widget.LinearLayout.measureVertical(LinearLayout.java:695)
at android.widget.LinearLayout.onMeasure(LinearLayout.java:588)
at android.view.View.measure(View.java:15848)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5012)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2189)
at android.view.View.measure(View.java:15848)
at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:1905)
at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1104)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1284)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1004)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5481)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:749)
at android.view.Choreographer.doCallbacks(Choreographer.java:562)
at android.view.Choreographer.doFrame(Choreographer.java:532)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:735)
at android.os.Handler.handleCallback(Handler.java:730)
at android.os.Handler.dispatchMessage(Handler.java:92)
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)
mCustomSwipeAdapter = new CustomSwipeAdapter(this, images);
mViewPager.setAdapter(mCustomSwipeAdapter);
mCustomSwipeAdapter.notifyDataSetChange() //Add this line in your 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.
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(...);
...
}
}
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"
I am trying to implement a SQLite database for a highscores table. I am just testing it to see if my database creation and insertion is working with the below code. But I am getting a NullPointerException on the below lines.
Thank you in advance!
Results.java
public class Results extends Activity {
DatabaseHelper dh;
public void onCreate(Bundle savedInstanceState) {
dh = DatabaseHelper.getInstance(this);
public void showResults() {
dh.openDB();
dh.insert(1231423, 436346); //Line 104
}
}
DatabaseHelper.java
private static final String SCORE = "score";
private static final String PERCENTAGE = "percentage";
public static DatabaseHelper mSingleton = null;
public synchronized static DatabaseHelper getInstance(Context context) {
if(mSingleton == null) {
mSingleton = new DatabaseHelper(context.getApplicationContext());
}
return mSingleton;
}
public SQLiteDatabase openDB() {
return this.getWritableDatabase();
}
public long insert(long score, int percentage) {
ContentValues values = new ContentValues();
values.put(SCORE, score);
values.put(PERCENTAGE, percentage);
return db.insert(TABLE, null, values); //Line 91
}
LogCat output
01-02 17:56:47.609: E/AndroidRuntime(1322): FATAL EXCEPTION: main
01-02 17:56:47.609: E/AndroidRuntime(1322): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.test/com.example.test.Results}: java.lang.NullPointerException
01-02 17:56:47.609: E/AndroidRuntime(1322): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2059)
01-02 17:56:47.609: E/AndroidRuntime(1322): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
01-02 17:56:47.609: E/AndroidRuntime(1322): at android.app.ActivityThread.access$600(ActivityThread.java:130)
01-02 17:56:47.609: E/AndroidRuntime(1322): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
01-02 17:56:47.609: E/AndroidRuntime(1322): at android.os.Handler.dispatchMessage(Handler.java:99)
01-02 17:56:47.609: E/AndroidRuntime(1322): at android.os.Looper.loop(Looper.java:137)
01-02 17:56:47.609: E/AndroidRuntime(1322): at android.app.ActivityThread.main(ActivityThread.java:4745)
01-02 17:56:47.609: E/AndroidRuntime(1322): at java.lang.reflect.Method.invokeNative(Native Method)
01-02 17:56:47.609: E/AndroidRuntime(1322): at java.lang.reflect.Method.invoke(Method.java:511)
01-02 17:56:47.609: E/AndroidRuntime(1322): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
01-02 17:56:47.609: E/AndroidRuntime(1322): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
01-02 17:56:47.609: E/AndroidRuntime(1322): at dalvik.system.NativeStart.main(Native Method)
01-02 17:56:47.609: E/AndroidRuntime(1322): Caused by: java.lang.NullPointerException
01-02 17:56:47.609: E/AndroidRuntime(1322): at com.example.test.DatabaseHelper.insert(DatabaseHelper.java:91)
01-02 17:56:47.609: E/AndroidRuntime(1322): at com.example.test.Results.showResults(Results.java:104)
01-02 17:56:47.609: E/AndroidRuntime(1322): at com.example.test.Results.onCreate(Results.java:50)
01-02 17:56:47.609: E/AndroidRuntime(1322): at android.app.Activity.performCreate(Activity.java:5008)
01-02 17:56:47.609: E/AndroidRuntime(1322): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079)
01-02 17:56:47.609: E/AndroidRuntime(1322): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2023)
01-02 17:56:47.609: E/AndroidRuntime(1322): ... 11 more
EDIT: The NullPointerException is at least jumping around but errors still are there. I have edited my code and posted the new LogCat output.
Change openDB() to save the SqliteDatabase it opens and open a writable database:
public void openDB() {
db = this.getWritableDatabase();
}
But this still doesn't match your stack trace, however it matches the code you provided.
You said you are doing:
DatabaseHelper dh;
dh.insert(1231423, 436346);
Looks like you are not instantiating dh:
dh = new DatabaseHelper(this);
A better approach would be to use the singleton pattern as you are ever going to need just one DatabaseHelper instance:
private static final String TABLE_NAME = "table_name";
private static final int SCHEME_VERSION = 1;
public static DatabaseHelper mSingleton = null;
private DatabaseHelper(Context ctxt) {
super(ctxt, DATABASE_NAME, null, SCHEME_VERSION);
}
public synchronized static DatabaseHelper getInstance(Context ctxt) {
if (mSingleton == null)
mSingleton = new DatabaseHelper(ctxt.getApplicationContext());
return mSingleton;
}
Now you can call like so:
DatabaseHelper dh = DatabaseHelper.getInstance(this);
If you are following the common SqlliteHelper pattern, you are likely to have forgotten to call the .open() method before calling insert.
package com.example.hostelmangement;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
public class DataBaseHelper extends SQLiteOpenHelper {
public DataBaseHelper(Context context, String name, CursorFactory factory,
int version)
{
super(context, name, factory, version);
// TODO Auto-generated constructor stub
}
#Override
public void onCreate(SQLiteDatabase db)
{
db.execSQL("create table demo(id integer primary key,join_date date,name text,father_name text,date_of_birth text,house_name text,place text,pin_no text,blood_group text,mobile text,email text,company text,company_place text,company_phone text,company_pin,rent text,pending integer,status text,photo text,Proof text)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
// TODO Auto-generated method stub
}
}