Why can't filereader find my file? [duplicate] - java

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
My app won't launch and points to a Null Pointer Exception on my FileReader fr. I initialized it as null to prevent a "Variable may not have been initialized" error. I know the file I want it to use is there under downloads. The file is also inside the main project folder and putting just "academiccalendar.json" does not work either.
My main activity:
public class MainActivity extends AppCompatActivity {
Event[] mobileArray;
Gson gson = new Gson();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BufferedReader br;
FileReader fr = null;
try {
fr = new FileReader("C:/Users/Ali/Downloads/academiccalendar.json");
}
catch (FileNotFoundException e){
e.printStackTrace();
}
br = new BufferedReader(fr);
//br = new BufferedReader(new FileReader("C:/Users/Ali/Downloads/academiccalendar.json"));
mobileArray = gson.fromJson(br, Event[].class);
My logcat output:
12-31 20:06:37.368 9449-9449/com.example.test.testassigment E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.test.testassigment/com.example.test.testassigment.MainActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1967)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1992)
at android.app.ActivityThread.access$600(ActivityThread.java:127)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1158)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4511)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:976)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:743)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at java.io.Reader.<init>(Reader.java:64)
at java.io.BufferedReader.<init>(BufferedReader.java:92)
at java.io.BufferedReader.<init>(BufferedReader.java:80)
at com.example.test.testassigment.MainActivity.onCreate(MainActivity.java:42)
at android.app.Activity.performCreate(Activity.java:4486)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1052)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1931)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1992) 
at android.app.ActivityThread.access$600(ActivityThread.java:127) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1158) 
at android.os.Handler.dispatchMessage(Handler.java:99) 
at android.os.Looper.loop(Looper.java:137) 
at android.app.ActivityThread.main(ActivityThread.java:4511) 
at java.lang.reflect.Method.invokeNative(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:511)

"C:/Users/Ali/Downloads/academiccalendar.json"
That is a path on your Windows PC. Windows uses drive letters.
Your Android app cannot read files from your PC of course. Or from mine ;-).
I suppose your Android app wants to read a file which is on your Android device.
Try to determine the file on the file system of your Android device.

Because of your path defination. You can use this:
fr = new FileReader("C:\\Users\\Ali\\Downloads\\academiccalendar.json");

Related

Getting `File not found` errors for an `asset`. How can this be?

