I'm currently working on Android Studio. I want to read a file from asset folder but it gives me this error. does anyone encountered this problem ?
java.lang.IllegalArgumentException: n <= 0: 0
here's my code:
private String getRandomDataFromCategory(String name/* @param for the name of text file*/){
readings = "";
StringBuffer stringBuffer = new StringBuffer();
String[] temp;
try{
//getting file from asset folder
InputStream inputStream = getAssets().open(name + ".txt",AssetManager.ACCESS_BUFFER);
int size = inputStream.available();
byte[] buffer = new byte[size];
inputStream.read(buffer);
inputStream.close();
stringBuffer.append(new String(buffer));
// to check if stringBuffer isn't empty
if (stringBuffer.length() != 0){
//spliting stringBuffer
temp = stringBuffer.toString().split("\\`");
Random random = new Random();
// to create random index of array temp
int a = random.nextInt(temp.length - 1);
readings = temp[a];
}
}catch (Exception e) {
Toast.makeText(gaming.this, e.toString(),Toast.LENGTH_SHORT).show();
}
return readings;
}
this post is somehow similar to this post Android Random Number llegalArgumentException: n <= 0: 0 yet different
You can read your text file from assets this way:
public String getContentFromFile(String filename)
{
StringBuilder s=new StringBuilder();
try
{
InputStream is=getAssets().open(filename);
BufferedReader br=new BufferedReader(new InputStreamReader(is,Charset.forName("UTF-8")));
String line;
while((line=br.readLine())!=null)
{
s.append(line).append("\n");
}
}catch (Exception | Error e){e.printStackTrace();}
return s.toString();
}
You can customize it to fit your need and if doesn't work you can still ask for clarifications in comments.