Array index out of bounds exception android - android

I am trying to get the data from database table via php file and displaying it in android. In php file I seperated each column with "#".
So now I am getting values like 4#2012-11-06#test1#test2. But for some columns there is not data. So the values are comng like 5###.
Here when I splitting with # and displaying the data it is throwing out of bounds exception. How can I resolve this issue?
Code:
String st="1#2012-10-30#test1#2#2012-10-30#test2#3#2012-11-06#test3#9##test1#21###22###23###";
String[] val = st.trim().split("#");
for (int i = 0; i < val.length; i++)
{
String str = val[i];
String arr[] = str.split("#");
System.out.println("arr0" + arr[0]);
System.out.println("arr1" + arr[1]);
System.out.println("arr2" + arr[2]);
}

try as using Pattern.compile to split your current string :
String your_string = "4#2012-11-06#test1#test2";
Pattern pattern = Pattern.compile("#");
String[] strarray =pattern.split(your_string);
for Handling if array index contain empty string change your code as:
for (int i = 0; i < val.length; i++)
{
String your_string =val[i];
Pattern pattern = Pattern.compile("#");
String[] strarray =pattern.split(your_string);
for(int j=0;j<strarray.length;j++){
if(strarray[j].trim().length() >0){
System.out.println("arr"+j+"::" + strarray[j]);
}
else{
}
}
}

Related

How to get a random value from a string array without repetition?

How to get a random value from a string array in android without repetition?
I have array in String.xml file as below -
<string-array name="msg">
<item>Cow</item>
<item>Pig</item>
<item>Bird</item>
<item>Sheep</item>
</string-array>
I am selecting random string by using following code -
String[] array = Objects.requireNonNull(context).getResources().getStringArray(R.array.msg);
String Msg = array[new Random().nextInt(array.length)];
Can anyone help me please? Thanks is advance...!
Can you just do something like this:
Collections.shuffle(copyOfArray);
Then loop through that?
for (int i = 0; i < copyOfArray.size(); i++) {
println(copyOfArray.get(i))
}
try this -
array = Objects.requireNonNull(context).getResources().getStringArray(R.array.msg);
//String msg = array[new Random().nextInt(array.length)];
LinkedList<String> myList = new LinkedList<String>();
for (String i : array)
myList.add(i);
Collections.shuffle(myList);
for (int i = 0; i < myList.size(); i++) {
String msg=myList.get(i);
}
Try this solution,
LinkedList<String> myList = new LinkedList<String>();
String[] words = { "Cow", "Pig", "Bird", "Sheep" };
for (String i : words)
myList.add(i);
Collections.shuffle(myList);
Then,
sampleText.setText(myList.pollLast());
pollLast() in LinkedList will retrieves and removes the last element of this list, or returns null if this list is empty.
try this.
int max = array.length() - 1;
int min = 0;
String Msg = array[new Random().nextInt(max - min + 1) + min];
First convert your String resource array to ArrayList
Fill value from current ArrayList to HashSet and convert that HashSet to newly ArrayList
Now shuffle that new ArrayList

Handle comma separated string

Creating an app in which i want to get string from json but i have one key and multiple value so i don't know how to handle this.
"colours": "#fff600,#000000,#ffffff,#00000,#ff9900,#333333"
And want to use this color in different class:
final ValueAnimator colorAnimation = ValueAnimator.ofObject(new android.animation.ArgbEvaluator(), Color.RED, Color.BLUE,Color.WHITE,Color.YELLOW,Color.CYAN,Color.MAGENTA,Color.GREEN,Color.GRAY);
colorAnimation.setDuration(1400);
Put the value of colours in string variable and then split the string in following way and add it to an arraylist :
String[] arr = str.split(",");
ArrayList<String> arr1 = new ArrayList<String>();
for (int i=0; i<arr.length; i++){
arr1.add(arr[i]);
}
Get value of color and use string tokenizer with ',' delima like this:
StringTokenizer stringTokenizer = new StringTokenizer(colorValueString, ",");
Also it has stringTokenizer.nextToken to get the next color in string
You can get the value of colours as a string and then split the string into parts like this:
String colours = json.getString("colours");
Log.d(TAG, colours);
String items[] = colours.split(",");
for (String item : items) {
Log.d(TAG, item);
}
If you own the json
You should use JSONArray:
"colours": ["#fff600","#000000","#ffffff","#00000","#ff9900","#333333"]
And read it like
JSONObject json = ...;
JSONArray colorsArray = json.getJSONArray("colours");
for(int i = 0; i < colorsArray.length(); i++) {
String colorString = colorsArray.getString(i);
int color = Color.parseColor(colorString);
// you should probably also catch IllegalArgumentException for wrong input
}
If you don't own the json
You can read it as string and split around commas:
JSONObject json = ...;
String colorsString = json.getString("colours");
String[] colorStrings = colorsString.split(",");
for(String string : colorStrings) {
int color = Color.parseColor(string);
// you should probably also catch IllegalArgumentException for wrong input
}

load text from String array and set text to textview is very slow in big string array

