What I'm doing exactly is this:
I have a class "Welcome" that calls another class "textWriter" which contains a method "write". Welcome passes two strings to "write", "name" is the name of the text file to write to and "something" is the thing to print.
i keep getting null pointer error on prt = new PrintStream(output);
here is the logcat
07-22 16:40:22.561: ERROR/AndroidRuntime(2245): FATAL EXCEPTION: main
07-22 16:40:22.561: ERROR/AndroidRuntime(2245): java.lang.NullPointerException
07-22 16:40:22.561: ERROR/AndroidRuntime(2245): at android.content.ContextWrapper.openFileOutput(ContextWrapper.java:158)
07-22 16:40:22.561: ERROR/AndroidRuntime(2245): at com.rhobot.budget.textWriter.write(textWriter.java:24)
07-22 16:40:22.561: ERROR/AndroidRuntime(2245): at com.rhobot.budget.Welcome.setSubChoices(Welcome.java:37)
07-22 16:40:22.561: ERROR/AndroidRuntime(2245): at com.rhobot.budget.Welcome$1.onClick(Welcome.java:76)
07-22 16:40:22.561: ERROR/AndroidRuntime(2245): at android.view.View.performClick(View.java:2408)
07-22 16:40:22.561: ERROR/AndroidRuntime(2245): at android.view.View$PerformClick.run(View.java:8816)
07-22 16:40:22.561: ERROR/AndroidRuntime(2245): at android.os.Handler.handleCallback(Handler.java:587)
07-22 16:40:22.561: ERROR/AndroidRuntime(2245): at android.os.Handler.dispatchMessage(Handler.java:92)
07-22 16:40:22.561: ERROR/AndroidRuntime(2245): at android.os.Looper.loop(Looper.java:123)
07-22 16:40:22.561: ERROR/AndroidRuntime(2245): at android.app.ActivityThread.main(ActivityThread.java:4627)
07-22 16:40:22.561: ERROR/AndroidRuntime(2245): at java.lang.reflect.Method.invokeNative(Native Method)
07-22 16:40:22.561: ERROR/AndroidRuntime(2245): at java.lang.reflect.Method.invoke(Method.java:521)
07-22 16:40:22.561: ERROR/AndroidRuntime(2245): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
07-22 16:40:22.561: ERROR/AndroidRuntime(2245): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
07-22 16:40:22.561: ERROR/AndroidRuntime(2245): at dalvik.system.NativeStart.main(Native Method)
here is the Welcome class:
public class Welcome extends Activity
{
P p = new P(); //shared prefs helper
loadArray la = new loadArray(); //array loader
textWriter tw = new textWriter();
private EditText txtBalance;
private Button btnEnter;
int subItemCount, addItemCount;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.welcomescreen);
capture();
}
public static String sub_choice_key = "sub_choice_key.txt";
public static String sub_compare = "sub_compare.txt";
public static String add_choice_key = "add_choice_key.txt";
public static String add_compare = "add_compare.txt";
public void setSubChoices() throws FileNotFoundException {
// TODO create a master list of choices
tw.write(sub_choice_key,"-1");
tw.write(sub_choice_key,"-2");
tw.write(sub_choice_key,"-3");
tw.write(sub_compare,"-1");
tw.write(sub_compare,"-2");
tw.write(sub_compare,"-3");
p.pisI("subItemCount", 3, this);
}...
Here is the textWriter class
public class textWriter extends Activity{
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
}
public void write(String name, String something) {
try {
FileOutputStream output;
output = openFileOutput(name,MODE_APPEND);
PrintStream prt;
prt = new PrintStream(output);
prt.println(something);
prt.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
id like to emphasize that these are two different files as well, and i am importing all the right stuff i believe.. also i have the line
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
in my android manifest.
what am i doing wrong? is it context? or lack there of? if so how should i implement it?
i am doing it this way because i want to use this textWrite in other programs as an easy (less messy) way of writing data. in my main it could save me about 50 lines of code if i do it this way.
Thanks in advance-
Tricknology
As probablykevin said, the issue is a lack of a valid Context.
One simple fix you could do if you want your class structure to stay the same is to remove the extends Activity from textWriter and instead pass in a Context in the constructor, i.e.:
public class textWriter{
private Context m_context;
public textWriter(Context ctx) {
m_context = ctx;
}
public void write(String name, String something) {
try {
FileOutputStream output;
output = m_context.openFileOutput(name,MODE_APPEND);
PrintStream prt;
prt = new PrintStream(output);
prt.println(something);
prt.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
You'd then need to construct it like so: textWriter tw = new textWriter(this);
Instead of creating a new Activity, place the write method in your original activity that you are calling it from.
The problem arises when textWriter calls openOutputStream() but has not been created yet. So yes, I would say it is a problem of Context because the context calling openOutputStream() has not been created yet.
Related
I would like use JSOUP in two Activity, but in both I have same code.
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button titlebutton = (Button) findViewById(R.id.button1);
titlebutton.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
// Execute Title AsyncTask
new AsyncTest().execute();
}
});
}
private class AsyncTest extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
Connection.Response response = null;
try {
response = Jsoup.connect("http://example.com")
.data("param1", "aaaa")
.data("param2", "bbbb")
.data("param3", "ccc")
.data("param4", "dd")
.execute();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
}
and:
public class Second extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
get();
}
public Connection.Response get()
{
Connection.Response response = null;
try {
response = Jsoup.connect("http://example.com")
.data("param1", "aaaa")
.data("param2", "bbbb")
.data("param3", "ccc")
.data("param4", "dd")
.execute();
} catch (IOException e) {
e.printStackTrace();
}
return response;
}
}
This is only example - I use in Second Activity a lot of operation with JSOUP, so I would like have function get in this class and import it into MainActivity.
I try in MainActivity:
private class AsyncTest extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
Connection.Response response = null;
response = new Second().get();
return null;
}
}
but this return errors:
08-25 21:18:00.164: W/dalvikvm(1552): threadid=11: thread exiting with uncaught exception (group=0x409961f8)
08-25 21:18:00.174: E/AndroidRuntime(1552): FATAL EXCEPTION: AsyncTask #1
08-25 21:18:00.174: E/AndroidRuntime(1552): java.lang.RuntimeException: An error occured while executing doInBackground()
08-25 21:18:00.174: E/AndroidRuntime(1552): at android.os.AsyncTask$3.done(AsyncTask.java:278)
08-25 21:18:00.174: E/AndroidRuntime(1552): at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
08-25 21:18:00.174: E/AndroidRuntime(1552): at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
08-25 21:18:00.174: E/AndroidRuntime(1552): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
08-25 21:18:00.174: E/AndroidRuntime(1552): at java.util.concurrent.FutureTask.run(FutureTask.java:137)
08-25 21:18:00.174: E/AndroidRuntime(1552): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:208)
08-25 21:18:00.174: E/AndroidRuntime(1552): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
08-25 21:18:00.174: E/AndroidRuntime(1552): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
08-25 21:18:00.174: E/AndroidRuntime(1552): at java.lang.Thread.run(Thread.java:856)
08-25 21:18:00.174: E/AndroidRuntime(1552): Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
08-25 21:18:00.174: E/AndroidRuntime(1552): at android.os.Handler.<init>(Handler.java:121)
08-25 21:18:00.174: E/AndroidRuntime(1552): at android.app.Activity.<init>(Activity.java:735)
08-25 21:18:00.174: E/AndroidRuntime(1552): at com.example.js.Second.<init>(Second.java:11)
08-25 21:18:00.174: E/AndroidRuntime(1552): at com.example.js.MainActivity$AsyncTest.doInBackground(MainActivity.java:35)
08-25 21:18:00.174: E/AndroidRuntime(1552): at com.example.js.MainActivity$AsyncTest.doInBackground(MainActivity.java:1)
08-25 21:18:00.174: E/AndroidRuntime(1552): at android.os.AsyncTask$2.call(AsyncTask.java:264)
08-25 21:18:00.174: E/AndroidRuntime(1552): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
08-25 21:18:00.174: E/AndroidRuntime(1552): ... 5 more
How is the best way to non-repeat code in my example?
Make your AsyncTask public and move it to a separate class (file):
AsyncTest.java:
public class AsyncTest extends AsyncTask<Void, Void, Void> {
...
}
Then in your activities call:
new AsyncTest().execute();
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 trying to build a small app that takes a data file in external storage and emails it. I keep getting 'null pointer exceptions' right away in logcat and then my app dies. I can't seem to locate my exception and I am wondering if there is a way to determine the line of code that is causing this. I have the MainActivity class and then a class called SendData- the code is below. I'm new at this so any help would be greatly appreciated- thank you.
private static final String TAG = "MainActivity_ErrorLog";
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
// Create the getData intent
Intent intentgetData = new Intent(MainActivity.this, SendData.class);
public void onStart()
{
{
try
{
File sd = Environment.getExternalStorageDirectory();
File data = Environment.getDataDirectory();
if (sd.canWrite())
{
// verify the paths
String currentDBPath = "TLC_COMMON/database.db";
String backupDBPath = "database.db";
File currentDB = new File(data, currentDBPath);
File backupDB = new File(sd, backupDBPath);
if (currentDB.exists())
{
FileChannel src = new FileInputStream(currentDB).getChannel();
FileChannel dst = new FileOutputStream(backupDB).getChannel();
dst.transferFrom(src, 0, src.size());
src.close();
dst.close();
}
}
}
catch (Exception e)
{
// change the V below to E when complete
Log.v(TAG,"ERROR: Database file not created");
}
startActivity(intentgetData);
}
}
}
--new class
public class SendData extends Activity
{
private static final String TAG = "MainActivity";
/* Checks if external storage is available to read */
public boolean isExternalStorageReadable()
{
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state) ||
Environment.MEDIA_MOUNTED_READ_ONLY.equals(state))
{
return true;
}
return false;
}
/** Called when the user clicks the Send My Data button */
public SendData(View view)
{
// Send data by email
{
File root = Environment.getExternalStorageDirectory();
// verify it is saving as this file name; also path in previous class
String fileName = "database.db";
if (root.canWrite())
{
File attachment = new File(root, fileName);
Intent email = new Intent(Intent.ACTION_SENDTO);
email.putExtra(android.content.Intent.EXTRA_SUBJECT, "Exercise data");
email.putExtra(android.content.Intent.EXTRA_EMAIL, new String[]{"test#gmail.com"});
// is the Uri necessary?
email.putExtra(android.content.Intent.EXTRA_TEXT, Uri.fromFile(attachment));
// look at this VVV
startActivity(Intent.createChooser(email, "Send the data via Email"));}
else
{
// Change the V below to E when complete
Log.v(TAG, "Email send failed");
}
}
}
public void finish()
{
}
}
11-13 13:29:37.343: W/dalvikvm(3319): threadid=1: thread exiting with uncaught exception (group=0x418e3300)
11-13 13:29:37.343: E/AndroidRuntime(3319): FATAL EXCEPTION: main
11-13 13:29:37.343: E/AndroidRuntime(3319): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.va.datasender/com.example.va.datasender.MainActivity}: java.lang.NullPointerException
11-13 13:29:37.343: E/AndroidRuntime(3319): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1983)
11-13 13:29:37.343: E/AndroidRuntime(3319): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
11-13 13:29:37.343: E/AndroidRuntime(3319): at android.app.ActivityThread.access$600(ActivityThread.java:130)
11-13 13:29:37.343: E/AndroidRuntime(3319): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
11-13 13:29:37.343: E/AndroidRuntime(3319): at android.os.Handler.dispatchMessage(Handler.java:99)
11-13 13:29:37.343: E/AndroidRuntime(3319): at android.os.Looper.loop(Looper.java:137)
11-13 13:29:37.343: E/AndroidRuntime(3319): at android.app.ActivityThread.main(ActivityThread.java:4745)
11-13 13:29:37.343: E/AndroidRuntime(3319): at java.lang.reflect.Method.invokeNative(Native Method)
11-13 13:29:37.343: E/AndroidRuntime(3319): at java.lang.reflect.Method.invoke(Method.java:511)
11-13 13:29:37.343: E/AndroidRuntime(3319): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
11-13 13:29:37.343: E/AndroidRuntime(3319): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
11-13 13:29:37.343: E/AndroidRuntime(3319): at dalvik.system.NativeStart.main(Native Method)
11-13 13:29:37.343: E/AndroidRuntime(3319): Caused by: java.lang.NullPointerException
11-13 13:29:37.343: E/AndroidRuntime(3319): at android.content.ContextWrapper.getPackageName(ContextWrapper.java:127)
11-13 13:29:37.343: E/AndroidRuntime(3319): at android.content.ComponentName.<init>(ComponentName.java:75)
11-13 13:29:37.343: E/AndroidRuntime(3319): at android.content.Intent.<init>(Intent.java:3301)
11-13 13:29:37.343: E/AndroidRuntime(3319): at com.example.va.datasender.MainActivity.<init>(MainActivity.java:36)
11-13 13:29:37.343: E/AndroidRuntime(3319): at java.lang.Class.newInstanceImpl(Native Method)
11-13 13:29:37.343: E/AndroidRuntime(3319): at java.lang.Class.newInstance(Class.java:1319)
11-13 13:29:37.343: E/AndroidRuntime(3319): at android.app.Instrumentation.newActivity(Instrumentation.java:1053)
11-13 13:29:37.343: E/AndroidRuntime(3319): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1974)
11-13 13:29:37.343: E/AndroidRuntime(3319): ... 11 more
Find the lowest "Caused by" and continue down until you reach a line from your code:
Caused by: java.lang.NullPointerException
at android.content.ContextWrapper.getPackageName(ContextWrapper.java:127)
at android.content.ComponentName.<init>(ComponentName.java:75)
at android.content.Intent.<init>(Intent.java:3301)
at com.example.va.datasender.MainActivity.<init>(MainActivity.java:36)
The <init> means you are doing something as a class variable or inside a constructor before the Activity has a valid Context... But the specific problem is on line 36.
I would guess that you are trying to create an Intent with this. Initialize your Intent inside onCreate() instead.
Found it. Change this:
// Create the getData intent
Intent intentgetData = new Intent(MainActivity.this, SendData.class);
to:
Intent intentgetData;
and inside onCreate() (or onStart() just before calling startActivity()) add:
intentgetData = new Intent(MainActivity.this, SendData.class);
Your problem comes from line 36 on your MainActivity. Check there for the problem.
11-13 13:29:37.343: E/AndroidRuntime(3319): at com.example.va.datasender.MainActivity.<init>(MainActivity.java:36)
The exeption from line number 36: at com.example.va.datasender.MainActivity.<init>(MainActivity.java:36).
Since the error log also shows android.content.Intent.<init> after the MainActivity.java:36, I would check the value for the first parameter in the following line, when instantiating intentgetData:
Intent intentgetData = new Intent(MainActivity.this, SendData.class);
Instead of having the instatiation done there, try doing it in the onStart() method just before calling startActivity(intentgetData);:
Intent intentgetData = new Intent(MainActivity.this, SendData.class);
startActivity(intentgetData);
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.