I am getting error FileNotFoundException open failed: EROFS (Read-only file system) while unzipping file in android. I have lost my time but not got solution. please help me for resolve my problem.
public class UnZipActivity extends Activity {
private String zipFile = Environment.getExternalStorageDirectory() + "/database/db.zip";
private String unzipLocation = Environment.getExternalStorageDirectory() + "/database/";
Button btnSelectPhoto;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_getimage);
Log.d("Unzip", "Zipfile: " + zipFile);
Log.d("Unzip", "location: " + unzipLocation);
btnSelectPhoto = (Button)findViewById(R.id.btnSelectPhoto);
btnSelectPhoto.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
unzip();
}
});
}
public void unzip() {
FileInputStream fin = null;
try {
fin = new FileInputStream(new File(zipFile));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ZipInputStream zin = new ZipInputStream(fin);
BufferedInputStream in = new BufferedInputStream(zin);
ZipEntry ze = null;
try {
while ((ze = zin.getNextEntry()) != null) {
Log.v("Unzip", "Unzipping " + ze.getName());
if (ze.isDirectory()) {
_dirChecker(ze.getName());
} else {
zin.closeEntry();
FileOutputStream fout = new FileOutputStream(new File(unzipLocation + ze.getName()));
BufferedOutputStream out = new BufferedOutputStream(fout);
/*for (int c = zin.read(); c != -1; c = zin.read()) {
fout.write(c);
}*/
byte b[] = new byte[1024];
int n;
while ((n = in.read(b,0,1024)) >= 0) {
out.write(b,0,n);
}
zin.closeEntry();
fout.close();
}
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
zin.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void _dirChecker(String dir) {
File f = new File(unzipLocation + dir);
if (!f.isDirectory()) {
f.mkdirs();
}
}
}
Error
08-21 02:40:46.934: W/System.err(8495): java.io.FileNotFoundException: /storage/sdcard/database/objectdetail_create.sql: open failed: EROFS (Read-only file system)
08-21 02:40:46.934: W/System.err(8495): at libcore.io.IoBridge.open(IoBridge.java:409)
08-21 02:40:46.944: W/System.err(8495): at java.io.FileOutputStream.<init>(FileOutputStream.java:88)
08-21 02:40:46.944: W/System.err(8495): at java.io.FileOutputStream.<init>(FileOutputStream.java:73)
08-21 02:40:46.954: W/System.err(8495): at com.example.buttonstyleapp.UnZipActivity.unzip(UnZipActivity.java:71)
08-21 02:40:46.954: W/System.err(8495): at com.example.buttonstyleapp.UnZipActivity$1.onClick(UnZipActivity.java:43)
08-21 02:40:46.954: W/System.err(8495): at android.view.View.performClick(View.java:4240)
08-21 02:40:46.954: W/System.err(8495): at android.view.View$PerformClick.run(View.java:17721)
08-21 02:40:46.954: W/System.err(8495): at android.os.Handler.handleCallback(Handler.java:730)
08-21 02:40:46.964: W/System.err(8495): at android.os.Handler.dispatchMessage(Handler.java:92)
08-21 02:40:46.964: W/System.err(8495): at android.os.Looper.loop(Looper.java:137)
08-21 02:40:46.974: W/System.err(8495): at android.app.ActivityThread.main(ActivityThread.java:5103)
08-21 02:40:46.974: W/System.err(8495): at java.lang.reflect.Method.invokeNative(Native Method)
08-21 02:40:46.974: W/System.err(8495): at java.lang.reflect.Method.invoke(Method.java:525)
08-21 02:40:46.974: W/System.err(8495): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
08-21 02:40:46.984: W/System.err(8495): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
08-21 02:40:46.984: W/System.err(8495): at dalvik.system.NativeStart.main(Native Method)
08-21 02:40:46.984: W/System.err(8495): Caused by: libcore.io.ErrnoException: open failed: EROFS (Read-only file system)
08-21 02:40:46.994: W/System.err(8495): at libcore.io.Posix.open(Native Method)
08-21 02:40:47.004: W/System.err(8495): at libcore.io.BlockGuardOs.open(BlockGuardOs.java:110)
08-21 02:40:47.014: W/System.err(8495): at libcore.io.IoBridge.open(IoBridge.java:393)
08-21 02:40:47.014: W/System.err(8495): ... 15 more
I have added permission in AndroidManifest.xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_INTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
Related
I am trying to create a class that sets and starts audio recording but as soon as I click the button the app crashes. Iv isolated the problem to where I set the parameters for the MediRecorder.
private void startRec() throws IOException {
if (mrecorder!=null)
mrecorder.release();
mrecorder= new MediaRecorder();
-> mrecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
/*
mrecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mrecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
mrecorder.setOutputFile(MFILE);
mrecorder.prepare();
mrecorder.start();
*/
}
It crashes when the line with the arrow above the start of the notes is executed. I added the following permission to the manifest as well:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
Any help much appreciated.
UPDATED LOGCAT
[ 05-12 00:39:13.299 30086:30158 D/ ]
ro.exynos.dss isEnabled: 0
05-12 00:39:13.309 30086-30158/record66.record6 D/mali_winsys: new_window_surface returns 0x3000, [1440x2560]-format:1
05-12 00:39:13.319 30086-30086/record66.record6 W/DisplayListCanvas: DisplayListCanvas is started on unbinded RenderNode (without mOwningView)
05-12 00:39:13.319 30086-30158/record66.record6 D/libGLESv1: DTS_GLAPI : DTS is not allowed for Package : record66.record6
05-12 00:39:13.359 30086-30086/record66.record6 D/ViewRootImpl: MSG_RESIZED_REPORT: ci=Rect(0, 96 - 0, 0) vi=Rect(0, 96 - 0, 0) or=1
05-12 00:39:13.389 30086-30086/record66.record6 I/Timeline: Timeline: Activity_idle id: android.os.BinderProxy#682466c time:234401322
05-12 00:39:15.749 30086-30086/record66.record6 D/ViewRootImpl: ViewPostImeInputStage processPointer 0
05-12 00:39:15.879 30086-30086/record66.record6 D/ViewRootImpl: ViewPostImeInputStage processPointer 1
05-12 00:39:15.929 30086-30086/record66.record6 D/AndroidRuntime: Shutting down VM
05-12 00:39:15.939 30086-30086/record66.record6 E/AndroidRuntime: FATAL EXCEPTION: main
Process: record66.record6, PID: 30086
java.lang.RuntimeException: setAudioSource failed.
at android.media.MediaRecorder._setAudioSource(Native Method)
at android.media.MediaRecorder.setAudioSource(MediaRecorder.java:488)
at record66.record6.MainActivity.startRec(MainActivity.java:58)
at record66.record6.MainActivity.onClick(MainActivity.java:94)
at android.view.View.performClick(View.java:5697)
at android.widget.TextView.performClick(TextView.java:10815)
at android.view.View$PerformClick.run(View.java:22526)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:158)
at android.app.ActivityThread.main(ActivityThread.java:7229)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
05-12 00:39:17.909 30086-30086/record66.record6 I/Process: Sending signal. PID: 30086 SIG: 9
Please see what logcat is.
And let us know what error you are getting. So can help.
package com.example.dhrupalpatel.test;
import android.app.Activity;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Environment;
import java.io.File;
import java.io.IOException;
public class MainActivity extends Activity implements View.OnClickListener{
MediaRecorder mrecorder;
boolean mStartRecording=false;
Button start, stop;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
start =(Button)findViewById(R.id.start);
stop =(Button)findViewById(R.id.stop);
start.setOnClickListener(this);
stop.setOnClickListener(this);
}
private void startRec() throws IOException {
boolean mExternalStorageAvailable = false;
boolean mExternalStorageWriteable = false;
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
// We can read and write the media
mExternalStorageAvailable = mExternalStorageWriteable = true;
} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
// We can only read the media
mExternalStorageAvailable = true;
mExternalStorageWriteable = false;
} else {
// Something else is wrong. It may be one of many other states, but all we need
// to know is we can neither read nor write
mExternalStorageAvailable = mExternalStorageWriteable = false;
}
File sdCardDirectory= Environment
.getExternalStorageDirectory();
if(mExternalStorageAvailable && !sdCardDirectory.exists())
{
sdCardDirectory.mkdir();
}
File f= new File(sdCardDirectory.getPath()+"/"+System.currentTimeMillis()+".mp3");
if( mrecorder == null ) {
mrecorder = new MediaRecorder();
mrecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mrecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mrecorder.setOutputFile(f.getPath());
mrecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
}
if(!mStartRecording) {
try {
mrecorder.prepare();
mrecorder.start();
mStartRecording = true;
} catch (IOException e) {
e.printStackTrace();
}
}
}
private void stopRec() throws IOException {
if(mStartRecording) {
mStartRecording = false;
mrecorder.stop();
mrecorder.reset();
mrecorder.release();
mrecorder = null;
}
}
#Override
public void onClick(View v) {
switch (v.getId())
{
case R.id.start:
try {
startRec();
} catch (IOException e) {
e.printStackTrace();
}
break;
case R.id.stop:
try {
stopRec();
} catch (IOException e) {
e.printStackTrace();
}
break;
}
}
}
i was implmenting a pdf reader in my project when i got the following error..
E/AndroidRuntime(1495): FATAL EXCEPTION: main
E/AndroidRuntime(1495): Process: com.example.testqstn, PID: 1495
E/AndroidRuntime(1495): java.lang.NoClassDefFoundError: com.questionpoint.pdf.Pdf
E/AndroidRuntime(1495): at com.question_point.main.Question_Point_Main.openPdfIntent(Question_Point_Main.java:272)
E/AndroidRuntime(1495): at com.question_point.main.Question_Point_Main.CopyReadAssets(Question_Point_Main.java:266)
E/AndroidRuntime(1495): at com.question_point.main.Question_Point_Main.pdfSelection(Question_Point_Main.java:128)
E/AndroidRuntime(1495): at com.question_point.main.Question_Point_Main$2.onClick(Question_Point_Main.java:104)
E/AndroidRuntime(1495): at android.view.View.performClick(View.java:4438)
E/AndroidRuntime(1495): at android.view.View$PerformClick.run(View.java:18422)
E/AndroidRuntime(1495): at android.os.Handler.handleCallback(Handler.java:733)
E/AndroidRuntime(1495): at android.os.Handler.dispatchMessage(Handler.java:95)
E/AndroidRuntime(1495): at android.os.Looper.loop(Looper.java:136)
E/AndroidRuntime(1495): at android.app.ActivityThread.main(ActivityThread.java:5017)
E/AndroidRuntime(1495): at java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime(1495): at java.lang.reflect.Method.invoke(Method.java:515)
E/AndroidRuntime(1495): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
E/AndroidRuntime(1495): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
E/AndroidRuntime(1495): at dalvik.system.NativeStart.main(Native Method)
I/Process(1495): Sending signal. PID: 1495 SIG: 9
i had imported a project to my code.. my library file is named libs, and i have repeatedly cleaned my project.. but still the error persists.. Thanks in advance..
The code that leads to error
public void CopyReadAssets(String url) {
AssetManager assetManager = getAssets();
InputStream in = null;
OutputStream out = null;
File file = new File(getFilesDir(), url);
try {
in = assetManager.open(url);
out = openFileOutput(file.getName(),
Context.MODE_WORLD_READABLE);
copyFile(in, out);
in.close();
in = null;
out.flush();
out.close();
out = null;
}
catch (Exception e) {
Log.e("tag", e.getMessage());
}
String path = "file://" + getFilesDir() + "/"+url;
openPdfIntent(path);
}
private void openPdfIntent(String path) {
// TODO Auto-generated method stub
try {
final Intent intent = new Intent(Question_Point_Main.this, Pdf.class);
intent.putExtra(PdfViewerActivity.EXTRA_PDFFILENAME, path);
startActivity(intent);
} catch (Exception e) {
e.printStackTrace();
}
}
Try these steps:
Step 1: Create a folder "lib", and copy all third-party jars here;
Step 2: Add these jars to build path;
Step 3: Use the folder as Source Folder(shown below).
Maybe you just forgot the underscore and you meant com.question_point.pdf.Pdf?
It would be easier to tell if you could post the relevant code where you make the call that leads to the Exception.
I try #Tarsem answer already but have fatal error occur can I know why?
#Tarsem answer:
https://stackoverflow.com/a/18308611/2398886
<--- these are my error codes in eclipse: --->
08-21 18:52:23.399: W/dalvikvm(29376): threadid=1: thread exiting with uncaught exception (group=0x40018578)
08-21 18:52:23.409: E/AndroidRuntime(29376): FATAL EXCEPTION: main
08-21 18:52:23.409: E/AndroidRuntime(29376): java.lang.NoClassDefFoundError: com.example.testing01.MainActivity2$6
08-21 18:52:23.409: E/AndroidRuntime(29376): at com.example.testing01.MainActivity2.CaptureMapScreen(MainActivity2.java:410)
08-21 18:52:23.409: E/AndroidRuntime(29376): at com.example.testing01.MainActivity2$3.onClick(MainActivity2.java:182)
08-21 18:52:23.409: E/AndroidRuntime(29376): at android.view.View.performClick(View.java:2485)
08-21 18:52:23.409: E/AndroidRuntime(29376): at android.view.View$PerformClick.run(View.java:9080)
08-21 18:52:23.409: E/AndroidRuntime(29376): at android.os.Handler.handleCallback(Handler.java:587)
08-21 18:52:23.409: E/AndroidRuntime(29376): at android.os.Handler.dispatchMessage(Handler.java:92)
08-21 18:52:23.409: E/AndroidRuntime(29376): at android.os.Looper.loop(Looper.java:130)
08-21 18:52:23.409: E/AndroidRuntime(29376): at android.app.ActivityThread.main(ActivityThread.java:3687)
08-21 18:52:23.409: E/AndroidRuntime(29376): at java.lang.reflect.Method.invokeNative(Native Method)
08-21 18:52:23.409: E/AndroidRuntime(29376): at java.lang.reflect.Method.invoke(Method.java:507)
08-21 18:52:23.409: E/AndroidRuntime(29376): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run (ZygoteInit.java:867)
08-21 18:52:23.409: E/AndroidRuntime(29376): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:625)
08-21 18:52:23.409: E/AndroidRuntime(29376): at dalvik.system.NativeStart.main(Native Method)
<--- these are my error codes in eclipse: --->
and these are my coding, is it my coding any bug?
public void CaptureMapScreen()
{
SnapshotReadyCallback callback = new SnapshotReadyCallback() {
Bitmap bitmap;
#Override
public void onSnapshotReady(Bitmap snapshot) {
// TODO Auto-generated method stub
bitmap = snapshot;
try {
FileOutputStream out = new FileOutputStream("/mnt/sdcard/"
+ "MyMapScreen" + System.currentTimeMillis()
+ ".png");
// above "/mnt ..... png" => is a storage path (where image will be stored) + name of image you can customize as per your Requirement
bitmap.compress(Bitmap.CompressFormat.PNG, 90, out);
} catch (Exception e) {
e.printStackTrace();
}
}
};
map.snapshot(callback);
// myMap is object of GoogleMap +> GoogleMap myMap;
// which is initialized in onCreate() =>
// myMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map_pass_home_call)).getMap();
}
my Stop Button function:
//End Button Function
Button timerStopButton = (Button) findViewById(R.id.btnTimerStop);
timerStopButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view){
String latitude3=Double.toString(latitude1);
String latitude4=Double.toString(latitude2);
String longitude3=Double.toString(longitude1);
String longitude4=Double.toString(longitude2);
String Kcalories=String.format("%.2f", calories);
Intent intent = new Intent(view.getContext(),NewDataActivity.class);
intent.putExtra("lat1", latitude3);
intent.putExtra("lat2", latitude4);
intent.putExtra("long1", longitude3);
intent.putExtra("long2", longitude4);
intent.putExtra("timer", timerStop1);
intent.putExtra("distance", distance2 + " m");
intent.putExtra("Ccalories", Kcalories + " kcal");
Toast.makeText(getApplicationContext(), "Calories (kcal):" + Kcalories, Toast.LENGTH_LONG).show();
startActivity(intent);
try {
CaptureMapScreen();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
//kill task timer and other
int pid = android.os.Process.myPid();
android.os.Process.killProcess(pid);
}
});
Is it my coding have any bug or my logic any probelm?
can anyone help me? thanks :)
Note Your code to Capture Map Screen is Correct and if still you have confusion than
Please Make sure Each Step Below:-
Below are the steps to capture screen shot of Google Map V2 with example
Step 1. open Android Sdk Manager (Window > Android Sdk Manager) then Expand Extras now update/install Google Play Services to Revision 10 ignore this step if already installed
Read Notes here https://developers.google.com/maps/documentation/android/releases#august_2013
Step 2. Restart Eclipse
Step 3. import com.google.android.gms.maps.GoogleMap.SnapshotReadyCallback;
Step 4. Make Method to Capture/Store Screen/image of Map like below
public void CaptureMapScreen()
{
SnapshotReadyCallback callback = new SnapshotReadyCallback() {
Bitmap bitmap;
#Override
public void onSnapshotReady(Bitmap snapshot) {
// TODO Auto-generated method stub
bitmap = snapshot;
try {
FileOutputStream out = new FileOutputStream("/mnt/sdcard/"
+ "MyMapScreen" + System.currentTimeMillis()
+ ".png");
// above "/mnt ..... png" => is a storage path (where image will be stored) + name of image you can customize as per your Requirement
bitmap.compress(Bitmap.CompressFormat.PNG, 90, out);
} catch (Exception e) {
e.printStackTrace();
}
}
};
myMap.snapshot(callback);
// myMap is object of GoogleMap +> GoogleMap myMap;
// which is initialized in onCreate() =>
// myMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map_pass_home_call)).getMap();
}
Step 5. Now call this CaptureMapScreen() method where you want to capture the image
in my case i am calling this method on Button click in my onCreate() which is working fine
like:
Button btnCap = (Button) findViewById(R.id.btnTakeScreenshot);
btnCap.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
try {
CaptureMapScreen();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
});
Check Doc here and here
else if (v.getId() == R.id.update) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
try {
URL url = new URL("http://darkliteempire.gaming.multiplay.co.uk/testdownload.txt");
//create the new connection
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
//set up some things on the connection
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
//and connect!
urlConnection.connect();
//set the path where we want to save the file
//in this case, going to save it on the root directory of the
//sd card.
File SDCardRoot = new File("/sdcard/"+"download/");
//create a new file, specifying the path, and the filename
//which we want to save the file as.
File file = new File(SDCardRoot,"test.txt");
//this will be used to write the downloaded data into the file we created
FileOutputStream fileOutput = new FileOutputStream(file);
//this will be used in reading the data from the internet
InputStream inputStream = urlConnection.getInputStream();
//this is the total size of the file
int totalSize = urlConnection.getContentLength();
//variable to store total downloaded bytes
int downloadedSize = 0;
//create a buffer...
byte[] buffer = new byte[1024];
int bufferLength = 0; //used to store a temporary size of the buffer
//now, read through the input buffer and write the contents to the file
while ( (bufferLength = inputStream.read(buffer)) > 0 )
{
//add the data in the buffer to the file in the file output stream (the file on the sd card
fileOutput.write(buffer, 0, bufferLength);
//add up the size so we know how much is downloaded
downloadedSize += bufferLength;
int progress=(int)(downloadedSize*100/totalSize);
//this is where you would do something to report the prgress, like this maybe
//updateProgress(downloadedSize, totalSize);
}
//close the output stream when done
fileOutput.close();
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (ProtocolException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
this code keeps coming out with the FileNotFoundException, but the file is there, if you follow the url you can see it.
does it have to be hosted in a specific way? or is it something wrong with the way im getting it
EDIT: this is the logcat message
12-14 22:29:19.890: W/System.err(24557): java.io.FileNotFoundException: http://darkliteempire.gaming.multiplay.co.uk/testdownload.txt
12-14 22:29:19.890: W/System.err(24557): at libcore.net.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:177)
12-14 22:29:19.890: W/System.err(24557): at com.MasterZangetsu.kentrocksoc.MainActivity.onClick(MainActivity.java:99)
12-14 22:29:19.890: W/System.err(24557): at android.view.View.performClick(View.java:3591)
12-14 22:29:19.890: W/System.err(24557): at android.view.View$PerformClick.run(View.java:14263)
12-14 22:29:19.895: W/System.err(24557): at android.os.Handler.handleCallback(Handler.java:605)
12-14 22:29:19.895: W/System.err(24557): at android.os.Handler.dispatchMessage(Handler.java:92)
12-14 22:29:19.895: W/System.err(24557): at android.os.Looper.loop(Looper.java:137)
12-14 22:29:19.895: W/System.err(24557): at android.app.ActivityThread.main(ActivityThread.java:4507)
12-14 22:29:19.895: W/System.err(24557): at java.lang.reflect.Method.invokeNative(Native Method)
12-14 22:29:19.895: W/System.err(24557): at java.lang.reflect.Method.invoke(Method.java:511)
12-14 22:29:19.895: W/System.err(24557): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:790)
12-14 22:29:19.895: W/System.err(24557): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:557)
12-14 22:29:19.895: W/System.err(24557): at dalvik.system.NativeStart.main(Native Method)
12-14 22:29:20.170: W/WifiStateTracker(2010): getNetworkInfo : NetworkInfo: type: WIFI[], state: DISCONNECTED/DISCONNECTED, reason: (unspecified), extra: (none), roaming: false, failover: false, isAvailable: false
comment the below piece of line in your code.
urlConnection.setDoOutput(true);
I'm loading a file that has been saved by another class via the FileOutputstream method. Anyway, I want to load that file in another class, but it either gives me syntax errors or crashes my App.
The only tutorials I could find where they saved and loaded the file in the same class, but I want to load it up in another class and couldn't find how to solve the problem of loading into another class.
Thanks
My Code:
public class LogIn extends Activity implements OnClickListener {
EditText eTuser;
EditText eTpassword;
CheckBox StaySignedIn;
Button bSubmit;
String user;
String pass;
FileOutputStream fos;
FileInputStream fis = null;
String FILENAME = "userandpass";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
eTuser = (EditText) findViewById(R.id.eTuser);
eTpassword = (EditText) findViewById(R.id.eTpassword);
StaySignedIn = (CheckBox) findViewById(R.id.Cbstay);
bSubmit = (Button) findViewById(R.id.bLogIn);
bSubmit.setOnClickListener(this);
File file = getBaseContext().getFileStreamPath(FILENAME);
if (file.exists()) {
Intent i = new Intent(LogIn.this, ChatService.class);
startActivity(i);
}
// if if file exist close bracket
try {
fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} // end of catch bracket
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} // end of catch
} // create ends here
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.bLogIn:
String user = eTuser.getText().toString();
String pass = eTpassword.getText().toString();
Bundle userandpass = new Bundle();
userandpass.putString("user", user);
userandpass.putString("pass", pass);
Intent login = new Intent(LogIn.this, logincheck.class);
login.putExtra("pass", user);
login.putExtra("user", pass);
startActivity(login);
if (StaySignedIn.isChecked())
;
String userstaysignedin = eTuser.getText().toString();
String passstaysignedin = eTpassword.getText().toString();
try {
fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.write(userstaysignedin.getBytes());
fos.write(passstaysignedin.getBytes());
fos.close();
} catch (IOException e) {
// end of try bracket, before the Catch IOExceptions e.
e.printStackTrace();
} // end of catch bracket
} // switch and case ends here
}// Click ends here
}// main class ends here
Class B( Class that loads the data.)
public class ChatService extends Activity {
String collected = null;
FileInputStream fis = null;
String FILENAME;
TextView userandpass;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.chatservice);
userandpass = (TextView) findViewById(R.id.textView1);
try {
fis = openFileInput(FILENAME);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
byte[] dataArray = null;
try {
dataArray = new byte[fis.available()];
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
while (fis.read(dataArray) != -1)
;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
{
// while statement
}
userandpass.setText(collected);
}// create ends here
}// class ends here
LogCat:
03-03 21:03:34.725: E/AndroidRuntime(279): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.gta5news.bananaphone/com.gta5news.bananaphone.ChatService}: java.lang.NullPointerException
03-03 21:03:34.725: E/AndroidRuntime(279): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
03-03 21:03:34.725: E/AndroidRuntime(279): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
03-03 21:03:34.725: E/AndroidRuntime(279): at android.app.ActivityThread.access$2300(ActivityThread.java:125)
03-03 21:03:34.725: E/AndroidRuntime(279): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
03-03 21:03:34.725: E/AndroidRuntime(279): at android.os.Handler.dispatchMessage(Handler.java:99)
03-03 21:03:34.725: E/AndroidRuntime(279): at android.os.Looper.loop(Looper.java:123)
03-03 21:03:34.725: E/AndroidRuntime(279): at android.app.ActivityThread.main(ActivityThread.java:4627)
03-03 21:03:34.725: E/AndroidRuntime(279): at java.lang.reflect.Method.invokeNative(Native Method)
03-03 21:03:34.725: E/AndroidRuntime(279): at java.lang.reflect.Method.invoke(Method.java:521)
03-03 21:03:34.725: E/AndroidRuntime(279): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
03-03 21:03:34.725: E/AndroidRuntime(279): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
03-03 21:03:34.725: E/AndroidRuntime(279): at dalvik.system.NativeStart.main(Native Method)
03-03 21:03:34.725: E/AndroidRuntime(279): Caused by: java.lang.NullPointerException
03-03 21:03:34.725: E/AndroidRuntime(279): at android.app.ContextImpl.makeFilename(ContextImpl.java:1599)
03-03 21:03:34.725: E/AndroidRuntime(279): at android.app.ContextImpl.openFileInput(ContextImpl.java:399)
03-03 21:03:34.725: E/AndroidRuntime(279): at android.content.ContextWrapper.openFileInput(ContextWrapper.java:152)
03-03 21:03:34.725: E/AndroidRuntime(279): at com.gta5news.bananaphone.ChatService.onCreate(ChatService.java:25)
03-03 21:03:34.725: E/AndroidRuntime(279): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
03-03 21:03:34.725: E/AndroidRuntime(279): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
03-03 21:03:34.725: E/AndroidRuntime(279): ... 11 more
The FILENAME string in the ChatService class is null. So you get a NullPointerException when you try to load a file using fis = openFileInput(FILENAME).
Also, your read loop throws away the data:
while (fis.read(dataArray) != -1)
;
It needs to collect the data and set the value of your collected String.
The stack trace tells you everything you need to know.
The error is a NullPointerException (meaning that you pass a null reference to a method expecting a non null reference, or that you call a method on a null reference).
The error occurs inside some android code (ContextWrapper.openFileInput()), which is called by your ChatService.onCreate() method, on line 25.
The line 25 is the following line:
fis = openFileInput(FILENAME);
So the error is clear: FILENAME is null. You haven't initialized it before this method is called.
I'm not sure about your program flow and if your two classes are running in the same thread, but it looks like you have a program flow issue. You are trying to open the file and getting a NullPointerException. Make sure the file is created and you have the correct reference to it before attempting to read.
If they are running in separate threads then you might try something like this:
try {
int waitTries=1;
fis = openFileInput(FILENAME);
while(fis.available()<EXPECTEDSIZE && waitTries++<10)
Tread.sleep(50);
}
If you know how large the file should be (EXPECTEDSIZE is some constant you will set), then this may be what you are looking for.