Android crashes when looping through a string array [Android Studio] - android

I am trying to filter out specific strings in an array with the following code, but it keeps crashes when I try to run it.
public String[] lister(String[] fl){
String[] filelist = {};
int j = 0;
for(int i = 0; i < fl.length; i++){
if (fl[i].contains("Incident ")){
filelist[j] = fl[i];
j++;
}
}
return filelist;
}
I already tried some things, and it seems to be that
filelist[j] = fl[i];
is the culprit.
When I run
public String[] lister(String[] fl){
String[] filelist = {};
int j = 0;
for(int i = 0; i < fl.length; i++){
if (fl[i].contains("Incident ")){
//filelist[j] = fl[i];
j++;
}
}
filelist = fl;
return filelist;
}
It doesn't crash, even though it runs the forloop. Obviously the result is not what I need.
I don't understand why it does this? For some reason it feels as if it doesn't see 'filelist' initialized in the forloop.

Instead of array use ArrayList.
List<String> filelist = new ArrayList();
for(int i = 0; i < fl.length; i++){
if (fl[i].contains("Incident ")){
filelist.add(fl[i]);
}
}
return filelist;

Not possible to declare an array of unknown length, arrays are constant in length. Its better to use java.util.List implementation like ArrayList or List.
Or give your array a size like
String[] filelist = new String[3];
Solution 1: Using ArrayList
public String[] lister(String[] fl){
List<String> filelist = new ArrayList();
for(int i = 0; i < fl.length; i++){
if (fl[i].contains("Incident ")){
filelist.add(fl[i]);
}
}
return filelist;
}
Solution 2: Giving array a fixed length (Useful only if you know the length already)
public String[] lister(String[] fl){
String[] filelist = new String[3]; // or any size
for(int i = 0; i < fl.length; i++){
if (fl[i].contains("Incident ")){
filelist[i] = fl[i];
}
}
return filelist;
}
Note: Variable j is not really required

That's because the length of the variable filelist is 0, as you give no values {}, so you are getting ArrayIndexOutOfBoundsException as filelist[j] will always exceed the array bounds whatever the value of j is, so you have to define it like the following:
String[] filelist = new String[fl.length];

Related

why I'm getting error when I want rewrite String[ ] with duplicate to String[ ] without duplicate

