Writing Data to Internal File - ContextWrapper NullPointerException - java

I'm creating a file for internal storage, and I'm running into a problem when the data is written. I know that it retrieves the right data when it's called (I used a Logcat tag to check that it was), but as soon as it tries to open the FileOutputStream, it says that there is a NullPointerException on the second line:
static ContextWrapper wrap = new ContextWrapper(context);
FileOutputStream gamesave = wrap.openFileOutput (FILENAME, Context.MODE_PRIVATE);
gamesave.write(DATA.getBytes());
gamesave.close();
I've looked at other questions and I can't figure out why the NullPointerException is there, it seems to be following the right procedure.

I think you have the wrong Context in your context var (i.e. ApplicationContext). Try using the context directly - without the Wrapper.

Why are you creating a ContextWrapper? There is no reason to do that. Just use the Context you have at hand -- the Activity if you are an Activity, or one passed in to your code if not.
Note that it is perfectly fine to use the Application as a Context for this.

Related

Java NoSuchFileException When File Exists

I am attempting to parse a json file as part of an android development project. Here is the error message that keeps popping up:
W/System.err: java.nio.file.NoSuchFileException: C:/Users/andno/Desktop/AndroidDev2ClimateApp/app/src/main/java/com/example/androiddev2climateapp/ui/home/test.json
However, in android studios, the path in the error is supplied as a link, which I can click, leading me to the write file- thus, I don't think the path is wrong.
Here is my code:
String first = "C:/Users/andno/Desktop/AndroidDev2ClimateApp/app/src/main/java/com/example/androiddev2climateapp/ui/home/test.json";
try {
String fileContents = new String((Files.readAllBytes(Paths.get(first))));
JSONObject json = new JSONObject(fileContents);
JSONArray widgets = new JSONArray("WidgetArray");
for(int i = 0; i < widgets.length(); i++){
int id = widgets.getJSONObject(i).getInt("id");
System.out.println(id);
}
} catch(IOException | JSONException e){
e.printStackTrace();
}
Sorry that the formatting is messed up. I have tried using \ in the path instead of / as well, but it doesn't work. Any help would be greatly appreciated- thanks so much!
You may be able to get this code to work when you're testing, but obviously, there is no C:\Users\andno on your android phone and there never will be.
You're barking up the wrong tree. You don't want to read a file at all.
You want to read a resource from the same place java (or, rather, android) is loading the class file (or whatever passes for class file in android). Which is probably from within a jar or apk or whatnot.
UiMain.class.getResource("test.json")
or
UiMain.class.getResourceAsStream("test.json")
will get you a resource named test.json from the same place that UiMain.class is located (i.e. in the same package, I'm assuming this is class com.example.android.androiddev2climateapp.home.ui.UiMain. The first one as a URL, which you can usually pass to constructors of images and the like, and the second as stream, which you'd need to safely close (try/finally or try-with-resources if android has gotten around to adding that 20 year old java feature already), and which you can turn into a string using various APIs. Probably the JSON API itself can just be fed an inputstream.

getResourceAsStream returning null with android when trying to retrieve JSON file

Trying to assign in to the file credentials.json in Android Studio but when I try to print in to check the that the value isn't null it returns null
InputStream in = getClass().getClassLoader().getResourceAsStream("/raw/credentials.json");
the project structure is:
app
|-src
|main
|java
|com.appProject
|myClass
|res
|raw
|credentials.json
The file is called from a class outside of the main activity called myClass.
Either the method I need a different approach to getting a stream from a json file or my file path is all wrong
EDIT
The answer given is correct, but it is vital that context is set correctly in your application as well, as I made the mistake of not setting it up correctly to the MainActivity
That is not how you access a raw resource in Android.
To get an InputStream on a raw resource, you can use a Context, such as your Activity:
context.getResources().openRawResource(R.raw.credentials);

FileTransfer "Saved file:" followed by FileNotFoundException

My app downloads a zip file from a remote webserver, then extracts it.
The javascript successfully calls FileTransfer, which logs:
FileTransfer Saved file: file:///data/data/com.yadda.yadda/update.zip
As part of the success function, javascript calls my custom update plugin which immediately tests for the file:
Context ctx = this.cordova.getActivity().getBaseContext();
File update = new File(ctx.getFilesDir(),"update.zip");
if(!update.exists()) Log.w("File not found",update.getAbsolutePath());
The log for that last line is:
File Not Found /data/data/com.yadda.yadda/update.zip
Later in a try/catch block I have an InputStream variable created and one of the catch blocks is a FileNotFoundException which is firing every time.
Begin edit - more info
The FileNotFoundException has an interesting bit. The file path is wrong - even though I'm sending the same "update" variable to create the FileInputStream
InputStream fileis = new FileInputStream(update);
And the interesting bit of the exception:
Caused by: java.io.FileNotFoundException: /data/data/com.yadda.yadda/files/update.zip
End edit
What is going wrong here? Cordova logs that the file transfer completed and the file was saved, but then the file doesn't exist when I test for it! When I create the FileInputStream, why is the path different, causing the exception?
What am I missing? Everything works fine in the IOS version of the app.
Edit 2: per request, I browsed the device filesystem and found that update.zip does indeed exist in /data/user/0/com.yadda.yadda
OK, somewhere there is a bug. I'm inclined to believe it's a bug in getAbsolutePath() because I'm seeing consistent operation elsewhere.
When I create the "File update" variable, then immediately test and log the update.getAbsolutePath() - it shows the correct path. But when I attempt to create the FileInputStream, the path is different (+ /files/)
So, a little searching and I found that in order to access the application data directory (without /files) I must send a different directory with the new File command. Here's what it looks like:
File update = new File(ctx.getApplicationInfo().dataDir,"update.zip");
Obtaining the dir with getFilesDir()
ctx.getFilesDir() = /data/data/com.yadda.yadda/files
Obtaining the correct dir
ctx.getApplicationInfo().dataDir = /data/data/com.yadda.yadda

Reading object from file using ObjectInputStream? ClassNotFoundException

In previous code in my program, I had saved an ArrayList (consisting of objects of a custom class called location as you can see in my code) in a file using ObjectOutputStream and FileOutPutStream. However, when trying to retrieve the object from the file, using ObjectInputStream, I am getting an error saying that I have an unhandled exception (ClassNotFoundException).
Here's the code I used to get the ArrayList out of the file:
String file = "file";
ObjectInputStream input = new ObjectInputStream(new FileInputStream("file"));
ArrayList<location> arrayList = new ArrayList<location>();
arrayList = (ArrayList) input.readObject();
The error is on the line where I call the .readObject() method. Any Help will be appreciated as I am new to Java. Thank You!
That means the class you sent could not be found in your app. You have to add it to the class path of the app, or only send classes the app has. In your case, the missing class will be in the ArrayList as ArrayList will always be there.
Nothing mysterious is going on, the error means just what it says.
It would be more useful if the exception told you which class was missing. I think Java 7 does this now.

FileInputStream and FileNotFound Exception

I am trying to retrieve a jrxml file in a relative path using the following java code:
String jasperFileName = "/web/WEB-INF/reports/MemberOrderListReport.jrxml";
File report = new File(jasperFileName);
FileInputStream fis = new FileInputStream(report);
However, most probably I didn't succeed in defining the relative path and get an java.io.FileNotFoundException: error during the execution.
Since I am not so experienced in Java I/O operations, I didn't solve my problem. Any helps or ideas are welcomed.
You're trying to treat the jrxml file as an object on the file-system, but that's not applicable inside a web application.
You don't know how or where your application will be deployed, so you can't point a File at it.
Instead you want to use getResourceAsStream from the ServletContext. Something like:
String resourceName = "/WEB-INF/reports/MemberOrderListReport.jrxml"
InputStream is = getServletContext().getResourceAsStream(resourceName);
is what you're after.
You should place 'MemberOrderListReport.jrxml' in classpath, such as it being included in a jar placed in web-inf\lib or as a file in web-inf\classes.
The you can read the file using the following code:
InputStream is=YourClass.class.getClassLoader().getResourceAsStream("MemberOrderListReport.jrxml");
String jasperFileName = "/web/WEB-INF/reports/MemberOrderListReport.jrxml";
Simple. You don't have a /web/WEB-INF/reports/MemoberOrderListReport.jrxml file on your computer.
You are clearly executing in a web-app environment and expecting the system to automatically resolve that in the context of the web-app container. It doesn't. That's what getRealPath() and friends are for.
check that your relative base path is that one you think is:
File f = new File("test.txt");
System.out.println(f.getAbsoluteFile());
I've seen this kind of problem many times, and the answer is always the same...
The problem is the file path isn't what you think it is. To figure it out, simply add this line after creating the File:
System.out.println(report.getAbsolutePath());
Look at the output and you immediately see what the problem is.

Categories

Resources