In my android application I used sharedpreference to store values in two activites like in first activity to store the values of login. So once user logs in, his username and password is saved and he will be routed to calculation activity, where user needs to fill his data inside several edittexts here I used second shared preference to store the edittext value. On pressing the show report button, user is directed to the next page that is daily prediction. So next time when user want to see the prediction, if he has logged in then he needs to skip the above said two activities and display the result. In my case I am able to achieve the login process correctly, but I used the second sharedpreference to store the edittext value the app is crashing. I am giving my code below.
first activity .. login activity
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
setContentView(R.layout.directcalc_xm);
/*
* Check if we successfully logged in before.
* If we did, redirect to calculation page
*/
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
if (settings.getString("logged", "").toString().equals("logged") && settings.getString("log", "").toString().equals("log"))
{
Intent intent = new Intent(DirectCalculation.this, FullExplanationEntry.class);
startActivity(intent);
}
else
{
btn1 = (Button) findViewById ( R.id.button1);
btn2 = (Button) findViewById ( R.id.button2);
btn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(DirectCalculation.this, SignInActivity.class);
startActivity(intent);
}
});
btn2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent in = new Intent(DirectCalculation.this, SignUpActivity.class);
startActivity(in);
}
});
}
second Activity .. calculation page
if(firstName.equals(""))
{
Toast.makeText(getApplicationContext(), "First Name should not be left blank.. Please enter your First Name and try once again.", Toast.LENGTH_LONG).show();
return;
}
else if(lastName.equals(""))
{
Toast.makeText(getApplicationContext(), "Last Name should not be left blank.. Please enter your Last Name and try once again.", Toast.LENGTH_LONG).show();
return;
}
else if(callFirstName.equals(""))
{
Toast.makeText(getApplicationContext(), "Please enter your First Name that is currently used and try once again.", Toast.LENGTH_LONG).show();
return;
}
else
{
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("log", "log");
editor.commit();
Intent i = new Intent(this, TabLayoutActivity.class);
//Personal Year
i.putExtra("name18",sum18 + "");
//Personal Month
i.putExtra("name19",sum19 + "");
//Personal Dya
i.putExtra("name20",sum20 + "");
//Current Pinnacle
i.putExtra("pin", pin + "");
//Current Challenge
i.putExtra("ch", ch + "");
i.putExtra("yearstr", yearstr);
i.putExtra("monthstr", monthstr);
i.putExtra("daystr", daystr);
startActivity(i);
}
}
logcat
01-17 08:37:30.800: D/Single Product Details(1267): {"product":[{"updated_at":"0000-00-00 00:00:00","pyno":"4","pdyno":"4","pmnno":"4","pdaynumber":"This is the prediction for Personal Day Number 4.","pmonthnumber":"This is the prediction for Personal Month Number 4.","pyearnumber":"This is the prediction for Personal Year Number 4.","created_at":"2013-11-28 01:16:49","rthoughtnumber":"This is the prediction for Relational Thought Number 4.","pid":"4","rthno":"4"}],"success":1}
01-17 08:37:31.380: D/Single Product Details(1267): {"product":[{"pinnacle":"This is the prediction for Pinnacle Number 6.","created_at":"2013-11-23 03:08:57","pid":"6","updated_at":"0000-00-00 00:00:00","challenge":"This is the prediction for Challenge Number 6.","pinnum":"6","chnum":"6"}],"success":1}
01-17 08:37:31.461: I/Choreographer(1267): Skipped 37 frames! The application may be doing too much work on its main thread.
01-17 08:37:31.769: I/Choreographer(1267): Skipped 32 frames! The application may be doing too much work on its main thread.
01-17 08:37:32.130: I/Choreographer(1267): Skipped 69 frames! The application may be doing too much work on its main thread.
01-17 08:38:00.560: D/AndroidRuntime(1313): Shutting down VM
01-17 08:38:00.560: W/dalvikvm(1313): threadid=1: thread exiting with uncaught exception (group=0x40a71930)
01-17 08:38:00.699: E/AndroidRuntime(1313): FATAL EXCEPTION: main
01-17 08:38:00.699: E/AndroidRuntime(1313): java.lang.RuntimeException: Unable to instantiate application android.app.Application: java.lang.NullPointerException
01-17 08:38:00.699: E/AndroidRuntime(1313): at android.app.LoadedApk.makeApplication(LoadedApk.java:504)
01-17 08:38:00.699: E/AndroidRuntime(1313): at android.app.ActivityThread.handleBindApplication(ActivityThread.java:4364)
01-17 08:38:00.699: E/AndroidRuntime(1313): at android.app.ActivityThread.access$1300(ActivityThread.java:141)
01-17 08:38:00.699: E/AndroidRuntime(1313): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1294)
01-17 08:38:00.699: E/AndroidRuntime(1313): at android.os.Handler.dispatchMessage(Handler.java:99)
01-17 08:38:00.699: E/AndroidRuntime(1313): at android.os.Looper.loop(Looper.java:137)
01-17 08:38:00.699: E/AndroidRuntime(1313): at android.app.ActivityThread.main(ActivityThread.java:5041)
01-17 08:38:00.699: E/AndroidRuntime(1313): at java.lang.reflect.Method.invokeNative(Native Method)
01-17 08:38:00.699: E/AndroidRuntime(1313): at java.lang.reflect.Method.invoke(Method.java:511)
01-17 08:38:00.699: E/AndroidRuntime(1313): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
01-17 08:38:00.699: E/AndroidRuntime(1313): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
01-17 08:38:00.699: E/AndroidRuntime(1313): at dalvik.system.NativeStart.main(Native Method)
01-17 08:38:00.699: E/AndroidRuntime(1313): Caused by: java.lang.NullPointerException
01-17 08:38:00.699: E/AndroidRuntime(1313): at android.app.LoadedApk.initializeJavaContextClassLoader(LoadedApk.java:379)
01-17 08:38:00.699: E/AndroidRuntime(1313): at android.app.LoadedApk.getClassLoader(LoadedApk.java:322)
01-17 08:38:00.699: E/AndroidRuntime(1313): at android.app.LoadedApk.makeApplication(LoadedApk.java:496)
01-17 08:38:00.699: E/AndroidRuntime(1313): ... 11 more
SignIn Activity
if(password.equals(storedPassword))
{
Toast.makeText(SignInActivity.this, "Login Successfull", Toast.LENGTH_LONG).show();
/*
* So login information is correct,
* we will save the Preference data
* and redirect to the next activity.
*/
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("logged", "logged");
editor.commit();
// the data is verified correct and the activity id redirecting to the user details entry page.
Intent i = new Intent(SignInActivity.this,FullExplanationEntry.class);
startActivity(i);
}
and when pressing button I need to go to third activity that is TabLayoutActivity
You are on 4.0 right ? No fault of your part - see this issue and for a very nice explanation RuntimeException: Unable to instantiate application
Related
If wifi or mobile data is not enabled, it should ask the user, if he clicks yes in the AlertDialog, it will go to the settings.
This is inside main, on create, when the update button clicked:
btnUpdate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.v(TAG,"ButtonUpdate clicked");
connectIfNecessary();
currentDate = Calendar.getInstance();
formatter= new SimpleDateFormat("yyyy-MM-dd");
new UpdateDB(MainActivity.this);
txtLastUpdateShow.setText(formatter.format(currentDate.getTime()));
});
This is connectifnecessary:
public void connectIfNecessary(){
Log.v(TAG, "main connectIfNecessary");
if(!isConnected()){
final Context ctx = this;
AlertDialog.Builder builder = new AlertDialog.Builder(ctx);
builder.setCancelable(true);
builder.setMessage("need internet");
builder.setTitle("do you want to enable it now?");
builder.setPositiveButton("yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
ctx.startActivity(new Intent(Settings.ACTION_WIRELESS_SETTINGS));
}
});
builder.setNegativeButton("no", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
return;
}
});
builder.setOnCancelListener(new DialogInterface.OnCancelListener() {
public void onCancel(DialogInterface dialog) {
return;
}
});
builder.show();
}
}
this is isConnected:
public boolean isConnected(){
Log.v(TAG, "mainisconnected");
ConnectivityManager conectivtyManager = (ConnectivityManager)
getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
if (conectivtyManager.getActiveNetworkInfo() != null
&& conectivtyManager.getActiveNetworkInfo().isAvailable()
&& conectivtyManager.getActiveNetworkInfo().isConnected()) {
Log.v(TAG, "mainisconnected true");
return true;
} else {
Log.v(TAG, "mainisconnected false");
return false;
}
}
in updatedb constructor, it will call asynctask to connect websites.
When i run this, and click update button, it crashes because it goes into updatedb withpout asking me in builder. The errors:
FATAL EXCEPTION: AsyncTask #1
Process: com.cursedchico.IstanbulEventPool, PID: 13068
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:300)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:841)
Caused by: java.lang.NullPointerException
at com.cursedchico.IstanbulEventPool.EventRetriever.doInBackground(UpdateDB.java:303)
at com.cursedchico.IstanbulEventPool.EventRetriever.doInBackground(UpdateDB.java:109)
at android.os.AsyncTask$2.call(AsyncTask.java:288)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:841)
01-01 18:48:00.299 13068-13068/com.cursedchico.IstanbulEventPool E/WindowManager: android.view.WindowLeaked: Activity com.cursedchico.IstanbulEventPool.MainActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{41e17480 V.E..... R.....I. 0,0-488,216} that was originally added here
at android.view.ViewRootImpl.<init>(ViewRootImpl.java:388)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:248)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
at android.app.Dialog.show(Dialog.java:286)
at android.support.v7.app.AlertDialog$Builder.show(AlertDialog.java:902)
at com.cursedchico.IstanbulEventPool.MainActivity.connectIfNecessary(MainActivity.java:106)
at com.cursedchico.IstanbulEventPool.MainActivity$6.onClick(MainActivity.java:276)
at android.view.View.performClick(View.java:4508)
at android.view.View$PerformClick.run(View.java:18675)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5584)
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:1268)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1084)
at dalvik.system.NativeStart.main(Native Method)
01-01 18:48:00.299 13068-13068/com.cursedchico.IstanbulEventPool E/WindowManager: android.view.WindowLeaked: Activity com.cursedchico.IstanbulEventPool.MainActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{41e36258 V.E..... R......D 0,0-488,165} that was originally added here
at android.view.ViewRootImpl.<init>(ViewRootImpl.java:388)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:248)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
at android.app.Dialog.show(Dialog.java:286)
at android.app.ProgressDialog.show(ProgressDialog.java:117)
at android.app.ProgressDialog.show(ProgressDialog.java:100)
at com.cursedchico.IstanbulEventPool.EventRetriever.onPreExecute(UpdateDB.java:269)
at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:587)
at android.os.AsyncTask.execute(AsyncTask.java:535)
at com.cursedchico.IstanbulEventPool.UpdateDB.<init>(UpdateDB.java:56)
at com.cursedchico.IstanbulEventPool.MainActivity$6.onClick(MainActivity.java:280)
at android.view.View.performClick(View.java:4508)
at android.view.View$PerformClick.run(View.java:18675)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5584)
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:1268)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1084)
at dalvik.system.NativeStart.main(Native Method)
MainActivity.java:106) is builder.show()
MainActivity.java:276) connectIfNecessary();
I am getting errors for hours, at first about appcompat, then manifest then layout now this.
I use real tablet device.
When device is not connected , following would be execution flow
Get inside connectIfNecessary()
Create Alert to ask user to enable internet. Please note that only Alter object is created at this moment, it will be displayed on screen only after stack of main thread unwinds.
Return from connectIfNecessary() create instance of updateDB(). Inside this application is crashing
Few simple changes would fix your code.
add isConnected() if check before creating instance of updateDB(). This will cover the CONNECTED case
if the device is NOT CONNECTED, user will shown the alter and take to settings screen. If user enables WIFI from settings and comes back, onResume() of your activity will be called. Check connectivity and add updateDB() here.
I have been able to set up a connection between my socket server (running on ruby) and my client, which is an Android(java) application. I will explain what my goal is.
I have to send a string to my server through the socket. Depending on the contents of the string, the server would execute a process in the database (store, delete, view data, etc).
The first option is to validate the user name/password. Im able to send the correct string, and the server receives it and replies back to me with the correct response (after validating whether or not my username is capable of logging into the application). Now, depending on this response i need to change the current activity (loginActivity) with the next activity (MenuActivity) so that the user can proceed to use the application menu.
Since the socket has to run on a different thread other than the UIThread, im running it using the AsyncTask way. However im having problems triggering the activity change thing after the AsyncTask process is over.
What im doing is, after the whole Async task is done (onPostExecute method) im trying to call up the activity, but its not working. This is what i've tried (based on similar cases i've found during research):
(AsyncTask class)
Context context;
private void AppContext(Context context) {
this.context = context.getApplicationContext();
}
OnPostExecute
Intent NewActivity = new Intent();
NewActivity.setClass(context.getApplicationContext(),MainActivity.class);
context.startActivity(NewActivity);
However this is not working and its causing my app to crash with a "thread exciting with uncaught exception"
I've tried showing only a Toast message that says "Granted" or "Denied" just to test it with a simpler task, but i keep getting the same error so im assuming its got to do with handling the change between the thread on which the Async task is running and the UI thread. Any ideas?
P.S: I've checked the other questions that are similar to mine and tried the suggested code, but nothing's worked.
ERROR LOG
09-29 09:59:11.387: E/AndroidRuntime(2856): FATAL EXCEPTION: main
09-29 09:59:11.387: E/AndroidRuntime(2856): java.lang.NullPointerException
09-29 09:59:11.387: E/AndroidRuntime(2856): at com.example.prescoterm.SocketClass.onPostExecute(SocketClass.java:111)
09-29 09:59:11.387: E/AndroidRuntime(2856): at com.example.prescoterm.SocketClass.onPostExecute(SocketClass.java:1)
09-29 09:59:11.387: E/AndroidRuntime(2856): at android.os.AsyncTask.finish(AsyncTask.java:602)
09-29 09:59:11.387: E/AndroidRuntime(2856): at android.os.AsyncTask.access$600(AsyncTask.java:156)
09-29 09:59:11.387: E/AndroidRuntime(2856): at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:615)
09-29 09:59:11.387: E/AndroidRuntime(2856): at android.os.Handler.dispatchMessage(Handler.java:99)
09-29 09:59:11.387: E/AndroidRuntime(2856): at android.os.Looper.loop(Looper.java:137)
09-29 09:59:11.387: E/AndroidRuntime(2856): at android.app.ActivityThread.main(ActivityThread.java:4424)
09-29 09:59:11.387: E/AndroidRuntime(2856): at java.lang.reflect.Method.invokeNative(Native Method)
09-29 09:59:11.387: E/AndroidRuntime(2856): at java.lang.reflect.Method.invoke(Method.java:511)
09-29 09:59:11.387: E/AndroidRuntime(2856): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
09-29 09:59:11.387: E/AndroidRuntime(2856): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
09-29 09:59:11.387: E/AndroidRuntime(2856): at dalvik.system.NativeStart.main(Native Method)
Ok so i found a workaround this, now i would like to hear from you guys if you think this'd be a suitable solution.
Since the problem was that the context was coming up null at my AsyncTask class, i decided to load the value on a variable from the moment the application start.
context = this.getApplicationContext();
new SocketReception().setContext(context);
On my SocketReception Class i had a setContext(context) method.
public void setContext(Context context)
{
SocketReception.appContext= context;
};
Now, on my AsyncTask post.execute i call the new activity like this:
SocketReception.appContext.startActivity(NewActivity);
Its now working, but i want to know if this is a convenient approach or if i should keep looking for a different solution.
P.S: I had to add the unpopular "FLAG_ACTIVITY_NEW_TASK", will research on how to avoid this later on.
I have used this asynctask directly in activity and work fine, may be help. When i try call Intent i = new Intent(getApplicationContext(), VyberIcoActivitySD.class); in class without context ( class extended not Activity, Fragment... ) i have not result...
class SynchroAllIcosSD extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(SynchroIcoActivitySD.this);
pDialog.setMessage(getString(R.string.progdata));
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
protected String doInBackground(String... args) {
//do something
return null;
}
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
Intent i = new Intent(getApplicationContext(), VyberIcoActivitySD.class);
Bundle extras = new Bundle();
extras.putString("odkade", "100");
extras.putString("page", "1");
i.putExtras(extras);
startActivity(i);
finish();
}
});
}
}
I am pretty new to both android and NFC. I am working on an NFC related application as a college project that reads the data from tags and lists them. Although I am able to do so, I am facing problems with intent where I am supposed to mail this list to user on button click.
Can someone please tell me where I am going wrong and help with a detailed step-by-step approach. Huge thanks..!!
Here's the WebServiceActivity:
public class WebServiceActivity extends Activity {
Intent intent = getIntent();
String studlist = intent.getStringExtra("studlist");
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.webservice);
TextView mailtext = (TextView) findViewById(R.id.students);
TextView mailbody = (TextView) findViewById(R.id.emailtext);
mailbody.setText("Here is the list for Tranport Tracking For Today: \n" + studlist);
Button send=(Button) findViewById(R.id.emailsendbutton);
send.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
Log.i("Send email", "");
String[] TO = {"h.trivedi04#gmail.com"};
String[] CC = {"h.trivedi04#gmail.com", "harshit.trivedi22#gmail.com"};
Intent emailIntent = new Intent(Intent.ACTION_SEND);
emailIntent.setData(Uri.parse("mailto:"));
emailIntent.setType("text/plain");
emailIntent.putExtra(Intent.EXTRA_EMAIL, TO);
emailIntent.putExtra(Intent.EXTRA_CC, CC);
emailIntent.putExtra(Intent.EXTRA_SUBJECT, "Student Transport Track For Today");
emailIntent.putExtra(Intent.EXTRA_TEXT, studlist);
try {
startActivity(Intent.createChooser(emailIntent, "Send mail..."));
finish();
Log.i("Finished sending email...", "");
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(WebServiceActivity.this,
"There is no email client installed.", Toast.LENGTH_SHORT).show();
}
}
});
}
}
And the main activity TransportActivity has:
Button webServiceButton = (Button)this.findViewById(R.id.webServiceButton);
webServiceButton.setOnClickListener(new android.view.View.OnClickListener()
{
public void onClick(View view) {
Intent intent = new Intent( view.getContext(), WebServiceActivity.class);
intent.putExtra("studlist", students.getText().toString());
startActivity(intent);
}
});
Here's the LogCat for the problem:
05-01 21:37:31.267: E/AndroidRuntime(27758): FATAL EXCEPTION: main
05-01 21:37:31.267: E/AndroidRuntime(27758): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.harshit.studenttranstrack/com.harshit.studenttranstrack.WebServiceActivity}: java.lang.NullPointerException
05-01 21:37:31.267: E/AndroidRuntime(27758): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2229)
05-01 21:37:31.267: E/AndroidRuntime(27758): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2359)
05-01 21:37:31.267: E/AndroidRuntime(27758): at android.app.ActivityThread.access$700(ActivityThread.java:165)
05-01 21:37:31.267: E/AndroidRuntime(27758): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1326)
05-01 21:37:31.267: E/AndroidRuntime(27758): at android.os.Handler.dispatchMessage(Handler.java:99)
05-01 21:37:31.267: E/AndroidRuntime(27758): at android.os.Looper.loop(Looper.java:137)
05-01 21:37:31.267: E/AndroidRuntime(27758): at android.app.ActivityThread.main(ActivityThread.java:5455)
05-01 21:37:31.267: E/AndroidRuntime(27758): at java.lang.reflect.Method.invokeNative(Native Method)
05-01 21:37:31.267: E/AndroidRuntime(27758): at java.lang.reflect.Method.invoke(Method.java:525)
05-01 21:37:31.267: E/AndroidRuntime(27758): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1209)
05-01 21:37:31.267: E/AndroidRuntime(27758): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1025)
05-01 21:37:31.267: E/AndroidRuntime(27758): at dalvik.system.NativeStart.main(Native Method)
05-01 21:37:31.267: E/AndroidRuntime(27758): Caused by: java.lang.NullPointerException
05-01 21:37:31.267: E/AndroidRuntime(27758): at com.harshit.studenttranstrack.WebServiceActivity.<init>(WebServiceActivity.java:22)
05-01 21:37:31.267: E/AndroidRuntime(27758): at java.lang.Class.newInstanceImpl(Native Method)
Try it like this inside onCreate() method.
Intent intent = this.getIntent(); //in the WebServiceActivity activity
String studlist = (String) intent .getStringExtra("studlist");
You can't getIntent() before onCreate() .There's simply no Intent available at that point. I believe the same is true for anything that requires a Context.
Set these in onCreate() method
String studlist = this.getIntent().getStringExtra("studlist");
I am rather new to Android/Java programming and looking for some help with a very, very basic app that I am working with. I am purely building this just to get used to Java coding and building applications for Droids, so bear with me.
I have 10 radio buttons grouped together and only one of them is the right answer (button #10). If the user clicks on any of them 1-9 I have it displaying a message that says "sorry try again", but if they click on #10, I want it to take them to a new activity, namely a page where I will put up some graphics and text that says congraulations and things of that nature. The buttons work fine for 1-9, but when I click on #10 I am gettinga force close error.
Here's what I have so far:
public class MainQuiz extends Activity implements OnCheckedChangeListener, android.widget.RadioGroup.OnCheckedChangeListener {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_quiz);
((RadioGroup)findViewById(R.id.radio_group)).setOnCheckedChangeListener(this);}
public void onCheckedChanged(RadioGroup radioGroup, int checkedId) {
String numeral = null;
if (checkedId == R.id.button1) {
numeral = "Nope, try again!";
} else if (checkedId == R.id.button2) {
numeral = "Nope, try again!";
} else if (checkedId == R.id.button3) {
numeral = "Nope, try again!";
}
else if (checkedId == R.id.button4) {
numeral = "Nope, try again!";
}
else if (checkedId == R.id.button5) {
numeral = "Nope, try again!";
}
else if (checkedId == R.id.button6) {
numeral = "Nope, try again!";
}
else if (checkedId == R.id.button7) {
numeral = "Nope, try again!";
}
else if (checkedId == R.id.button8) {
numeral = "Nope, try again!";
}
else if (checkedId == R.id.button9) {
numeral = "Nope, try again!";
}
else if (checkedId == R.id.button10) {
Intent myIntent = new Intent(MainQuiz.this, CorrectAnswer.class);
MainQuiz.this.startActivity(myIntent);
}
Toast.makeText(getApplicationContext(), ""+numeral+"",
Toast.LENGTH_SHORT).show(); }
Any help would be apprecitaed, I am sure this is a simple fix and I am sure it is something glaring in the syntax and code that I have messed up, but again, I am new :)
Thanks!
Here is the log after the Force Close:
11-14 13:56:48.982: D/AndroidRuntime(862): Shutting down VM
11-14 13:56:48.982: W/dalvikvm(862): threadid=1: thread exiting with uncaught exception (group=0x4001d800)
11-14 13:56:48.992: E/AndroidRuntime(862): FATAL EXCEPTION: main
11-14 13:56:48.992: E/AndroidRuntime(862): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.test.quiz/com.test.quiz.CorrectAnswer}: java.lang.ClassCastException: com.test.quiz.CorrectAnswer
11-14 13:56:48.992: E/AndroidRuntime(862): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2585)
11-14 13:56:48.992: E/AndroidRuntime(862): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
11-14 13:56:48.992: E/AndroidRuntime(862): at android.app.ActivityThread.access$2300(ActivityThread.java:125)
11-14 13:56:48.992: E/AndroidRuntime(862): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
11-14 13:56:48.992: E/AndroidRuntime(862): at android.os.Handler.dispatchMessage(Handler.java:99)
11-14 13:56:48.992: E/AndroidRuntime(862): at android.os.Looper.loop(Looper.java:123)
11-14 13:56:48.992: E/AndroidRuntime(862): at android.app.ActivityThread.main(ActivityThread.java:4627)
11-14 13:56:48.992: E/AndroidRuntime(862): at java.lang.reflect.Method.invokeNative(Native Method)
11-14 13:56:48.992: E/AndroidRuntime(862): at java.lang.reflect.Method.invoke(Method.java:521)
11-14 13:56:48.992: E/AndroidRuntime(862): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
11-14 13:56:48.992: E/AndroidRuntime(862): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
11-14 13:56:48.992: E/AndroidRuntime(862): at dalvik.system.NativeStart.main(Native Method)
11-14 13:56:48.992: E/AndroidRuntime(862): Caused by: java.lang.ClassCastException: com.test.quiz.CorrectAnswer
11-14 13:56:48.992: E/AndroidRuntime(862): at android.app.Instrumentation.newActivity(Instrumentation.java:1021)
11-14 13:56:48.992: E/AndroidRuntime(862): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2577)
11-14 13:56:48.992: E/AndroidRuntime(862): ... 11 more
The force close will always put an exception stack trace in your logcat file. Please put this in future posts, it tells us what line crashed and why.
My guess from your code and newness to Android- you probably didn't add the CorrectAnswer activity to your manifest.
I don't know what is your problem, but you can improve your code:
use "switch - case" construction.
switch (chekedId) {
case R.id.button10:
Intent myIntent = new Intent(MainQuiz.this, CorrectAnswer.class);
startActivity(myIntent);
break;
default:
Toast.makeText(getApplicationContext(), "Nope, try again!",
Toast.LENGTH_SHORT).show();
}
It seems like this line is probably what is causing your problems.
MainQuiz.this.startActivity(myIntent);
Remove the MainQuiz, and it should work
this.startActivity(myIntent);
MainQuiz.this.startActivity(myIntent);
replace by
startActivity(myIntent);
I'm having a problem, and I already tried everything I found on this site, it's not helping, so I'm asking this question myself.
my code is:
public class MyActivity extends Activity{
protected PositionSense positionSense;
protected Preferences preferences;
String IP;
String ID;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
positionSense = new PositionSense(this, null);
SharedPreferences settings = getSharedPreferences("preferences", 0);
IP = settings.getString("ip", "http://192.168.1.3:8080/servlet");
ID = settings.getString("id", "USER");
}
Later on, I use these variables in a background running thread that contacts the servlet and sends some info (including position and ID of the user which is saved in preferences)
I'm not posting all of that because I don't want to clog up the thread more than necessary (but if it is needed, I will post it all)
In any case, it doesn't work and it gives me the following error log:
09-14 16:47:20.854: WARN/dalvikvm(552): threadid=1: thread exiting with uncaught exception (group=0x409c01f8)
09-14 16:47:20.884: ERROR/AndroidRuntime(552): FATAL EXCEPTION: main
java.lang.IllegalStateException: Could not execute method of the activity
at android.view.View$1.onClick(View.java:3044)
at android.view.View.performClick(View.java:3511)
at android.view.View$PerformClick.run(View.java:14105)
at android.os.Handler.handleCallback(Handler.java:605)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4424)
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:784)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at android.view.View$1.onClick(View.java:3039)
... 11 more
Caused by: java.lang.NullPointerException
at com.moodswings.MoodSwingsActivity.clickHappy(MoodSwingsActivity.java:94)
... 14 more
I don't know what to do about it.
Can someone give me the SIMPLEST possible way to save 2 strings in preferences in one activity that are used in some other activity within the same application? It's supposed to be really simple, but I simply cannot make it work, and I'm nearing my deadline.
Thanks!
To save to shared preferences you can try:
String ip = "192.168.1.1";
SharedPreferences prefs = getSharedPreferences("IP", Context.MODE_PRIVATE);
prefs.edit().putString("Sample IP", ip).commit();
To get the information from the shared preferences you can try:
String newIP = prefs.getString("Sample IP");//You can also place a default value if needed; to bypass the null character.
Now to pass them into activities you can try doing an intent call like below
**Activity One
Intent intent = new Intent(getApplicationContext(),SecondActivity.class);
intent.putExtra("IP",newIp);
startActivity(intent);
**Activity Two
Bundle extras = intent.getExtras();
String tmp = extras.getString("IP");
Also you can use this link to reference.