hi
why load text from String array and set text to textview is very slow in big string array?
please help to me.
//get khotbe text from database and copy to khotbe activity
private void setkhotbetextarabicfarsi() {
this.sqliteDB = SQLiteDatabase.openOrCreateDatabase(this.getDatabasePath("aliname").getPath(), (SQLiteDatabase.CursorFactory) null);
Itemid = this.getIntent().getIntExtra("selectedFromListid", 1);
Cursor cursorLines = this.sqliteDB.rawQuery("SELECT * FROM khotbe where IDFehrest=" + this.Itemid , (String[]) null);
allrecs = cursorLines.getCount();
matn = new String[allrecs];
if (this.allrecs != 0) {
cursorLines.moveToFirst();
for (int i = 0; i < this.allrecs; ++i) {
String TextArabicOfKhotbe = cursorLines.getString(cursorLines.getColumnIndex("TextArabicOfKhotbe"));
int IDkhotbe = cursorLines.getInt(cursorLines.getColumnIndex("IDkhotbe"));
this.matn[i] = TextArabicOfKhotbe;
cursorLines.moveToNext();
}
}
and main code:
for(int var1 = 0; var1 < this.allrecs; ++var1) {
tvArabic = new JustifiedTextView(this);
tvArabic.setText(matn[var1]);
you are creating the textviews in loop that might making it slow.. try populating the array values using an adapter..
Also check the number of rows you are accessing from the DB. if they are huge in number, they would require more time to be fetched.
Use limit in that case.

How to store the values dynamically in string in java android?

In my project I need to store the values dynamically in a string and need to split that string with ",". How can I do that ? Please help me..
My Code:
static ArrayList<ArrayList<String>> listhere;
ArrayList<String> arropids;
String arropids1;
for(int q=0;q<listhere.size();q++)
{
arropids = listhere.get(q);
if(arropids.get(3).equals("1"))
{
arropids1 += arropids.get(0) + ",";
System.out.println("arropids1"+arropids1);
}
}
You must be getting NullPointerException as you havent initialized the String, initialize it as
String arropids1="";
It will resolve your issue, but I dont Recommend String for this task, as String is Immutable type, you can use StringBuffer for this purpose, so I recommend following code:
static ArrayList<ArrayList<String>> listhere;
ArrayList<String> arropids;
StringBuffer buffer=new StringBuffer();
for(int q=0;q<listhere.size();q++)
{
arropids = listhere.get(q);
if(arropids.get(3).equals("1"))
{
buffer.append(arropids.get(0));
buffer.append(",");
System.out.println("arropids1"+arropids1);
}
}
and finally get String from that buffer by:
String arropids1=buffer.toString();
In order to split the results after storing your parse in the for loop, you use the split method on your stored string and set that equal to a string array like this:
static ArrayList<ArrayList<String>> listhere;
ArrayList<String> arropids;
String arropids1 = "";
for(int q=0;q<listhere.size();q++) {
arropids = listhere.get(q);
if(arropids.get(3).equals("1"))
{
arropids1 += arropids.get(0) + ",";
System.out.println("arropids1"+arropids1);
}
}
String[] results = arropids1.split(",");
for (int i =0; i < results.length; i++) {
System.out.println(results[i]);
}
I hope that this is what you're looking for.

android sqlite indexof()

hi to all im reading this format from a file
BOOKNO= [1]
From= [ 2011-02-28 07:00:52]
To= [2011-03-17 07:01:02]
Link= [http://www.example.com]
SINCE= [5] days.
BOOKNO= [2]
From= [ 2011-03-01 17:55:15]
To= [2011-03-30 17:55:21]
Link= [http://www.something.com]
SINCE= [3] days.
and i need to insert what is between the brackets only into an sqlite database
and its not working .....!!
any suggestions on how to fix it or any other good ideas on how to read it and insert it to my database columns
NOTE: addressString has the information that needs to be inserted into the tabel and i have 5 columns BOOK,FROM,TO,LINK, and SINCE and when i read the file i get the information for all the books (more than 1 book)... thats why im using indexof() and for loop 'J' so i can insert 5 columns and loop to insert the next 5....
this is the code:
db.open();
long idx;
String lines[] = {addressString};
String fields[] = new String[lines.length];
for (int i = 0; i < lines.length; i++) {
for (int j=0; j<5; j++){
int be = lines[i].indexOf('[');
int e = lines[i].indexOf(']');
fields[i] = lines[i].substring(be+1, e);
idx = db.insertTitle(fields[0],fields[1],fields[2],fields[3],fields[4]);
}
}
hi to all again i've been playing around with my code and when i try to show the output on the screen with this code i get only number 1 on the screen it does not read all the text that is in address string
if (addressString != "didn't read titels"){
String lines[] = {addressString};
String fields[] = new String[lines.length];
for (int i = 0; i < lines.length; i++) {
int be = lines[i].indexOf('[');
int e = lines[i].indexOf(']');
fields[i] = lines[i].substring(be+1, e);
myLoutputText.setText(fields[i]);
}
db.insertTitle(...) should be outside the for loop (controlled by j).

Categories

Resources