Dynamically populating an expandableListView - android

So All I'm trying to do is create a dynamic expandableListView Currently It works if I just do the groupViews. The problem comes in when I have to populate the children of those groupViews.. I don't know if I'm doing something wrong, or if theres another better way to do it. If anyone knows please let me know. I'm open to anything.
Currently I'm pulling my data off a server and the error I'm getting is java null pointer exception. So I'm thinking it might have something to do with how big I specified my array sizes?
private static String[][] children = new String[7][4];
private static String[] groups = new String[7];
Here is the rest of the code when I try to populate the View.
public void getData(){
try {
int tempGroupCount = 0;
URL food_url = new URL (Constants.SERVER_DINING);
BufferedReader my_buffer = new BufferedReader(new InputStreamReader(food_url.openStream()));
temp = my_buffer.readLine();
// prime read
while (temp != null ){
childrenCount = 0;
// check to see if readline equals Location
//Log.w("HERasdfsafdsafdsafE", temp);
// start a new location
if (temp.equalsIgnoreCase("Location"))
{
temp = my_buffer.readLine();
groups[tempGroupCount] = temp;
tempGroupCount++;
Log.w("HERE IS TEMP", temp);
}
temp = my_buffer.readLine();
while (temp.equalsIgnoreCase("Location") == false){
Log.w("ONMG HEHREHRHERHER", temp);
children[groupCount][childrenCount] = "IAJHSDSAD";
childrenCount++;
temp = my_buffer.readLine();
}
groupCount++;
}
my_buffer.close();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
Log.e("IO EXCEPTION", "Exception occured in MyExpandableListAdapter:" + e.toString());
}
}

