when I am carrying out a search operation after fetching the contacts,it shows this exception when I type the letters very fast in the search bar and the application crashes.Could you please help me out to resolve this issue.I am including the portion of the code also along
#Override
public boolean onQueryTextChange(String newtext) {
String searchString = newtext;
int textLength = searchString.length();
ArrayList<Masterlistmodel> type_name_filter = new ArrayList<Masterlistmodel>();
/* String text = edtField.getText().toString(); */
for (int i = 0; i <masterarr.size(); i++) {
String Name = masterarr.get(i).getName();
if (searchString.equalsIgnoreCase(Name.substring(0,
textLength))) {
type_name_filter.add(masterarr.get(i));
}
}
type_name_copy = type_name_filter;
listUpdate(type_name_copy);
return true;
}
#Override
public boolean onQueryTextSubmit(String arg0) {
// TODO Auto-generated method stub
return false;
}
First thing I'd point out is that we don't know what kind of object is masterarr, So I'll guess is like an ArrayList.
I'd try not to use the .size() but the .length() method, size is related to capacity and length is related to the amount of items actually in the array.
Also, as #rsinha said, I think a possible mistake is when you try to execute the equalsIgnoreCase method and the Name variable in that iteration has a lenght shorter than the lenght of the String typed by the user, so I would try:
for (int i = 0; i <masterarr.size(); i++) {
String Name = masterarr.get(i).getName();
if (searchString.equalsIgnoreCase(Name.substring(0,
Math.min(textLength,Name.length())))) {
type_name_filter.add(masterarr.get(i));
}
}
Try first using .length() and if does not work, try the changes in the for loop. I see no more in your code I could help with.
You get IndexOutOfBoundsException when you want to access an array index which is out of range. For example:
String[] myArray = new String[10];
myArray[10] = "test"; // 10 is out of limits(0-9)
Would produce such an exception.
with this:
ArrayList<String> result= new ArrayList<String>();
Then you can add elements to this list with the following:
// result[i] = trax.substring(s1+4,s2);
result.add(trax.substring(s1+4,s2));
It will work for you and it will remove this exception.
'textLength' is length of the search string entered by user. An entry of this length may not be in your master list 'masterarr'. You may try:
String Name = masterarr.get(i).getName();
if (Name.startsWith(searchString)) {
type_name_filter.add(masterarr.get(i));
}
Add the first statement in the method "onQueryTextChange"
if(newtext==null) return true;
Then try
Related
code gets two user inputs from user and compares inputs to a database and prints out d corresponding data from the database.how do i add code to check for empty fields?
protected void onPostExecute(Void v) {
try {
boolean available=false;
JSONArray Jarray = new JSONArray(result);
for(int i=0;i<Jarray.length();i++) {
JSONObject Jasonobject = null;
//text_1 = (TextView)findViewById(R.id.txt1);
Jasonobject = Jarray.getJSONObject(i);
//get an output on the screen
//String id = Jasonobject.getString("id");
String name = Jasonobject.getString("name");
String name1 = Jasonobject.getString("name1");
String db_detail = "";
if (et.getText().toString().equalsIgnoreCase(name) && et1.getText().toString().equalsIgnoreCase(name1)||et.getText().toString().equalsIgnoreCase(name1) && et1.getText().toString().equalsIgnoreCase(name)) {
db_detail = Jasonobject.getString("detail");
text.setText(db_detail);
available = true;
break;
}
}
if(!available)
Toast.makeText(MainActivity.this, "Not available", Toast.LENGTH_LONG).show();
this.progressDialog.dismiss();
}
Use TextUtils.isEmpty(charactersequence)
if(!TextUtils.isEmpty(et.getText().toString().equalsIgnoreCase(name)))
{
}
Docs :
public static boolean isEmpty (CharSequence str)
Added in API level 1
Returns true if the string is null or 0-length.
Parameters
str the string to be examined
Returns
true if str is null or zero length
Also better to use optString
Jasonobject.optString("name");
You can use String.isEmpty() method which checks whether the length of the String is 0.
You can also try on String.matches().
Using equalsIgnoreCase("") performs an actual string comparison. This method returns true if the argument is not null and the Strings are equal, ignoring case; false otherwise.
So you may check using isEmpty() or matches("") method to check empty values and then do the comparison.
suppose your string you received is as below,
String nameString = jsonObj.getString("name");
you can check if its empty by using following check.
if(nameString.equals(""))
I am trying to save some values in a arraylist but somehow they all get overwritten ending up with only 1 value in the arraylist (200).
final String[] titles = new String[urls.length];
for (int i = 0; i < titles.length; i++){
ArrayList<Integer> valuesList = new ArrayList<Integer>();
valuesList.add(page.getTopicCount()); // returns 4 values (50,100,150,200)
System.out.println("Element: " + valuesList.toString());
// returns only value 200
}
The code page.getTopicCount() returns the 4 values in 1 line (50 100 150 200) only the last one (200) gets added to the arraylist but i am trying to find a way to save them all 4 seperately.
What options do i have? (SharedPreferences, saving to file, do i have to build another loop)?
I already did some research and ended up on this page but i don`t know if this will work.
Ps: the 4 values are constantly changing, thus it is no option to add them as:
valuesList.add("50");
valuesList.add("100");
etc..
Edit:
getTopicCount is part of a Saxparser class, see below code snippet:
public void endElement(final String uri, final String localName, final String qName)
throws SAXException {
//
} else if (localName.equals("topiccount")) {
in_topiccount = true;
sb = new StringBuilder();
}
//
else if (localName.equals("topiccount")) {
in_topiccount = false;
forumPage.setTopicCount(Integer.parseInt(sb.toString())); //returns 50 100 150 200
sb = null;
}
//
}
Inside the for loop, you are initializing the valuesList ArrayList. So each iteration, you create a new ArrayList and add one element to it and then discard it. As a result, at the end you only have a reference to the last ArrayList you created, which can only have 200 in it.
Presumably what you want to do is something like:
ArrayList<Integer> valuesList = new ArrayList<Integer>();
for (int i = 0; i < titles.length; i++){
valuesList.add(page.getTopicCount()); // returns 4 values (50,100,150,200)
}
System.out.println("Element: " + valuesList.toString());
Edit: Essentially, create the ArrayList once, and then insert elements into it in the for loop.
I am using a database to show random message at the push of a button.
Every time the button is pushed, a random number is generated and displays a message that corresponds to that number.
Of course, the same message can appear twice as the same number can be generated twice.
So I am creating a string, and I am concatenating each number when the button is pushed.
If the new random number is in the String, then I want to get another number. If that number is in that String, I want to get another number etc etc (Regression?).
I also want to have a global count that I can change, so if the String reaches a size of 9 numbers, it will be reset to "".
String randomList; //global
final int MAX_STRING_LENGTH = 9;
Integer randomNumber = getRandomMessage(messages.size());
if(randomList.length() > 0)
{
if(!randoms.contains(randomNumber.toString()))
{
messageText.setText(messages.get(randomNumber));
}
}
Create a boolean Array of 9 elements
boolean[] check = new boolean[9];
Everytime you use a number, set check[number] to true
void useNumber(int number){
check[number] = true;
}
To check if you already used this number
boolean checkNumber(int number){
return check[number];
}
To reset check
void resetCheck(){
for(int i = 0; i < check.length; i++) check[i] = false;
}
Edit:
Get a string for a given number, resetCheck if necessary;
String getString(int number){
if(usedString == check.length){
resetCheck();
usedString = 0;
}
if(checkNumber(number)){
return getString(getRandomNumber());
}else{
usedString++;
return strings[number];
}
}
I think you can better use a boolean array. You can store the boolean array with the SharedPreferences class. A boolean array is more flexible and you can retrieve the values in constant time. You can also easily make it larger when you have more random messages.
Do a simple trick Hope this works for you
buttonRandom.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Collections.shuffle(messages);
messageText.setText(messages.get(0));
}
});
I'm working on code that takes two arrays with strings (the strings are just sentences) and allocates them to classes which are held in another array (The Sentence class array shown below in the code).
So here's my problem. When popList() is called, the for loop runs through twice and works fine, putting the first index of addStrings and addTranslation into the first class in the array. However, when the loop indexes up and runs temp.sentence = addStrings[1] again, it OVERRIDES the first class's .sentence also. Then when temp.translations = addTranslations[1] runs again it OVERRIDES the first class's .translation.
So by the end of the loop, all of the arrays are filled with the same thing: the last index of addStrings and addTranslation. Every time it loops it overwrites all the indices before it with the index it's supposed to be putting in.
Anyone know what the problem is here? Thanks!
public class Sentence {
public String sentence;
public String translation;
Sentence() {
sentence = " ";
translation = " ";
}
}
private void popStrings() {
addStrings[0] = "我是你的朋友。"; addTranslations[0] = "I am your friend.";
addStrings[1] = "你可以帮助我吗?"; addTranslations[1] = "Could you help me?";
addStrings[2] = "我不想吃啊!"; addTranslations[2] = "I don't want to eat!";
}
//Fill Sentence array with string and translation arrays
private void popList() {
int i = 0;
Sentence temp = new Sentence();
for(i = 0; i < addStrings.length && i < addTranslations.length ; i++) {
temp.sentence = addStrings[i];
temp.translation = addTranslations[i];
sentences[i] = temp;
}
}
You need to create new Sentence() inside the loop:
for(i = 0; i < addStrings.length && i < addTranslations.length ; i++) {
Sentence temp = new Sentence();
temp.sentence = addStrings[i];
temp.translation = addTranslations[i];
sentences[i] = temp;
}
Otherwise you set sentence and translation continuously in the same object.
When parsing the SoapObject data into a String[], the empty fields in the response from the webservice do not get added to it and I can't identify the empty propeties by checking for null or "".
So my problem is basically: The SoapObject contains the right amount of properties, but the parsed result (String[]) does not contain the ones that are empty, nor can I check for empty properties and add "" to the String[].
This causes problems for me when saving to the SQLite DB since every e.g. "User" contains a different amount of fields.
public static String[] getStringArrayResponse(SoapObject node, Vector<String> strings) {
boolean isFirstCall = false;
if (strings == null) {
isFirstCall = true;
strings = new Vector<String>();
}
int count = node.getPropertyCount();
for (int i = 0; i < count; i++) {
Object obj1 = node.getProperty(i);
if (obj1 instanceof SoapObject) {
if (((SoapObject)obj1).getPropertyCount() > 0) {
// Returns the correct amount of properties
Log.d("PARSER", "propertycount = " +((SoapObject)obj1).getPropertyCount());
getStringArrayResponse((SoapObject)obj1, strings);
}
} else if (obj1 instanceof SoapPrimitive) {
strings.add(((SoapPrimitive)obj1).toString());
}
}
if (isFirstCall) {
return (String[])strings.toArray(new String[strings.size()]);
}
return null;
}
This is really giving me a headache and I'm grateful for any help I can get :)
I needed to check for "AnyType{}" :)
if (obj1.toString().equals("anyType{}")){
strings.add("");
}
Just added this block of code below the else if.