NullPointerException when creating an array from a file- Android? - android

I am getting a nullpointerexception when I create a large array from a file. A new element is to be created for each line of the .txt file. I get the nullPointerException when I use the array created from this file.
Here is my code:
static String[] results=new String[172820];
public String[] getWords(){
try{
InputStream fstream = getResources().openRawResource(R.raw.enable1);
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
for (int x=0; (strLine = br.readLine()) != null; x++) {
results[x]=strLine;
}
in.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
return results;
}

At first I was going to mention that most devices have a maximum heap size of 16MB and that you might be exceeding that, but then I found this page. It would appear that 512 is the maximum array size. I would try the suggestion given by #kcoppock, and try an ArrayList.
As a side note: it would seem you're loading "words" into an array. No device on the market is anywhere near fast enough to iterate over a 172K item array with any efficiency; I believe you're setting the user up for a slow and painful experience.

Related

Reading data from a json file BufferedReader returns only null

I'm currently learning android with a books called "Android Programming - The Big Nerd Ranch Guide".
As a part of a learning project we create Json serializer for saving and loading data. Writing the file appearently works fine, and I get no error messages on the Logcat. After I terminate the app and recreate it, the data loader is called and raises the following exception:
org.json.JSONException: End of input at character 0
I've looked for this issue online and figured it's probably because the BufferedReader returns an empty response. I've checked and indeed it is the case.
For simplicity sake, I've temporarily put a BufferedReader into the saving function and tried reading the info I've just saved into the file, and still the BufferedReader returns only null.
public void saveCrimes(ArrayList<Crime>crimes)
throws JSONException, IOException {
JSONArray array = new JSONArray();
for(Crime c: crimes)
array.put(c.toJSON());
Writer writer = null;
try {
OutputStream out = mContext.openFileOutput(mFileName, Context.MODE_PRIVATE);
writer = new OutputStreamWriter(out);
writer.write(array.toString());
Log.d(TAG, array.toString());
} finally {
if(writer == null)
writer.close();
}
// Extracting the data
BufferedReader bufferedReader = null;
try {
InputStream inputStream = mContext.openFileInput(mFileName);
bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
if (bufferedReader.readLine() == null)
Log.d(TAG, "WHY GOD WHYYYYYYY");
}catch (IOException e){
}
}
(The two log messages from the code, the first one displays the data that is in the JsonArray I'm using)
D/CriminalIntentJSONSerializer: [{"date":"Mon May 14 17:33:08 GMT+00:00 2018","id":"97fe9532-991f-4352-9de1-602fa8dfa93e","isSolved":true,"title":""}]
D/CriminalIntentJSONSerializer: WHY GOD WHYYYYYYY
Would love to hear your insight.
BufferedReader bufferedReader = null;
try {
InputStream inputStream = mContext.openFileInput(mFileName);
bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
if (bufferedReader.readLine() == null)
Log.d(TAG, "WHY GOD WHYYYYYYY");
}catch (IOException e){
}
Ok. you've created your BufferedReader bufferedReader = null;
What happens when yuou say bufferedReader = new BufferedReader(anything)...Well...it can't call a new instance the same thing that's already been declared...in fact, it's already been instantiated as null. So you can't create a new instance of the same name.
Try deleting the line where you point it at null. Then, substitute
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
for the original declaration in your try block
Try to check if mFilename is empty on second try-catch, usually in Android instance disappear easily.
PD: I advise you choice another JSON library to manipulte JSON files, they are lightweight and easy-to-use.
== Edit ==
Have you added writing and reading permissions on AndroidManifest?
If answer is "there it is" try to debug app step-by-step looking for variables and in-variables for checking existence of values.
Could be file isn't writing itself or it's writing empty.
Error basically is empty string or non-format JSON-like:
""
"[{"a": "abdc", "b": "jef2","
Paying attention to BufferedReader because it read lines each and you need all file and then join into string variable.
Also, try to use android file explorer that come in AndroidStudio. There you can explore files, logs and database files and export them to your specific folders (Documents, Downloads, etc). Generally files written by app are stored in data -> <com.your.app.package>.

String Tokenizing from file in android

I have a file stored in my phone "SaveTT.txt" . Every word in the file is seperated by spaces. i wish to retrieve each word from the file and display every word in seperate textViews. How to do this. please help
I am able to retrieve the contents of the file into a string with the following code
try {
BufferedReader inputReader = new BufferedReader(new InputStreamReader(
openFileInput("SAVETT.txt")));
StringBuffer stringBuffer = new StringBuffer();
while ((inputString = inputReader.readLine()) != null) {
stringBuffer.append(inputString + "\n");
//EditText txt = (EditText) findViewById(R.id.temp);
//txt.setText(inputString);
}
} catch (IOException e) {
e.printStackTrace();
}
with this code get the entire string into inputString
after this . i am tokenizing the string with the following code
StringTokenizer tokenizer = new StringTokenizer(inputString);
String[] arr = new String[tokenizer.countTokens()];
while(tokenizer.hasMoreElements())
{
arr[i]= tokenizer.nextToken();
i++;
}
with the above code i am trying to save eack token in an array. Next I try to display the text in Textviews.
I dont know where i am goig wrong. the activity is stopped and a NullPointer exception is displayed.
I Figured out the problem myself. The problem was that the value of inputString is inaccessible from outside the Try catch block since it is set inside the block;
so if i write the string tokenisation block inside try catch it works perfectly fine

Separate different Strings from text

I want to read a txt file that contains a lot of different chunks of text separated by a string. In xcode this is pretty easy and i just use.
self.Array = [text componentsSeparatedByString: #"NEWSTRING"];
I don't seem to get this to work in android though, I can read in the whole text and put it into an array but it doesn't get separated so its just one long text.
I am using this code
AssetManager mngr;
String line = null;
boolean skillcheck = false;
StringBuffer sb = new StringBuffer(0);
String[] bb = null;
tester = new ArrayList <String>();
try {
mngr = getAssets();
InputStream is = mngr.open("mytext.txt");
InputStreamReader sir = new InputStreamReader(is);
BufferedReader br = new BufferedReader(sir);
while((line=br.readLine()) != null) {
sb.append(line);
sb.append("\n");
}
tester.add(sb);
br.close();
} catch (IOException e1) {
}
Any good ways to do this?
You can use String.split method
String[] result = text.split("sometext");
For your acknowledgement
String.split returns the array of strings computed by splitting this
string around matches of the given regular expression
You should use StringTokenizer.
StringTokenizer sTok=new StringTokenizer(stringVariable, "newString");
while(sTok.hasMoreTokens())
System.out.println(sTok.nextToken());
stringVariable is the file contents and newString is the delimiter string.
EDIT
The second parameter of the StringTokenizer's constructor is the delimiter. It can be a new line \n or comma , or whatever you want.

Strange characters in HTTP GET response

I'm trying to figure out why special characters in a JSON feed (that looks completely fine when viewed in a browser) will break when used in my Android code. Characters with accent marks, ellipsis characters, curly quote characters and so on are replaced by other characters--perhaps translating it from UTF-8 down to ASCII? I'm not sure. I'm using a GET request to pull JSON data from a server, parsing it, storing it in a database, then using Html.fromHtml() and placing the contents in a TextView.
After much experimentation, I narrowed down possibilities until I discovered the problem is with the Ignition HTTP libraries (https://github.com/kaeppler/ignition). Specifically, with ignitedHttpResponse.getResponseBodyAsString()
Although that's a handy shortcut, that one line results in the broken characters. Instead, I now use:
InputStream contentStream = ignitedHttpResponse.getResponseBody();
String content = Util.inputStreamToString(contentStream);
public static String inputStreamToString(InputStream is) throws IOException {
String line = "";
StringBuilder total = new StringBuilder();
// Wrap a BufferedReader around the InputStream
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
// Read response until the end
while ((line = rd.readLine()) != null) {
total.append(line);
}
// Return full string
return total.toString();
}
Edit: Adding more detail
Here is a minimum test case to reproduce the issue.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test);
activity = this;
instance = this;
String url = SaveConstants.URL;
IgnitedHttpRequest request = new IgnitedHttp(activity).get(url);
InputStream contentStream = null;
try {
IgnitedHttpResponse response = request.send();
String badContent = response.getResponseBodyAsString();
int start = badContent.indexOf("is Texas");
Log.e(TAG, "bad content: " + badContent.substring(start, start + 10));
contentStream = response.getResponseBody();
String goodContent = Util.inputStreamToString(contentStream);
start = goodContent.indexOf("is Texas");
Log.e(TAG, "good content: " + goodContent.substring(start, start + 10));
} catch (IOException ioe) {
Log.e(TAG, "error", ioe);
}
}
In the log:
bad content: is Texasâ good content: is Texas’
Update: either I'm crazy, or the problem only occurs in the clients' production feed, not their development feed, although the contents look identical when viewed in a browser--showing "Texas’". So perhaps there's some wonky server configuration required to cause this issue... but still, the fix for this issue when it occurs is as I outlined. I do not recommend using response.getResponseBodyAsString();

Android - Adding strings to hashmap

I am currently reading a dictionary.png (which is a text file) into a buffer.
.png to make android think it is compressed.
InputStream is = getResources().openRawResource(R.raw.dictionary);
try {
BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF8"));
String next;
while ((next = br.readLine()) != null) {
//Add the string next to a map or whatever
}
} catch (Exception e) {
//Something nasty happened
}
i'm not very familiar with HashMaps but i want to read the files from the dictionary into a hash map.
Any help would be appreciated.
An example that does something similar to what you're asking about: Using HashMap to map a String and int

Categories

Resources