to me it looks like an error in the loop - as you are reading another line without checking is it null
your while loop should look something like this methinks:
// prime read
while (temp != null ){
int childrenCount = 0;
// check to see if readline equals Location
// start a new location
//Log.w("HERasdfsafdsafdsafE", temp);
if (temp.equalsIgnoreCase("Location"))
{
temp = my_buffer.readLine();
groups[tempGroupCount] = temp;
tempGroupCount++;
Log.w("HERE IS TEMP", temp);
}
//>>remove following line as that one isn't checked and
//>>you are loosing on a line that is potentialy a child
//temp = my_buffer.readLine();
//>>check do you have first item to add subitems
else if (tempGroupCount>0){
while (temp.equalsIgnoreCase("Location") == false){
Log.w("ONMG HEHREHRHERHER", temp);
children[tempGroupCount-1][childrenCount] = "IAJHSDSAD";
childrenCount++;
temp = my_buffer.readLine();
}
//>>next counter is probably not need but can't see if you're using it somewhere else
//groupCount++;
}

I would first replace strings array to some 2d collection for example arraylist2d ( you can google it ) so you could easally add and remove data from list. If you created adapter that extends BaseExpandableListAdapter everything should be handled without any problems.
About NULLPointer, could you paste stacktrace or more info on which line it occurs ?

Related

List all files, recursively, in Android Dropbox API

How can I list all files, recursively in DropBox folder?
I tried code below but returns no result:
result = dbxClient.files().search("", "*");
And this returns files in path, not subfolders:
result = dbxClient.files().listFolder(path);
You can get a ListFolderBuilder from listFolderBuilder and use the withRecursive option to list out sub-items as well.
Be sure to check ListFolderResult.hasMore to see if you should call back to listFolderContinue to get more results though.
You can check this link, navigate to inner class 'FolderScanTask'. It contains working code for Android:
https://github.com/ControlX/Android-Dropbox-UploadImage-To-SpecificFolder-By-FolderSelection/blob/master/app/src/main/java/io/github/controlx/dbxdemo/MainActivity.java
This is work in progress, here I'm just making an ArrayList for parent folders, has more logic as suggested by Greg is already there you just need to fill in that.
Code Snippet for the same:
String path = "";
DbxClientV2 dbxClient = DropboxClient.getClient(ACCESS_TOKEN);
TreeMap<String, Metadata> children = new TreeMap<String, Metadata>();
try {
try {
result = dbxClient.files()
.listFolder(path);
} catch (ListFolderErrorException ex) {
ex.printStackTrace();
}
List<Metadata> list = result.getEntries();
cs = new CharSequence[list.size()];
arrayList = new ArrayList<>();
arrayList.add("/");
while (true) {
int i = 0;
for (Metadata md : result.getEntries()) {
if (md instanceof DeletedMetadata) {
children.remove(md.getPathLower());
} else {
String fileOrFolder = md.getPathLower();
children.put(fileOrFolder, md);
if(!fileOrFolder.contains("."))
arrayList.add(fileOrFolder);
}
i++;
}
if (!result.getHasMore()) break;
try {
result = dbxClient.files()
.listFolderContinue(result.getCursor());
} catch (ListFolderContinueErrorException ex) {
ex.printStackTrace();
}
}
} catch (DbxException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
Here ArrayList is just for my use wherein I'm just making a list of only folders.
So, modify accordingly.

Randomize array of questions while reading from text file android

This is a android quiz app code snippet which load the question from text file.
I want to shuffle the question and answer after every next click so how can i implement random function ?
https://github.com/gitssk/quizfun/blob/master/src/ssk/quizfun/QuizFunActivity.java
https://github.com/gitssk/quizfun/blob/master/res/raw/questions.txt
private void loadQuestions() throws Exception {
try {
InputStream questions = this.getBaseContext().getResources()
.openRawResource(R.raw.questions);
bReader = new BufferedReader(new InputStreamReader(questions));
StringBuilder quesString = new StringBuilder();
String aJsonLine = null;
while ((aJsonLine = bReader.readLine()) != null) {
quesString.append(aJsonLine);
}
Log.d(this.getClass().toString(), quesString.toString());
JSONObject quesObj = new JSONObject(quesString.toString());
quesList = quesObj.getJSONArray("Questions");
Log.d(this.getClass().getName(),
"Num Questions " + quesList.length());
} catch (Exception e){
} finally {
try {
bReader.close();
} catch (Exception e) {
Log.e("", e.getMessage().toString(), e.getCause());
}
}
}
https://github.com/gitssk/quizfun/blob/master/src/ssk/quizfun/QuizFunActivity.java
I will refrain from posting much code because I think you should attempt it on your own. It is seriously not that tough. I will give you an approach though.
You have quesList = quesObj.getJSONArray("Questions");. So quesList is the list of questions that is a JSONArray. You want to shuffle this. Just do this:
Get the length of the quesList array. Let's call it len.
Create a simple arrayList called quesOrder containing integers 0 to len.
List<Integer> quesOrder = new ArrayList<>();
for (int i = 0; i <= len; i++)
{
quesOrder.add(i);
}
Once you have the quesOrder array. Just do Collections.shuffle(quesOrder);. Now when you get questions from your quesList array, just get the index from quesOrder list. And you will have a randomized selection. Put it together in a function for convenience.

I keep getting ArrayIndexOutOfBoundsException

Keep getting ArrayIndexOutOfBoundsException when trying to display a specific item form array list data displays fine in logcat but then after displaying throws exception at top please help is the code kind of new to android
public void loadData(){
InputStream file = ourContext.getResources().openRawResource(R.raw.cashpot);
BufferedReader reader = new BufferedReader(new InputStreamReader(file));
String line ="";
ArrayList<String> values = new ArrayList<String>();
try {
while((line = reader.readLine()) != null) {
values.add(line);
// String[] strings = line.split(",");
/*for(String s : strings) {
values.add(s);
}*/
}
reader.close();
//for(String s : values) Log.d("CSV Test", s);
for(int i = 0; i < values.size();i++){
String[] data = values.get(i).split(",");
Log.d("Test String",data[2] );
}
} catch (IOException e) {
e.printStackTrace();
}
}
Your some lines do not have comma(,)(or 1 comma) and you are trying to split them by comma and storing it in to data array. and you are accessing data[2] location. which might not been created that's why you are getting this exception.
There might not be a 3rd element in your array ,that is created after the split on ",".
You can print value of data before accessing data[2](that might not exist).
Or you can Debug your program and proceed step by step and monitoring the value of each variable.

Android: Getting into right condition using fileinputstream

I'm facing a different problem, see below is the code for my app that can read stored file and have to check condition according to that.
My inputs are "ON" and "OFF"
String val="";
final ToggleButton start = (ToggleButton) findViewById(R.id.startup);
FileInputStream fileos;
try {
fileos = openFileInput("startup");
byte[] input = new byte[fileos.available()];
while(fileos.read(input) != -1){
val += new String(input);
}
if(val.toString() == "ON"){
start.setChecked(true);
}else if(val.toString() == "OFF"){
start.setChecked(false);
}else{
start.setChecked(true);
}
fileos.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
The above code fetching the output correctly either "ON" or "OFF", But it Always going into else conditionelse
else{ start.setChecked(true); }
I'm stucked here, Please help me some one
android is based in java , in java you can't use "==" to compare two strings , you should replace
val.toString() == "ON"
to
"ON".equals(val.toString())
There are actually two big problems with this code. One is that you must use the equals() method to compare String objects, always -- the == operator is appropriate only in very limited cases.
The second one is more subtle, and won't break all the time. When you read data into input, although you're using a loop, the code will only work if all the data is read at once. This is because you're creating a String out of the entire array, even if the entire array doesn't contain valid data. The correct loop would look like this:
int count;
while((count = fileos.read(input)) != -1){
val += new String(input, 0, count);
}
you have to compare the string using .equals()
if(val.equals("ON")){
start.setChecked(true);
}else if(val.equals("OFF")){
start.setChecked(false);
}else{
start.setChecked(true);
}
Use String.equals() to compare Strings. Do no use ==
val.toString().equals("ON")

Get int from text file and set it to variable

I'm trying to get the int value of a text file that have text like:
123456789 12345678 1234567 123456 12345 1234 123 12 1
as you can see every number is different and they are in a same line separated by a "space". I need to get the values separated. to get something like this:
INT1 = 123456789, INT2 = 12345678, INT3 = 1234567;
and so on. I don't create the text so I don't know how much numbers and groups they are, but they are always separated by a "space". I know how to read it. This is how I'm reading it:
try {
TEST1 = new BufferedReader(new FileReader("/sdcard/test.txt")).readLine();
} catch (NumberFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
TEST.setText(""+scaling_available_frequencies);
and I got this output
194208 776175 958253 767883 700246 243663 966618 345199 945363 459833
NOTE: This is just a test.txt that I created to see if it works. The current code will ask the user for entering path and file name.
Now how can I set them to a variable per group?
Thanks
This is one way to parse the String to an integer array:
public int[] toIntArray( String stringFromFile ){
String[] allStrings = stringFromFile.split( "\\s" );
int[] intArray = new int[allStrings.length];
for( int i = 0; i < allStrings.length; ++i ){
try{
intArray[i] = Integer.parseInt( allStrings[i] );
}catch( NumberFormatException e ){
// Do whatever you think is appropriated
intArray[i] = -1;
}
}
return intArray;
}
Hope this helps.
I believe readLine() get you String.
You will need to use the Split() method of String and pass in the regularExpression (whitespace).
then you will need to use Integer.parseInt( ) method and pass in every string to parse them into Integer.
you also need a loop to do the parse until nothing left

Categories

Resources