I'm about to go nuts with this. I keep getting errors when trying to open a text file that's in my assets directory, whose full path name is
C:\Users\Dov\Google Drive\AndroidStudioProjects\WordyHelperton - Copy - Copy\
app\src\main\assets
Even though we can SEE filename Dictionary.dic in the assets folder for my project...
... I keep getting errors that the file doesn't exist:
W/`````: Can't open <Dictionary.dic>
W/System.err: java.io.FileNotFoundException: Dictionary.dic
W/System.err: at android.content.res.AssetManager.openAsset(Native Method)
W/System.err: at android.content.res.AssetManager.open(AssetManager.java:316)
W/System.err: at android.content.res.AssetManager.open(AssetManager.java:290)
W/System.err: at com.dslomer64.servyhelperton.DatabaseConnector$LoadDatabase.doInBackground(DatabaseConnector.java:328)
W/System.err: at com.dslomer64.servyhelperton.DatabaseConnector$LoadDatabase.doInBackground(DatabaseConnector.java:315)
W/System.err: at android.os.AsyncTask$2.call(AsyncTask.java:288)
W/System.err: at java.util.concurrent.FutureTask.run(FutureTask.java:237)
W/System.err: at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
W/System.err: at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
W/System.err: at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
W/System.err: at java.lang.Thread.run(Thread.java:841)
Doc says you can use hierarchical name in the open statement:
W/`````: Can't open <C:\Users\Dov\Google Drive\AndroidStudioProjects\WordyHelperton - Copy - Copy\app\src\main\assets\Dictionary.dic>
W/System.err: java.io.FileNotFoundException: C:\Users\Dov\Google Drive\AndroidStudioProjects\WordyHelperton - Copy - Copy\app\src\main\assets\Dictionary.dic
W/System.err: at android.content.res.AssetManager.openAsset(Native Method)
W/System.err: at android.content.res.AssetManager.open(AssetManager.java:316)
W/System.err: at android.content.res.AssetManager.open(AssetManager.java:290)
W/System.err: at com.dslomer64.servyhelperton.DatabaseConnector$LoadDatabase.doInBackground(DatabaseConnector.java:330)
W/System.err: at com.dslomer64.servyhelperton.DatabaseConnector$LoadDatabase.doInBackground(DatabaseConnector.java:317)
W/System.err: at android.os.AsyncTask$2.call(AsyncTask.java:288)
Same problem.
Can you see any problem with my code? The problem HAS to be obvious, but after two days of trying this and that and utterly failing, and it LOOKS so good and therefore MUST be obvious, but I CAN'T SEE IT....
I've included this in case it's not obvious from above. If this doesn't help, I'm on my own.
Here is how DatabaseConnector gets called in onCreate in MainActivity:
assets = getAssets();
dbc = new DatabaseConnector(getApplicationContext(), assets); // to create DB if needed
Here's how mAssets and SOURCE_NAME are defined; also have DatabaseConnector definition and its call to dbOpenHelper.
Here's how LoadDatabase is called from createDbIfNecessary:
LoadDatabase
__loadDb;
__loadDb = new LoadDatabase();
__loadDb.execute((Object[]) null);
EDIT
Another opinion:
EDIT 2
Please note that changing the filename in the code to lowercase doesn't help. AND it's a DOS file, NOT ANDROID. AND File is never leaving drive C:
public static String DATABASE_SOURCE =
"C:\\Users\\Dov\\Desktop\\ServyHelperton\\app\\src\\main" +
"\\assets\\dictionary.dic";
W/`````: Can't open <C:\Users\Dov\Desktop\ServyHelperton\app\src\main\assets\dictionary.dic>
W/System.err: java.io.FileNotFoundException: C:\Users\Dov\Desktop\ServyHelperton\app\src\main\assets\dictionary.dic
I could add more code to prove what I just said, but trust me. The DATABASE_SOURCE name is ALL I changed.
It appears your path is for Dictionary.dic rather than dictionary.dic
See if that helps
In the end, the fix was sort of easy or maybe dumb luck, because I'm not sure why making the InputStream and Scanner local to doInBackground cured the problem.
Refer to the first picture in the original Question. I made no significant changes to MainActivity, but here is the interesting line in it:
dbc = new DatabaseConnector(getApplicationContext(), getAssets());
This is what worked:
public class DatabaseConnector
{
static Context mContext;
public DatabaseConnector(Context _context, AssetManager _assets)
{
mAssets = _assets;
mContext = _context;
mDbOpenHelper = new DbOpenHelper(_context, DATABASE_NAME, null, 1);
createDbIfNecessary();
}
private class DbOpenHelper extends SQLiteOpenHelper
{
DbOpenHelper(Context _context, String _name, CursorFactory _factory, int _version)
{
super(_context, _name, _factory, _version);
}
private class LoadDatabase extends AsyncTask<Object, Integer, Void>
{
protected Void doInBackground(Object[] params)
{
Scanner scDict = null; // ***** MOVING/ADDING THESE
InputStream stream; // ***** TWO LINES HERE WAS KEY
try{
stream = mContext.getAssets().open(DATABASE_SOURCE);
scDict = new Scanner(stream).useDelimiter("\r\n");
}
catch(IOException e){e.printStackTrace(); System.exit(69);}
}
}
}
}

Android studio - ArrayList into ListView conflict [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I did not understand the Error i am getting;
my elements declared as following;
ListView listViewLocations;
private ArrayAdapter<String> listAdapter ;
ArrayList<Long> addressList = new ArrayList<Long>();
and inside onCreate;
listViewLocations = (ListView) findViewById(R.id.listViewLocations);
ArrayList<Long> addresses = new ArrayList<>();
then the method displayed in the picture.
In my Stacktrace i made sure to log the final ArrayList by commenting the code and adding the log.i statement in order to confirm the retrieval of Data, and it is logging it as an Array;
5-08 14:28:06.265 22794-22794/net.we4x4 I/myTag: [20.4203339/84.5712178, 62.4334592/94.5716614, 22.4214592/59.5711114]
Simply i am trying to put this Array in a listView and i followed a simple tutorial on how to do so :
http://windrealm.org/tutorials/android/android-listview.php
Then i tried declaring the ArrayList in a different way;
ListView listViewLocations;
private ArrayAdapter<String> listAdapter ;
ArrayList addressList;
to resolve the redline (error shown in the picture)
and i got this error in my stack trace;
05-08 15:12:16.790 22349-22349/net.we4x4 E/AndroidRuntime: FATAL EXCEPTION: main
Process: net.we4x4, PID: 22349
java.lang.NullPointerException
at android.widget.ArrayAdapter.getCount(ArrayAdapter.java:330)
at android.widget.ListView.setAdapter(ListView.java:486)
at net.we4x4.GPSlocations.listAddresses(GPSlocations.java:228)
at net.we4x4.GPSlocations.access$000(GPSlocations.java:47)
at net.we4x4.GPSlocations$1.onClick(GPSlocations.java:93)
at android.view.View.performClick(View.java:4508)
at android.view.View$PerformClick.run(View.java:18675)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5584)
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:1268)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1084)
at dalvik.system.NativeStart.main(Native Method)
I believe that forgot to create listAdapter
listAdapter = new ArrayAdapter<string>();

Parsing a text file in android from an HTML

So I have been working on this for a bit and hit a brick wall. It keeps giving me a fatal error when it start to process.
So basically I want to read in a text file off the internet and then parse it so I can start to break that apart and use a JSON parser to deal with JSON data. But that further down the line (and i have the part built). I just am having trouble with the connection and downloading of the data. I just want to read in the text file and then print it out again.
Thank you for any help with this.
This is what it gives me
01-26 15:11:48.373 1958-1958/com.example.mmillar.urljsonparser I/art: Not late-enabling -Xcheck:jni (already on)
01-26 15:11:48.556 1958-1958/com.example.mmillar.urljsonparser D/HTML P1:: http://textfiles.com/100/914bbs.txt
01-26 15:11:48.556 1958-1958/com.example.mmillar.urljsonparser D/HTML P2:: http://textfiles.com/100/914bbs.txt
01-26 15:11:48.557 1958-1958/com.example.mmillar.urljsonparser D/HTML inJSON:: http://textfiles.com/100/914bbs.txt
01-26 15:11:48.569 1958-1958/com.example.mmillar.urljsonparser D/Status:: Connection Opened
01-26 15:11:48.569 1958-1958/com.example.mmillar.urljsonparser D/Status:: Closing connection
01-26 15:11:48.569 1958-1958/com.example.mmillar.urljsonparser D/AndroidRuntime: Shutting down VM
01-26 15:11:48.570 1958-1958/com.example.mmillar.urljsonparser E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.mmillar.urljsonparser, PID: 1958
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.mmillar.urljsonparser/com.example.mmillar.urljsonparser.MainActivity}: android.os.NetworkOnMainThreadException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2325)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Caused by: android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1147)
at java.net.InetAddress.lookupHostByName(InetAddress.java:418)
at java.net.InetAddress.getAllByNameImpl(InetAddress.java:252)
at java.net.InetAddress.getAllByName(InetAddress.java:215)
at com.android.okhttp.HostResolver$1.getAllByName(HostResolver.java:29)
at com.android.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:232)
at com.android.okhttp.internal.http.RouteSelector.next(RouteSelector.java:124)
at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:272)
at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:211)
at com.android.okhttp.internal.http.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:382)
at com.android.okhttp.internal.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:332)
at com.android.okhttp.internal.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:199)
at com.example.mmillar.urljsonparser.JSONParser.getStream(JSONParser.java:40)
at com.example.mmillar.urljsonparser.MainActivity.onCreate(MainActivity.java:24)
at android.app.Activity.performCreate(Activity.java:5990)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387) 
at android.app.ActivityThread.access$800(ActivityThread.java:151) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:135) 
at android.app.ActivityThread.main(ActivityThread.java:5254) 
at java.lang.reflect.Method.invoke(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:372) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698) 
01-26 15:11:53.474 1958-1958/? I/Process: Sending signal. PID: 1958 SIG: 9
So I'm a bit lost to where this is going wrong. I think I have everything set up and going good. Like the inputstream, bufferreader and all. So here is what I have.
This is the Parser program
public class JSONParser extends AsyncTask<String, Void, String>{
#Override
protected String doInBackground(String... inputUrl) {
getStream(inputUrl[0]);
return null;
}
public void getStream(String urlString)
{
Log.d("HTML inJSON: ", urlString );
//variables for the connection and downloading the JSON data
URL url = null;
HttpURLConnection urlConnection = null;
InputStream inputStream = null;
try {
url = new URL(urlString);
urlConnection = (HttpURLConnection)url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
Log.d("Status:","Connection Opened");
//read in the data
BufferedReader br = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
//build the data for parsing
StringBuilder myString = new StringBuilder();
String line;
while((line = br.readLine()) !=null)
{
myString.append(line);
}
Log.d("Status:"," JSON loaded into string");
Log.d("Total:", myString.toString());
} catch (IOException e) {
e.printStackTrace();
}finally {
if (urlConnection != null)
{
//close the connection
urlConnection.disconnect();
Log.d("Status:", " Closing connection");
}
}
}
}
And here is the main program I just run the thing because I just want to output from the file to the console I just want to make sure it works.
public class MainActivity extends AppCompatActivity {
//http://textfiles.com/100/914bbs.txt
private String testHtml = "http://textfiles.com/100/914bbs.txt";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d("HTML P1: ", testHtml );
JSONParser jp = new JSONParser();
Log.d("HTML P2: ", testHtml );
jp.getStream(testHtml);
Log.d("HTML P3: ", testHtml);
}
instead of using
jp.getStream(testHtml);
use
jp.execute("stream url here");
Currently you are trying to create a function in your Asynctask, but are not leveraging the use of AsyncTask. It still tries to make a HttpConnection on the mainThread, and that throws the exception.

UrlConnection.getInputStream() returns an exception that is null in Java

I have the following java code
try {
String u = "http://webapi.com/demo.zip";
URL url = new URL(u);
URLConnection ucon = url.openConnection();
InputStream is = ucon.getInputStream();
}
catch (Exception e) {
Log.d('downloaderror', e.getMessage());
}
But for some reason, the InputStream is = ucon.getInputStream() causes an error and the catch block is fired. And when the catch block is fired, the value of e is null.
Does anyone konw what is wrong with my ucon.getInputStream() ? I know for a fact that http://webapi.com/demo.zip exists, because I'm able to download the file from my web browser.
EDIT
Here's the stack trace on ucon.getInputstream()
java.lang.Exception
at com.example.instantramenz.samplewebview.MainActivity$1.onClick(MainActivity.java:94)
at android.view.View.performClick(View.java:4633)
at android.view.View$PerformClick.run(View.java:19270)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:146)
at android.app.ActivityThread.main(ActivityThread.java:5602)
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)
i fixed the problem by putting this line of code before downloading the file:
android.os.StrictMode.ThreadPolicy policy = new android.os.StrictMode.ThreadPolicy.Builder().permitAll().build();
android.os.StrictMode.setThreadPolicy(policy);

(Android) No Class Def Found Error for com.loopj.android.http.AsyncHttpClient

I've added the following (http://loopj.com/android-async-http/) to my /libs folder and have also put it in the module settings as a library and ticked the export button. In the actual file there are no errors given that it can't find the class and when I do import com.loopj and so-forth it completes it for me and shows me the available options.
However, when I run it on my phone it gives the following errors:
12-02 23:00:08.943 8209-8209/mobi.vassilev.beam E/dalvikvm﹕ Could not find class 'com.loopj.android.http.AsyncHttpClient', referenced from method mobi.vassilev.beam.GoogleLoginActivity.requestAPIKeyFromOAuthToken
12-02 23:00:09.183 8209-8209/mobi.vassilev.beam E/﹕ file /data/data/com.nvidia.NvCPLSvc/files/driverlist.txt: not found!
12-02 23:00:10.453 8382-8382/? E/ObjectHelper﹕ Can't find method:setCompatibilityInfo
12-02 23:00:10.598 8209-8209/mobi.vassilev.beam E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.NoClassDefFoundError: com.loopj.android.http.AsyncHttpClient
at mobi.vassilev.beam.GoogleLoginActivity.requestAPIKeyFromOAuthToken(GoogleLoginActivity.java:118)
at mobi.vassilev.beam.GoogleLoginActivity.access$200(GoogleLoginActivity.java:24)
at mobi.vassilev.beam.GoogleLoginActivity$OnTokenAcquired.run(GoogleLoginActivity.java:105)
at android.accounts.AccountManager$11.run(AccountManager.java:1335)
at android.os.Handler.handleCallback(Handler.java:725)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:158)
at android.app.ActivityThread.main(ActivityThread.java:5751)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1083)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:850)
at dalvik.system.NativeStart.main(Native Method)
12-02 23:00:10.633 513-548/? E/EmbeddedLogger﹕ App crashed! Process: mobi.vassilev.beam
and the extract of code (not complete obv as the URL is fake, but that shouldn't affect anything):
private void requestAPIKeyFromOAuthToken(String token) {
AsyncHttpClient client = new AsyncHttpClient(); // <-- this is line 118
RequestParams params = new RequestParams("token", token);
client.post("https://myrailsapp.com/api/v1/auth/verify", params, new AsyncHttpResponseHandler() {
#Override
public void onSuccess(String response) {
Log.w("OAUTH", "Got API key from server: " + response);
finish();
}
#Override
public void onFailure(Throwable e) {
Log.w("OAUTH", "Error getting API key");
Toast.makeText(getApplicationContext(), R.string.connection_error_message, Toast.LENGTH_LONG).show();
e.printStackTrace();
}
});
}
Would anyone know a solution to this problem?
Thank you very much,
Daniel
In Android Studio, you have to add your jar into the lib folder, add the dependency into the build.gradle file and call gradlew clean from console. The gradlew is in your project directory.
Check this thread for more details: Android Studio: Add jar as library?

Categories

Resources