backup of database to sd card - java

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.

Related

java.lang.NumberFormatException: Invalid int: "" model texture

I would like to add texture to my model but I keep getting this error . Any help would be appreciated. Thanks
for (String i : faces) {
for (String j : i.split(" ")) {
iCoords[faceIndex] = (short) faceIndex++;
String[] faceComponent = j.split("/");
String vertex = vertexes.get(Integer.parseInt(faceComponent[0]) - 1);
// this line throws NFE
String texture = textures.get(Integer.parseInt(faceComponent[1]) - 1);
String vertexComp[] = vertex.split(" ");
String textureComp[] = texture.split(" ");
for (String v : vertexComp) {
vCoords[vertexIndex++] = Float.parseFloat(v);
}
for (String t : textureComp) {
tCoords[textureIndex++] = Float.parseFloat(t);
}
}
}
java.lang.RuntimeException: Unable to start activity
ComponentInfo{com.app.glapp/com.app.glapp.MainActivity}:
java.lang.NumberFormatException: Invalid int: ""
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2413)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2471)
at android.app.ActivityThread.access$900(ActivityThread.java:175)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1308)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:146)
at android.app.ActivityThread.main(ActivityThread.java:5603)
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:1283)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NumberFormatException: Invalid int: ""
at java.lang.Integer.invalidInt(Integer.java:137)
at java.lang.Integer.parseInt(Integer.java:358)
at java.lang.Integer.parseInt(Integer.java:331)
at com.mingatronenterprices.glapp.mesh.(mesh.java:72)
at com.mingatronenterprices.glapp.ClearRenderer.(MainActivity.java:70)
at com.app.glapp.ClearGLSurfaceView.(MainActivity.java:54)
at com.app.glapp.MainActivity.onCreate(MainActivity.java:32)
at android.app.Activity.performCreate(Activity.java:5458)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1093)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2377)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2471)
at android.app.ActivityThread.access$900(ActivityThread.java:175)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1308)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:146)
at android.app.ActivityThread.main(ActivityThread.java:5603)
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:1283)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
at dalvik.system.NativeStart.main(Native Method)
Try to modify like this:
for (String v : vertexComp) {
try {
vCoords[vertexIndex++] = Float.parseFloat(v);
}
catch (NumberFormatException e) {
}
}
for (String t : textureComp) {
try {
tCoords[textureIndex++] = Float.parseFloat(t);
}
catch (NumberFormatException e) {
}
}

Sending email using Android services

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.

Unable to start the recorder in Oncreate