Hi I have String[] array with repeating data.
I want to rewrite this array to new String[] array2, without duplicate.
Cursor c;
c= myDbHelper.getReadableDatabase().rawQuery("SELECT * FROM BusPlan", null);
c.moveToFirst();
int columnCnt = c.getCount();
String[] stringArray = new String[columnCnt]; //deklaracja tablicy stringArray
String[] stringArray2 = new String[columnCnt];
for(int i = 0; i < columnCnt ; i++){
String variable= new String();
variable=c.getString(c.getColumnIndex("Bushaltestelle"));
stringArray2[i] = c.getString(c.getColumnIndex("Bushaltestelle"));
c.moveToNext();
for (int j=0;j< columnCnt;j++){
if(!variable.equals(stringArray2[j].toString())){
stringArray[j]= c.getString(c.getColumnIndex("Bushaltestelle"));
}
}
}
what I'm doing wrong?
How to make it working?
I solved problem using Hashset, but I'm not happy from that.
Spinner spinner= (Spinner) findViewById(R.id.spinner);
Cursor c;
c= myDbHelper.getReadableDatabase().rawQuery("SELECT * FROM BusPlan", null);
c.moveToFirst();
int columnCnt = c.getCount();
String[] stringArray = new String[columnCnt]; //deklaracja tablicy stringArray
String[] stringArray2 = new String[columnCnt];
for(int i = 0; i < columnCnt ; i++){
stringArray[i] = c.getString(c.getColumnIndex("Bushaltestelle"));
c.moveToNext();}
stringArray2 = new HashSet<String>(Arrays.asList(stringArray)).toArray(new String[0]);
ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(Bodo.this, android.R.layout.simple_spinner_item,stringArray2); //selected item will look like a spinner set from XML
spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(spinnerArrayAdapter);
TextView tv = (TextView) findViewById(R.id.textView);
tv.setText(stringArray[16]);
If someone know how to make it working using arrays I'll be glad for info
In your for (int j loop your overwriting all data thats not equal to the new data. Try this:
Cursor c;
c= myDbHelper.getReadableDatabase().rawQuery("SELECT * FROM BusPlan", null);
c.moveToFirst();
int columnCnt = c.getCount();
String[] stringArray = new String[columnCnt]; //deklaracja tablicy stringArray
String[] stringArray2 = new String[columnCnt];
for(int i = 0; i < columnCnt ; i++){
String variable = c.getString(c.getColumnIndex("Bushaltestelle"));
stringArray[i] = variable;
c.moveToNext();
if (variable == null)
continue;
for (int j=0;j< columnCnt;j++){
if (stringArray2[j] != null && variable.equals(stringArray2[j].toString())) {
break; // duplicate so ignore
}
if (stringArray2[j] == null) {
stringArray2[j]= variable; // new empty slot, all already added data has already been passed by the loop
break;
}
}
}

Compare two array-list element and get un-common element

I have done something like this :
public class MainActivity extends AppCompatActivity {
ArrayList<String> al = new ArrayList<String>();
ArrayList<String> a2 = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
al.add("C");
al.add("A");
al.add("E");
al.add("B");
al.add("D");
al.add("F");
a2.add("C");
a2.add("C");
a2.add("E");
a2.add("B");
a2.add("D");
a2.add("F");
for (int i = 0; i < al.size(); i++) {
for (int j = 0; j < a2.size(); j++) {
if (al.get(i).equals(a2.get(j))) {
a2.remove(j);
Log.e("array 2 ", a2.toString());
break;
}
}
}
}
}
-- But my output is like this :
[C, E, B, D, F]
[C, B, D, F]
[C, D, F]
[C, F]
[C]
-- i am having same elements in arraylist 2, then also i am getting 'C', it should be null .i.e zero un-common value.
You are messing with the index when you remove the a2 items directly inside for loop. Refer to my solution below
ArrayList<String> al = new ArrayList<>();
ArrayList<String> a2 = new ArrayList<>();
al.add("C");
al.add("A");
al.add("E");
al.add("B");
al.add("D");
al.add("F");
a2.add("C");
a2.add("C");
a2.add("E");
a2.add("B");
a2.add("D");
a2.add("F");
ArrayList<String> tempToDelete = new ArrayList<>();
for (int i = 0; i < al.size(); i++) {
for (int j = 0; j < a2.size(); j++) {
if (al.get(i).equals(a2.get(j))) {
tempToDelete.add(a2.get(j));
break;
}
}
}
a2.removeAll(tempToDelete);
for shorter method, you can just do this:
a2.removeAll(al);
Try This it will help you
ArrayList<String> al = new ArrayList<String>();
ArrayList<String> a2 = new ArrayList<String>();
al.add("C");
al.add("A");
al.add("E");
al.add("B");
al.add("D");
al.add("F");
a2.add("C");
a2.add("C");
a2.add("E");
a2.add("B");
a2.add("D");
a2.add("F");
Integer a = null;
for (int i=0; i<a1.size(); i++)
{
a = a1.get(i);
if (a2.contains(a)
{
a2.remove(a);
a1.remove(a);
i--;
}
}
ArrayList<String> finaldata = new ArrayList<String>();
finaldata.addAll(a1);
finaldata.addAll(a2);
// finaldata = { A}
Just replace break; with this:
j = -1;
code:
for (int i = 0; i < al.size(); i++) {
for (int j = 0; j < a2.size(); j++) {
if (al.get(i).equals(a2.get(j))) {
a2.remove(j);
Log.e("array 2 ", a2.toString());
j = -1;
}
}
}
I recommend you to use Set's instead of ArrayList. You can find some info here.
Also, here you can read some examples of using java Set in set operations in this stackoverflow answer.

How to generate random number with out duplicates using JSON array in android

I am new to android. I am doing quize app.I have one JSON array text file.how to generate random number with out repetation using JSON array in android..please help me
Thank you adv..
this is my sample code
public static JSONArray getQuesList()throws JSONException{
ArrayList<Integer> list = new ArrayList<Integer>(size);
for(i =size - 1; i >= 0; i--) {
//index = rnd.nextInt(list.size());
list.add(i);
}
Random rand = new Random();
while(list.size() > 0) {
index = rand.nextInt(list.size());
Object object = quesList.get(index);
quesList.put(index, quesList.get(i));
quesList.put(i, object);
Log.d("","Selected: "+list.remove(index));
}
return quesList;
Edited
QuestionActivity.java
Global variable
int[] quizarray = null;
Add two functions
private void createQuizIndex() {
int[] array = new int[QuizFunActivity.getQuesList().length()];
quizarray = new int[QuizFunActivity.getQuesList().length()];
for(int i = 0 ; i < QuizFunActivity.getQuesList().length() ; i++){
array[i] = i;
}
Random random = new Random();
int m = 0;
for (int n = array.length ; n > 0; n--){
int r = random.nextInt(n);
quizarray[m++] = array[r];
array[r] = array[n-1];
}
}
private int getIndexNum(int quesIndex2) {
return quizarray[quesIndex2];
}
Change every showQuestion
showQuestion(getIndexNum(quesIndex),review);
Call createQuizIndex() in line 80, and line 194 if "Retake" means another random quiz

I want to delete a null column from a 2d array in android?

i have problem in data binding in expandable list view. here i use
ArrayList<ExpandListGroup> list = new ArrayList<ExpandListGroup>();
ExpandListGroup for data binding. but in sum 2d array there is null value.Data is coming dynamically .
eg:
String [] [] array1 = [[one,two,three,null],[seven,six,null]] ;
I want to remove the null column from this two dimensional array
You need to take a intermediate arraylist and result array and follows the below steps.
First copy the source array(containing null) into arraylist.
Then remove null from arraylist
Then create new array and copy data from arraylist to array.
private void remove_nulls()
{
String [] [] array1 = {{"one","two","three",null},{"seven","six",null}} ;
ArrayList<ArrayList<String>> contact = new ArrayList<ArrayList<String>>();
for(int i=0;i<array1.length;i++)
{
ArrayList<String> con = new ArrayList<String>();
for(int j=0;j<array1[i].length;j++)
{
if(array1[i][j]!=null)
con.add(array1[i][j]);
}
if(con.size()>0)
contact.add(con);
}
String [] [] array2 = new String[array1.length][];
for(int i=0;i<contact.size();i++)
{
array2[i]=new String[contact.get(i).size()];
for(int j=0;j<contact.get(i).size();j++)
{
array2[i][j]=contact.get(i).get(j);
}
}
}
Unless there is some trick to the question...
String[][] array1 = {{"one", "two", "three", null}, {"seven", "six", null}};
List<String[]> newList = new ArrayList<>();
for (int i = 0; i < array1.length; ++i) {
List<String> currentLine = new ArrayList<>();
for (int j = 0; j < array1[i].length; ++j) {
if (array1[i][j] != null) {
currentLine.add(array1[i][j]);
}
}
//create the array in place
newList.add(currentLine.toArray(new String[currentLine.size()]));
}
//no need to use an intermediate array
String[][] array2 = newList.toArray(new String [newList.size()][]);
//And a test for array2
for (int i = 0; i < array2.length; ++i) {
for (int j = 0; j < array2[i].length; ++j) {
System.out.print(array2[i][j] + " ");
}
System.out.println();
}
System.out.println("Compared to...");
//Compared to the original array1
for (int i = 0; i < array1.length; ++i) {
for (int j = 0; j < array1[i].length; ++j) {
System.out.print(array1[i][j] + " ");
}
System.out.println();
}

Convert 2d string array into ArrayList in android

How to convert 2d string array into ArrayList??
I have a 2d array of string, how can i covert it to array list???
If you want a full list of elements just do this. Probably there is a simple way
ArrayList<String> list = new ArrayList<String>();
for (int i=0; i < array_limit ; i++)
for (int j=0 ; j < array_limit; j++)
list.add(your_array[i][j]);
public static ArrayList<String> rowsToString(String[][] data) {
ArrayList<String> list = new ArrayList<String>();
for(int i = 0; i < data.length; i++) {
String row = Arrays.toString(data[i]);
list.add( row.substring(1, row.length()-1) );
}
return list;
}
Depends on what exactly you want. Try:
for(int i=0;i<a.length;i++){
newList.add(new ArrayList<String>());
for(int j=0;j<a.length;j++){
newList.get(i).add(a[i][j]);
}
}
Then you can access elements for example by:
newList.get(1).get(2);

Categories

Resources