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"
Related
I am beginner and I had a test. I did all tasks, but I have a problem -
public class HttpTask extends AsyncTask<Integer, String, String> {####
ProgressDialog dialog;
Context context;
public HttpTask(Activity activity) {
//init progress dialog
dialog = new ProgressDialog(context);****
dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
}
protected void onPreExecute() {
// show progress dialog
dialog.setMessage("Loading...");
dialog.setCancelable(false);
}
protected String doInBackground(Integer... params) {
//freeze system to 5 seconds
try {
int seconds = params[0]*5;####
TimeUnit.SECONDS.sleep(seconds);
} catch (InterruptedException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(final String success) {
// if there is progress dialog hide it
dialog.dismiss();
}
}
It crashes, when I try to compile it (I showed where are problems with * sign):
08-03 10:43:10.873 29441-29441/? E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.NullPointerException
at android.app.AlertDialog.resolveDialogTheme(AlertDialog.java:142)
at android.app.AlertDialog.<init>(AlertDialog.java:98)
at android.app.ProgressDialog.<init>(ProgressDialog.java:77)
at net.joerichard.androidtest.main.f.HttpTask.<init>(HttpTask.java:26)
at net.joerichard.androidtest.main.f.F_Networking_Activity$1.onClick(F_Networking_Activity.java:27)
at android.view.View.performClick(View.java:4107)
at android.view.View$PerformClick.run(View.java:17166)
at android.os.Handler.handleCallback(Handler.java:615)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:155)
at android.app.ActivityThread.main(ActivityThread.java:5559)
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:1074)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:841)
at dalvik.system.NativeStart.main(Native Method)
08-03 10:43:10.913 754-877/? E/EmbeddedLogger﹕ App crashed! Process: net.joerichard.androidtest
08-03 10:43:10.913 754-877/? E/EmbeddedLogger﹕ App crashed! Package: net.joerichard.androidtest v1 (1.0)
08-03 10:43:10.913 754-877/? E/EmbeddedLogger﹕ Application Label: AndroidTest
This is class of main activity.
public class F_Networking_Activity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_f__networking_);
// bDownload: start HttpTask
Button bDownload = (Button) findViewById(R.id.bDownload);
bDownload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
HttpTask task = new HttpTask(F_Networking_Activity.this);****
task.execute();
}
});
}
Thank you for your answers. Now I have another problem (I showed with # sign of second problems)
08-03 11:28:18.292 754-877/? E/EmbeddedLogger﹕ App crashed! Process: net.joerichard.androidtest'
08-03 11:28:18.292 754-877/? E/EmbeddedLogger﹕ App crashed! Package: net.joerichard.androidtest v1 (1.0)
08-03 11:28:18.292 754-877/? E/EmbeddedLogger﹕ Application Label: AndroidTest
08-03 11:28:18.292 30544-30726/? E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #1
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:299)
at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
at java.util.concurrent.FutureTask.run(FutureTask.java:137)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
at java.lang.Thread.run(Thread.java:864)
Caused by: java.lang.ArrayIndexOutOfBoundsException: length=0; index=0
at net.joerichard.androidtest.main.f.HttpTask.doInBackground(HttpTask.java:40)
at net.joerichard.androidtest.main.f.HttpTask.doInBackground(HttpTask.java:20)
at android.os.AsyncTask$2.call(AsyncTask.java:287)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
at java.util.concurrent.FutureTask.run(FutureTask.java:137)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
at java.lang.Thread.run(Thread.java:864)
Actually, your context is null because you didn't initialize it.
Add one extra line inside your HttpTask:
public HttpTask(Activity activity) {
this.context = activity;
dialog = new ProgressDialog(context);
dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
}
and change Context to Activity like this:
Activity context;
Now call this context anywhere in your class.
Yes you must get NullPointer. Because your context is null.
Change this like
public HttpTask(Context _context) {
context = _context;
//init progress dialog
dialog = new ProgressDialog(context);****
dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
}
I'm trying to implement a system service on Android with inter-process communication based on binding a messenger. For this I'm following this tutorial:
http://www.survivingwithandroid.com/2014/01/android-bound-service-ipc-with-messenger.html
But no matter what I'm trying, i can't get it to work.
I found different tutorials online but in the end they are all based on the same procedure.
The app will crash right away when I'm trying to communicate with the service.
Error message
10-09 15:40:33.490 3468-3468/com.example.stenosis.testservice E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.stenosis.testservice, PID: 3468
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.stenosis.testservice/com.example.stenosis.testservice.MyActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2184)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2233)
at android.app.ActivityThread.access$800(ActivityThread.java:135)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
at android.os.Handler.dispatchMessage(Handler.java:102)
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: java.lang.NullPointerException
at com.example.stenosis.testservice.MyActivity.sendMsg(MyActivity.java:87)
at com.example.stenosis.testservice.MyActivity.onCreate(MyActivity.java:49)
at android.app.Activity.performCreate(Activity.java:5231)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2148)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2233)
at android.app.ActivityThread.access$800(ActivityThread.java:135)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
at android.os.Handler.dispatchMessage(Handler.java:102)
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)
MyActivity.java:
public class MyActivity extends Activity {
private ServiceConnection sConn;
private Messenger messenger;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
// Service Connection to handle system callbacks
sConn = new ServiceConnection() {
#Override
public void onServiceDisconnected(ComponentName name) {
messenger = null;
}
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
// We are conntected to the service
messenger = new Messenger(service);
}
};
// We bind to the service
bindService(new Intent(this, MyService.class), sConn, Context.BIND_AUTO_CREATE);
// Try to send a message to the service
sendMsg();
}
// This class handles the Service response
class ResponseHandler extends Handler {
#Override
public void handleMessage(Message msg) {
int respCode = msg.what;
String result = "";
switch (respCode) {
case MyService.TO_UPPER_CASE_RESPONSE: {
result = msg.getData().getString("respData");
System.out.println("result");
Toast.makeText(getApplicationContext(), result, Toast.LENGTH_LONG).show();
}
}
}
}
public void sendMsg() {
String val = "This is a test";
Message msg = Message
.obtain(null, MyService.TO_UPPER_CASE);
msg.replyTo = new Messenger(new ResponseHandler());
// We pass the value
Bundle b = new Bundle();
b.putString("data", val);
msg.setData(b);
try {
messenger.send(msg);
} catch (RemoteException e) {
e.printStackTrace();
}
}
}
MyService.java
public class MyService extends Service {
public static final int TO_UPPER_CASE = 0;
public static final int TO_UPPER_CASE_RESPONSE = 1;
private Messenger msg = new Messenger(new ConvertHanlder());;
#Override
public IBinder onBind(Intent intent) {
return msg.getBinder();
}
class ConvertHanlder extends Handler {
#Override
public void handleMessage(Message msg) {
// This is the action
int msgType = msg.what;
switch (msgType) {
case TO_UPPER_CASE: {
try {
// Incoming data
String data = msg.getData().getString("data");
Message resp = Message.obtain(null, TO_UPPER_CASE_RESPONSE);
Bundle bResp = new Bundle();
bResp.putString("respData", data.toUpperCase());
resp.setData(bResp);
msg.replyTo.send(resp);
} catch (RemoteException e) {
e.printStackTrace();
}
break;
}
default:
super.handleMessage(msg);
}
}
}
}
AndroidManifest.xml
<service android:name=".MyService" android:process=":convertprc"/>
Your problem is that the messanger property is null. You are experiencing concurrency problem. The bindService method is asynchronous - it returns immediately and performs the binding in a background thread. When the binding is done, the onServiceConnected method is invoked. When you try to send the message, the messanger is still not initialized because the onServiceConnected method is hasn't been executed yet.
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 very new to android. I have a counter on some SomeActivity, but when I get to the page corresponding to SomeActivity, my app crashes :
final TextView counter = (TextView) findViewById(R.id.laws_counter);
ImageView handDown = (ImageView) findViewById(R.id.handViewDown);
counter.setText("" + 0);
I want that on click of the handown, the counter is idented by -1. Here's
handDown.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(NewsActivity.this,
"The favorite list would appear on clicking this icon",
Toast.LENGTH_LONG).show();
setDown();
}
private void setDown() {
String count = counter.getText().toString();
int now_count = Integer.parseInt(count) +1;
counter.setText(String.valueOf(now_count));
}
});
Is this code correct ?
Update : here's the logcat
10-22 00:18:05.579: ERROR/AndroidRuntime(378): FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.donnfelker.android.bootstrap/com.donnfelker.android.bootstrap.ui.NewsActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1647)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
at android.app.ActivityThread.access$1500(ActivityThread.java:117)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:123)
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:839)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.donnfelker.android.bootstrap.ui.NewsActivity.onCreate(NewsActivity.java:41)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
... 11 more
There are many ways that you can implement that functionality but think this would be an easy solution.
Make a helper method:
public class PreferencesData {
public static void saveInt(Context context, String key, int value) {
SharedPreferences sharedPrefs = PreferenceManager
.getDefaultSharedPreferences(context);
sharedPrefs.edit().putInt(key, value).commit();
}
public static int getInt(Context context, String key, int defaultValue) {
SharedPreferences sharedPrefs = PreferenceManager
.getDefaultSharedPreferences(context);
return sharedPrefs.getInt(key, defaultValue);
}
}
Then simply call the putInt method to save the counter in any Activity and getInt to get it again in any other Activity. As long as you use the same key both places.
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
}
}