I made a simple video recorder app in which the video starts recording on Button click. This is my code:
package com.example.videocapture2;
import java.io.IOException;
import android.app.Activity;
import android.content.pm.ActivityInfo;
import android.media.CamcorderProfile;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends Activity implements SurfaceHolder.Callback,android.media.MediaRecorder.OnInfoListener{
MediaRecorder recorder;
SurfaceHolder holder;
Button Rec = null;
boolean recording = false;
int count =1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
recorder = new MediaRecorder();
initRecorder();
setContentView(R.layout.activity_main);
SurfaceView cameraView = (SurfaceView) findViewById(R.id.videoview);
holder = cameraView.getHolder();
holder.addCallback(this);
holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
recorder.start(); //This is the line pointed to by the IllegalStateException
//cameraView.setClickable(true);
// cameraView.setOnClickListener(this);
Rec = (Button)findViewById(R.id.mybutton);
Rec.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (recording) {
recorder.stop();
recording = false;
// Let's initRecorder so we can record again
initRecorder();
prepareRecorder();
} else {
recording = true;
recorder.start();
}
}
});
}
private void initRecorder() {
recorder.setAudioSource(MediaRecorder.AudioSource.DEFAULT);
recorder.setVideoSource(MediaRecorder.VideoSource.DEFAULT);
CamcorderProfile cpHigh = CamcorderProfile
.get(CamcorderProfile.QUALITY_HIGH);
recorder.setProfile(cpHigh);
recorder.setOutputFile("/sdcard/videocapture_example"+count+".mp4");
recorder.setMaxDuration(50000); // 50 seconds
recorder.setMaxFileSize(2*1048576); // Approximately 5 megabytes
count++;
}
private void prepareRecorder() {
recorder.setPreviewDisplay(holder.getSurface());
try {
recorder.prepare();
} catch (IllegalStateException e) {
e.printStackTrace();
finish();
} catch (IOException e) {
e.printStackTrace();
finish();
}
}
public void surfaceCreated(SurfaceHolder holder) {
prepareRecorder();
}
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
}
public void surfaceDestroyed(SurfaceHolder holder) {
if (recording) {
recorder.stop();
recording = false;
}
recorder.release();
//Toast.makeText(getApplicationContext(), "Video is saved", Toast.LENGTH_LONG).show();
//finish();
}
#Override
public void onInfo(MediaRecorder mr, int what, int extra) {
// TODO Auto-generated method stub
System.out.println("Reached onInfoListener");
if(what==android.media.MediaRecorder.MEDIA_RECORDER_INFO_MAX_FILESIZE_REACHED)
{
Toast.makeText(getApplicationContext(), "Video clip recorded", Toast.LENGTH_LONG).show();
}
}
}
What changes should I make to call the
recorder.start();
from onCreate, or rather immediately after I launch my app, instead of in the OnClick method? Moreover, if I try to call it directly from the OnCreate, it throws the IllegalStateException in the line of the recorder.start() statement.
Logcat:
04-03 12:48:51.005: E/Trace(26160): error opening trace file: No such file or directory (2)
04-03 12:48:51.025: V/ActivityThread(26160): Class path: /data/app/com.example.videocapture2-2.apk, JNI path: /data/data/com.example.videocapture2/lib
04-03 12:48:51.174: I/System.out(26160): In surface view:false
04-03 12:48:51.174: E/MediaRecorder(26160): start called in an invalid state: 4
04-03 12:48:51.175: D/AndroidRuntime(26160): Shutting down VM
04-03 12:48:51.175: W/dalvikvm(26160): threadid=1: thread exiting with uncaught exception (group=0x41bd88a8)
04-03 12:48:51.178: E/AndroidRuntime(26160): FATAL EXCEPTION: main
04-03 12:48:51.178: E/AndroidRuntime(26160): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.videocapture2/com.example.videocapture2.MainActivity}: java.lang.IllegalStateException
04-03 12:48:51.178: E/AndroidRuntime(26160): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2198)
04-03 12:48:51.178: E/AndroidRuntime(26160): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2225)
04-03 12:48:51.178: E/AndroidRuntime(26160): at android.app.ActivityThread.access$600(ActivityThread.java:151)
04-03 12:48:51.178: E/AndroidRuntime(26160): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1301)
04-03 12:48:51.178: E/AndroidRuntime(26160): at android.os.Handler.dispatchMessage(Handler.java:99)
04-03 12:48:51.178: E/AndroidRuntime(26160): at android.os.Looper.loop(Looper.java:153)
04-03 12:48:51.178: E/AndroidRuntime(26160): at android.app.ActivityThread.main(ActivityThread.java:5096)
04-03 12:48:51.178: E/AndroidRuntime(26160): at java.lang.reflect.Method.invokeNative(Native Method)
04-03 12:48:51.178: E/AndroidRuntime(26160): at java.lang.reflect.Method.invoke(Method.java:511)
04-03 12:48:51.178: E/AndroidRuntime(26160): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:790)
04-03 12:48:51.178: E/AndroidRuntime(26160): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:557)
04-03 12:48:51.178: E/AndroidRuntime(26160): at dalvik.system.NativeStart.main(Native Method)
04-03 12:48:51.178: E/AndroidRuntime(26160): Caused by: java.lang.IllegalStateException
04-03 12:48:51.178: E/AndroidRuntime(26160): at android.media.MediaRecorder.native_start(Native Method)
04-03 12:48:51.178: E/AndroidRuntime(26160): at android.media.MediaRecorder.start(MediaRecorder.java:728)
04-03 12:48:51.178: E/AndroidRuntime(26160): at com.example.videocapture2.MainActivity.onCreate(MainActivity.java:51)
04-03 12:48:51.178: E/AndroidRuntime(26160): at android.app.Activity.performCreate(Activity.java:5244)
04-03 12:48:51.178: E/AndroidRuntime(26160): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1082)
04-03 12:48:51.178: E/AndroidRuntime(26160): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2162)
04-03 12:48:51.178: E/AndroidRuntime(26160): ... 11 more
Attempts at solving this:
1) It does not work if I keep it in onCreate
2) It does not work if I keep it in a new thread called from onCreate.
3) It also does not work if I keep it in the onClick, and simulate a click through code, using myButton.performClick()
All above scenarios gives same exception error.
But funnily enough, if the recorder.start() mentioned there is kept within buttonClick event, it works fine.
I am not able to understand why. I need the video to be recorded and saved as soon as the activity is launched.
Because It takes some time to load recorder object into memory. so it will show illegal state exception.
If you want to use this in onCreate use Handler for make some delay.
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
recorder.start();
}
}, 1000);
Update:
put recorder.start(); in prepareRecorder() method
private void prepareRecorder() {
recorder.setPreviewDisplay(holder.getSurface());
try {
recorder.prepare();
recorder.start();
} catch (IllegalStateException e) {
e.printStackTrace();
finish();
} catch (IOException e) {
e.printStackTrace();
finish();
}
}

how to find null pointer exception with logcat

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);

App Crashes on Launch, Trying to see if file exist's for login screen

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.

Categories

Resources