I want to send an Email at particular date. I am developing a service will be sending email at particular date. I spent hours trying to figure out for how to send an email at particular date in service background even if my keypad is lock. Can someone help me how to do this?
Here is Log Cat Info
08-16 15:18:00.122: E/AndroidRuntime(632): java.lang.RuntimeException: Unable to start service com.demo.EmailService#40561c20 with Intent { cmp=com.demo/.EmailService }: android.util.AndroidRuntimeException: Calling startActivity() from outside of an Activity context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want?
08-16 15:18:00.122: E/AndroidRuntime(632): at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:2052)
08-16 15:18:00.122: E/AndroidRuntime(632): at android.app.ActivityThread.access$2800(ActivityThread.java:117)
08-16 15:18:00.122: E/AndroidRuntime(632): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:994)
08-16 15:18:00.122: E/AndroidRuntime(632): at android.os.Handler.dispatchMessage(Handler.java:99)
08-16 15:18:00.122: E/AndroidRuntime(632): at android.os.Looper.loop(Looper.java:123)
08-16 15:18:00.122: E/AndroidRuntime(632): at android.app.ActivityThread.main(ActivityThread.java:3683)
08-16 15:18:00.122: E/AndroidRuntime(632): at java.lang.reflect.Method.invokeNative(Native Method)
08-16 15:18:00.122: E/AndroidRuntime(632): at java.lang.reflect.Method.invoke(Method.java:507)
08-16 15:18:00.122: E/AndroidRuntime(632): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
08-16 15:18:00.122: E/AndroidRuntime(632): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
08-16 15:18:00.122: E/AndroidRuntime(632): at dalvik.system.NativeStart.main(Native Method)
08-16 15:18:00.122: E/AndroidRuntime(632): Caused by: android.util.AndroidRuntimeException: Calling startActivity() from outside of an Activity context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want?
08-16 15:18:00.122: E/AndroidRuntime(632): at android.app.ContextImpl.startActivity(ContextImpl.java:621)
08-16 15:18:00.122: E/AndroidRuntime(632): at android.content.ContextWrapper.startActivity(ContextWrapper.java:258)
08-16 15:18:00.122: E/AndroidRuntime(632): at com.demo.EmailService.sendEmail(EmailService.java:86)
08-16 15:18:00.122: E/AndroidRuntime(632): at com.demo.EmailService.onStartCommand(EmailService.java:44)
08-16 15:18:00.122: E/AndroidRuntime(632): at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:2039)
Here is my Service Code
public class EmailService extends Service
{
private static final String TAG = null;
private static final String TAG1="MyService";
private static final String LOGTAG = null;
String strServiceName ;
String strSuppliername ;
String strEmail;
String strReplacementDate ;
String strIntervalDays;
String strNextReplacementDate;
String strMyServicePref;
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
public void onCreate()
{
Toast.makeText(this,"My Service Created",Toast.LENGTH_LONG).show();
Log.d(TAG,"ON CREATE");
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId)
{
startService(intent);
sendEmail();
return Service.START_STICKY;
}
protected void sendEmail()
{
SharedPreferences sharedPref1 =getSharedPreferences("MyPref_CellNumber", 0);
SharedPreferences.Editor editor1 = sharedPref1.edit();
strServiceName=sharedPref1.getString("ServiceName" , "a\n");
strSuppliername=sharedPref1.getString("Suppliername" , "a\n");
strEmail=sharedPref1.getString("Email" , "a\n");
strReplacementDate=sharedPref1.getString("ReplacementDate" , "a\n");
strIntervalDays=sharedPref1.getString("IntervalDays" , "a\n");
strNextReplacementDate=sharedPref1.getString("NextReplacementDate" , "a\n");
Log.e(TAG,"ON CREATE" + strServiceName);
Log.e(TAG,"ON CREATE" + strSuppliername);
Log.e(TAG,"ON CREATE" + strEmail);
Log.e(TAG,"ON CREATE" + strReplacementDate);
Log.e(TAG,"ON CREATE" + strIntervalDays);
Log.e(TAG,"ON CREATE" + strNextReplacementDate);
String subject = strServiceName;
String body = strServiceName+","
+strSuppliername+","
+strReplacementDate+","
+strIntervalDays+","
+strNextReplacementDate;
Log.e("body " , " = " + body);
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("message/rfc822");
i.putExtra(Intent.EXTRA_EMAIL , new String[]{strEmail});
i.putExtra(Intent.EXTRA_SUBJECT, subject);
i.putExtra(Intent.EXTRA_TEXT , body);
try
{
startActivity(Intent.createChooser(i, "Send mail...in Service Background"));
}
catch (android.content.ActivityNotFoundException ex)
{
Toast.makeText(EmailService.this, "There are no email clients installed.", Toast.LENGTH_SHORT).show();
}
}
}
I think you should use Alarm Manager.
The Alarm Manager is intended for cases where you want to have your
application code run at a specific time, even if your application is
not currently running.
Related
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");
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
i am try to make back up feature in my app but it give force close error
can any one give some idea whats wrong in my code
pls help me out
here is my code
public class Mydatabase {
private String appName = "";
private String packageName = "";
public static final String DATABASE_NAME = "data.db";
public boolean backup() {
boolean rc = false;
boolean writeable = isSDCardWriteable();
if (writeable) {
File file = new File(Environment.getDataDirectory() + "/data/" + packageName + "/databases/" + DATABASE_NAME);
File fileBackupDir = new File(Environment.getExternalStorageDirectory(), appName + "/backup");
if (!fileBackupDir.exists()) {
fileBackupDir.mkdirs();
}
if (file.exists()) {
File fileBackup = new File(fileBackupDir, DATABASE_NAME);
try {
fileBackup.createNewFile();
FileUtils..copyFile(file, fileBackup);
rc = true;
} catch (IOException ioException) {
//
} catch (Exception exception) {
//
}
}
}
return rc;
}
private boolean isSDCardWriteable() {
boolean rc = false;
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
rc = true;
}
return rc;
}
public Mydatabase(final Context context, final String appName) {
this.appName = appName;
packageName = context.getPackageName();
}
}
this is my log
04-03 00:39:18.595: E/AndroidRuntime(674): FATAL EXCEPTION: main
04-03 00:39:18.595: E/AndroidRuntime(674): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.neelrazin.noteit/com.neelrazin.noteit.Mydatabase}: java.lang.InstantiationException: com.neelrazin.noteit.Mydatabase
04-03 00:39:18.595: E/AndroidRuntime(674): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1569)
04-03 00:39:18.595: E/AndroidRuntime(674): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
04-03 00:39:18.595: E/AndroidRuntime(674): at android.app.ActivityThread.access$1500(ActivityThread.java:117)
04-03 00:39:18.595: E/AndroidRuntime(674): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
04-03 00:39:18.595: E/AndroidRuntime(674): at android.os.Handler.dispatchMessage(Handler.java:99)
04-03 00:39:18.595: E/AndroidRuntime(674): at android.os.Looper.loop(Looper.java:123)
04-03 00:39:18.595: E/AndroidRuntime(674): at android.app.ActivityThread.main(ActivityThread.java:3683)
04-03 00:39:18.595: E/AndroidRuntime(674): at java.lang.reflect.Method.invokeNative(Native Method)
04-03 00:39:18.595: E/AndroidRuntime(674): at java.lang.reflect.Method.invoke(Method.java:507)
04-03 00:39:18.595: E/AndroidRuntime(674): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
04-03 00:39:18.595: E/AndroidRuntime(674): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
04-03 00:39:18.595: E/AndroidRuntime(674): at dalvik.system.NativeStart.main(Native Method)
04-03 00:39:18.595: E/AndroidRuntime(674): Caused by: java.lang.InstantiationException: com.neelrazin.noteit.Mydatabase
04-03 00:39:18.595: E/AndroidRuntime(674): at java.lang.Class.newInstanceImpl(Native Method)
04-03 00:39:18.595: E/AndroidRuntime(674): at java.lang.Class.newInstance(Class.java:1409)
04-03 00:39:18.595: E/AndroidRuntime(674): at android.app.Instrumentation.newActivity(Instrumentation.java:1021)
04-03 00:39:18.595: E/AndroidRuntime(674): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1561)
04-03 00:39:18.595: E/AndroidRuntime(674): ... 11 more
You seem a bit lost.
Here is a functional method to backup your database, you can place it in any class.
public static void backupDatabase() throws IOException {
//Open your local db as the input stream
String inFileName = "/data/data/com.android.exemple/databases/databename.db";
File dbFile = new File(inFileName);
FileInputStream fis = new FileInputStream(dbFile);
String outFileName = Environment.getExternalStorageDirectory()+"/database.db";
//Open the empty db as the output stream
OutputStream output = new FileOutputStream(outFileName);
//transfer bytes from the inputfile to the outputfile
byte[] buffer = new byte[1024];
int length;
while ((length = fis.read(buffer))>0){
output.write(buffer, 0, length);
}
//Close the streams
output.flush();
output.close();
fis.close();
}
You need to add this line in your manifest before the application element
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
Don't forget to change the package name in the inFileName variable and the databasename at both place.
The trace points the finger at the fact that you're trying to launch an Activity called Mydatabase. As we can see from your code snippet, Mydatabase doesn't extend Activity. The system is looking for an Activity to launch, not a class that just derives from Object.
I'm creating a Class that checks to see if the file has been created (Has username and passwords.) and if it does it creates an intent to go to another class to read the data and check it againts a server via FTP. For some reason, I can't get it to work, I've tried everything and read every single web page I could, but no luck.
My Code:
public class LogIn extends Activity implements OnClickListener {
Button send;
EditText user;
EditText pass;
CheckBox staySignedIn;
FileOutputStream Fos;
String a;
String b;
String string = a;
String string2 = b;
String FILENAME = "userandpass";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
send = (Button) findViewById(R.id.bLogIn);
user = (EditText) findViewById(R.id.eTuser);
pass = (EditText) findViewById(R.id.eTpassword);
staySignedIn = (CheckBox) findViewById(R.id.Cbstay);
send.setOnClickListener(this);
if (staySignedIn.isChecked()) {
String a = user.getText().toString();
String b = pass.getText().toString();
File f = new File(FILENAME);
try {
Fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
Fos.write(string.getBytes());
Fos.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
File file = getBaseContext().getFileStreamPath(FILENAME);
if(file.exists());
Intent i = new Intent(LogIn.this, ChatService.class);
}
}
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.bLogIn:
if (pass.length() == 0)
Toast.makeText(this,
"Try to type in your username and password again!",
Toast.LENGTH_LONG).show();
else if (user.length() == 0)
Toast.makeText(this,
"Try to type in your username and password again!",
Toast.LENGTH_LONG).show();
else {
String u = user.getText().toString();
String p = pass.getText().toString();
Bundle send = new Bundle();
send.putString("key", u);
send.putString("key1", p);
Intent a = new Intent(LogIn.this, logincheck.class);
a.putExtra("key", u);
a.putExtra("key1", p);
startActivity(a);
Toast.makeText(this, "Were signing you in!", Toast.LENGTH_LONG)
.show();
break;
}
}
}
}
LogCat:
01-19 11:37:17.601: W/dalvikvm(4411): threadid=1: thread exiting with uncaught exception (group=0x4001d800)
01-19 11:37:17.621: E/AndroidRuntime(4411): FATAL EXCEPTION: main
01-19 11:37:17.621: E/AndroidRuntime(4411): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.gta5news.bananaphone/com.gta5news.bananaphone.LogIn}: java.lang.NullPointerException
01-19 11:37:17.621: E/AndroidRuntime(4411): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
01-19 11:37:17.621: E/AndroidRuntime(4411): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
01-19 11:37:17.621: E/AndroidRuntime(4411): at android.app.ActivityThread.access$2300(ActivityThread.java:125)
01-19 11:37:17.621: E/AndroidRuntime(4411): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
01-19 11:37:17.621: E/AndroidRuntime(4411): at android.os.Handler.dispatchMessage(Handler.java:99)
01-19 11:37:17.621: E/AndroidRuntime(4411): at android.os.Looper.loop(Looper.java:123)
01-19 11:37:17.621: E/AndroidRuntime(4411): at android.app.ActivityThread.main(ActivityThread.java:4627)
01-19 11:37:17.621: E/AndroidRuntime(4411): at java.lang.reflect.Method.invokeNative(Native Method)
01-19 11:37:17.621: E/AndroidRuntime(4411): at java.lang.reflect.Method.invoke(Method.java:521)
01-19 11:37:17.621: E/AndroidRuntime(4411): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
01-19 11:37:17.621: E/AndroidRuntime(4411): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
01-19 11:37:17.621: E/AndroidRuntime(4411):
at dalvik.system.NativeStart.main(Native Method)
01-19 11:37:17.621: E/AndroidRuntime(4411): Caused by: java.lang.NullPointerException
01-19 11:37:17.621: E/AndroidRuntime(4411): at com.gta5news.bananaphone.LogIn.onCreate(LogIn.java:55)
01-19 11:37:17.621: E/AndroidRuntime(4411): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
01-19 11:37:17.621: E/AndroidRuntime(4411): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
If line 55 is
Fos.write(string.getBytes());
then either Fos or string is uninitialized. Given that string is initialized to a which is itself uninitialized, that explains it. You need to assign a proper value to string.
Fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
It seems for some reason openFileOutput returning null which makes Fos null, which is throwing NullPointerException.
Add
if(Fos != null) {
Fos.write(string.getBytes());
Fos.close();
} check.
OR catch NullpointerException.
i cannot find the null pointer exception in my code, i was wondering if anyone could help me find what is giving an error.
code:
package com.dingle.ubat;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.PowerManager;
import android.view.Display;
import android.view.MotionEvent;
import android.widget.Toast;
public class UltraBrightAndroidTorchActivity extends Activity {
/** Called when the activity is first created. */
PowerManager pm;
PowerManager.WakeLock wl;
public boolean flash = false;
public boolean enableFlash = false;
public boolean dimDisplay = false;
Display display = getWindowManager().getDefaultDisplay();
public int windowWidth = display.getWidth();
public int windowHeight = display.getHeight();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
wl = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK, "My Tag");
flash = this.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);
if(flash == true && enableFlash == true){
try {
DroidLED led = new DroidLED();
led.enable(!led.isEnabled());
}
catch(Exception e) {
Toast.makeText(this, "Error interacting with LED.", Toast.LENGTH_SHORT).show();
throw new RuntimeException(e);
} }
wl.acquire();
}
#Override
public boolean onTouchEvent(MotionEvent event) {
//int tx = (int) event.getRawX();
int ty = (int) event.getRawY();
if (ty <= (windowHeight/2)){
dimDisplay = !dimDisplay;
}
if (ty >= (windowHeight/2)){
enableFlash = !enableFlash;
}
return super.onTouchEvent(event);
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
wl.release();
}
#Override
protected void onNewIntent(Intent intent) {
// TODO Auto-generated method stub
super.onNewIntent(intent);
wl.release();
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
wl.release();
}
#Override
protected void onStop() {
// TODO Auto-generated method stub
super.onStop();
wl.release();
}
}
Error list:
12-10 20:40:42.224: W/dalvikvm(274): threadid=3: thread exiting with uncaught exception (group=0x4001b188)
12-10 20:40:42.232: E/AndroidRuntime(274): Uncaught handler: thread main exiting due to uncaught exception
12-10 20:40:42.282: E/AndroidRuntime(274): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.dingle.ubat/com.dingle.ubat.UltraBrightAndroidTorchActivity}: java.lang.NullPointerException
12-10 20:40:42.282: E/AndroidRuntime(274): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2417)
12-10 20:40:42.282: E/AndroidRuntime(274): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2512)
12-10 20:40:42.282: E/AndroidRuntime(274): at android.app.ActivityThread.access$2200(ActivityThread.java:119)
12-10 20:40:42.282: E/AndroidRuntime(274): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1863)
12-10 20:40:42.282: E/AndroidRuntime(274): at android.os.Handler.dispatchMessage(Handler.java:99)
12-10 20:40:42.282: E/AndroidRuntime(274): at android.os.Looper.loop(Looper.java:123)
12-10 20:40:42.282: E/AndroidRuntime(274): at android.app.ActivityThread.main(ActivityThread.java:4363)
12-10 20:40:42.282: E/AndroidRuntime(274): at java.lang.reflect.Method.invokeNative(Native Method)
12-10 20:40:42.282: E/AndroidRuntime(274): at java.lang.reflect.Method.invoke(Method.java:521)
12-10 20:40:42.282: E/AndroidRuntime(274): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:860)
12-10 20:40:42.282: E/AndroidRuntime(274): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
12-10 20:40:42.282: E/AndroidRuntime(274): at dalvik.system.NativeStart.main(Native Method)
12-10 20:40:42.282: E/AndroidRuntime(274): Caused by: java.lang.NullPointerException
12-10 20:40:42.282: E/AndroidRuntime(274): at com.dingle.ubat.UltraBrightAndroidTorchActivity.<init>(UltraBrightAndroidTorchActivity.java:20)
12-10 20:40:42.282: E/AndroidRuntime(274): at java.lang.Class.newInstanceImpl(Native Method)
12-10 20:40:42.282: E/AndroidRuntime(274): at java.lang.Class.newInstance(Class.java:1479)
12-10 20:40:42.282: E/AndroidRuntime(274): at android.app.Instrumentation.newActivity(Instrumentation.java:1021)
12-10 20:40:42.282: E/AndroidRuntime(274): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2409)
12-10 20:40:42.282: E/AndroidRuntime(274): ... 11 more
any help and criticism is greatly appreciated
code is being compiled for android 2.1. code is a basic, crappily coded torch app.
thanx
The code is bailing out on one of these two lines:
Display display = getWindowManager().getDefaultDisplay();
public int windowWidth = display.getWidth();
Either getWindowManager() is returning a null and that first initializer will fail, or getDefaultDisplay() is, and the second one will.
You should probably move these initializations to the onCreate handler. Having them at instance initialization sounds a bit risky - the activity's "environment" might not be completely set up yet at that point.
(And check the return values.)
Activity is full available only after it has been created. This line does not do the intended purpose:
Display display = getWindowManager().getDefaultDisplay();
Move this line and subsequent ones inside onCreate method.