This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
i spend hole day on looking what is going on. In one class I've got simple listview with multiple choice. At the end each choice is put to String array and share to next class.
SparseBooleanArray checked = listView.getCheckedItemPositions();
ArrayList<String> selectedItems = new ArrayList<String>();
for (int i = 0; i < checked.size(); i++) {
// Item position in adapter
int position = checked.keyAt(i);
// Add sport if it is checked i.e.) == TRUE!
if (checked.valueAt(i))
selectedItems.add(adapter.getItem(position));
}
String[] outputStrArr = new String[selectedItems.size()];
for (int i = 0; i < selectedItems.size(); i++) {
outputStrArr[i] = selectedItems.get(i);
}
Intent intent = new Intent(getApplicationContext(),
ReadComments.class);
// Create a bundle object
Bundle b = new Bundle();
b.putStringArray("selectedItems", outputStrArr);
// Add the bundle to the intent.
intent.putExtras(b);
// start the ResultActivity
startActivity(intent);
In ReadComments class i've made simple method:
public String[] tablica(){
Bundle b = getIntent().getExtras();
String[] resultArr = b.getStringArray("selectedItems");
return resultArr;
}
which bring back my data. When I put it to another method in the same class:
String resultArr[] = tablica();
int x = 0;
for (Map<String, String> mListaMar : mListaMarketow) {
lat = mListaMar.get(TAG_SZER);
longi = mListaMar.get(TAG_DLUG);
name = mListaMar.get(TAG_MARKET);
x=0;
for (x = 0; x < resultArr.length; x++) {
if (resultArr[x] == name) {
ustawMape();
}}}
UstawMape() method is responsible for show marker on google map. My problem is a logical problem because everything is working fine but ustawMape() method should show many markers and right now it show only one (construcion of ustawMape() is ok because without for loop it's work ok). The clue is very simple first loop for bring data from JSON and the second one should filter and show only this which user choose in listView. PLZ help my somebody!!
if (resultArr[x] == name)
Use equals() for string comparisons instead of ==:
if (name.equals(resultArr[x]))
== compares object references which won't be the same unless the strings are interned. equals() compares the string values.
Related
I created a loop that will get the data from my cursor, however I noticed that even though it is looping(with the correct count) it only shows the first value.
int vv = 0;
if ((CR3.moveToFirst()) || CR3.getCount() !=0){
while (CR3.isAfterLast() == false) {
vendoName[vv] = CR3.getString(0);
vendoEsch[vv] = CR3.getString(1);
vendoAsch[vv] = CR3.getString(2);
vendoTag[vv] = CR3.getString(3);
vv++;
CR3.moveToNext();
}}
and when I call all my data( I only need the first three records)
ArrayList<SearchResults2> results2 = new ArrayList<SearchResults2>();
SearchResults2 sr2 = new SearchResults2();
for(int j = 0;j < 3;j++)
{
sr2.setName(vendoName[j]);
sr2.setEsch(vendoEsch[j]);
sr2.setAsch(vendoAsch[j]);
sr2.setTag(vendoTag[j]);
results2.add(sr2);
}
I am putting inside a listview, when I check, it is showing always the first data.
This is an example I used as a reference to my code(It's almost the same except that I used an array to put my data from)
http://geekswithblogs.net/bosuch/archive/2011/01/31/android---create-a-custom-multi-line-listview-bound-to-an.aspx
Am I doing something wrong which is why it is only getting the first piece of data?
Is it not easier to do something like this (if you don't need more than 3 results):
ArrayList<SearchResults2> results2 = new ArrayList<SearchResults2>();
CR3.moveToFirst();
for (i = 0; i < 3; i++) {
SearchResults2 sr2 = new SearchResults2();
sr2.setName(CR3.getString(0));
sr2.setEsch(CR3.getString(1));
sr2.setAsch(CR3.getString(2));
sr2.setTag(CR3.getString(3));
results2.add(sr2);
CR3.moveToNext();
}
I think that maybe the cursor doesn't iterate properly through your results in your while-loop and that's why you become one and the same result for the three items
Data is not binding in array list as it came from the Service, as like first option which added in ArrayList is Lead, second is Qualified, and third is test. When i check list on first position it shows Qualified, Lead, test. But i want as i bind my list as it show in that sequence.
public static HashMap<String,ArrayList<LeadData>> LeadDataMap= new HashMap<String,ArrayList<LeadData>>();
public static ArrayList<String> aList = new ArrayList<String>();
for (int i = 0; i < LeadListsJSONArray.length(); i++) {
JSONObject Leadsobj = LeadListsJSONArray.getJSONObject(i);
//get stage name for hashmap key value..
String StageNameString = Leadsobj.getString("StageName");
String StageIdString = Leadsobj.getString("StageId");
System.out.println("stage id........................"+StageIdString);
//get new leads list..
JSONArray jaarr2 = new JSONArray(Leadsobj.getString("Leads"));
ArrayList<LeadData> leadDataList = new ArrayList<LeadData>();
for (int j = 0; j < jaarr2.length(); j++) {
LeadData ld = new LeadData();
JSONObject obj3 = jaarr2.getJSONObject(j);
ld.setLeadCompanyName(obj3.getString("LeadCompanyName"));
ld.setLeadId(obj3.getString("LeadId"));
ld.setTitle(obj3.getString("Title"));
leadDataList.add(ld);
}
//here we are puttin the leaddatalist inot map with respect to stage name...
LeadDataMap.put(StageNameString.trim().toString(), leadDataList);
//LeadDataMap.put(StageIdString, leadDataList);
}
In LeadDataMap data in not in that sequence in that i have put. This is the problem.
I get solution by using LinkedHashmap.
I have:
a String array with an unknown length that's populated with unknown items (let's say fish, bird, cat)
an ArrayAdapter and a Spinner that displays the items
a variable that contains one unknown item from the string array (let's say cat)
I want to set the Spinner to the value from the variable (cat). What's the most elegant solution? I thought about running the string through a loop and comparing the items with the variable (until I hit cat in this example), then use that iteration's # to set the selection of the Spinner, but that seems very convoluted.
Or should I just ditch the Spinner? I looked around and found a solution that uses a button and dialog field: https://stackoverflow.com/a/5790662/1928813
//EDIT: My current code. I want to use "cow" without having to go through the loop, if possible!
final Spinner bSpinner = (Spinner) findViewById(R.id.spinner1);
String[] animals = new String[] { "cat", "bird", "cow", "dog" };
String animal = "cow";
int spinnerpos;
final ArrayAdapter<String> animaladapter = new ArrayAdapter<String>(
this, android.R.layout.simple_spinner_item, animals);
animaladapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
bSpinner.setAdapter(animaladapter);
for (Integer j = 0; j < animals.length; j++) {
if (animals[j].equals(animal)) {
spinnerpos = j;
bSpinner.setSelection(spinnerpos);
} else {
};
}
(Temporarily) convert your String array to a List so you can use indexOf.
int position = Arrays.asList(array).indexOf(randomVariable);
spinner.setSelection(position);
EDIT:
I understand your problem now. If your String array contains all unique values, you can put them in a HashMap for O(1) retrieval:
HashMap<String, Integer> map = new HashMap<String, Integer>();
for (int i = 0; i < animals.length; i++) {
map.put(animals[i], i);
}
String randomAnimal = "cow";
Integer position = map.get(randomAnimal);
if (position != null) bSpinner.setSelection(position);
This question already has answers here:
How to get a resource id with a known resource name?
(10 answers)
Closed 8 years ago.
Is there a way to change a reference to an ID in the Android manifest using a variable?
As in:
for(int counter6=1;counter6 <= 12; counter6++)
value = bundle.getString("value"+counter6);
TextView text1 = (TextView) findViewById(R.id.textView+counter6);
text1.setText(value);
Is it possible to have the counter6 variable used in the ID directory, so the for loop can loops through all the different text view making each one text1 respectively then setting their text to the string value?
Its not really a problem if it cant work this way it just means more lines of code to write.
You can't really make a loop on the id and increment it as it is generated but you can make an array of references and by getting that array find each TextView and update the text:
<array name="array_text_views">
<item>#id/text_view_1</item>
<item>#id/text_view_2</item>
<item>#id/text_view_3</item>
<array>
In your code, something like that:
ArrayList<TextView> myTextViews = new ArrayList<TextView>();
TypedArray ar = context.getResources().obtainTypedArray(R.array.array_text_views);
int len = ar.length();
for (int i = 0; i < len; i++){
myTextViews.add(findById(ar[i]));
}
ar.recycle();
I would usually just put a small int[] array of Ids into the code somewhere. If you have a lot of them, consider creating them programmatically (layout.addView(new TextView(..).
For example if you want to start an Activity and tell it what strings to display via the Extras Bundle you can put them directly as an array.
void startOther(String[] texts) {
Intent i = new Intent( /* ... */);
i.putExtra("texts", texts);
// start via intent
}
Now inside that Activity I would put the ids as a "constant".
// hardcoded array of R.ids
private static final int[] TEXT_IDS = {
R.id.text1,
R.id.text2,
// ...
};
And then use both the Bundle and the id Array for example like this:
// a List of TextViews used within this Activity instance
private List<TextView> mTextViews = new ArrayList<TextView>(TEXT_IDS.length);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.something);
// find all TextViews & add them to the List
for (int id : TEXT_IDS) {
mTextViews.add((TextView)findViewById(id));
}
// set their values based on Bundle
String[] stringArray = savedInstanceState.getStringArray("texts");
for (int i = 0; i < mTextViews.size() && i < stringArray.length; i++) {
mTextViews.get(i).setText(stringArray[i]);
}
}
ok so i create an array that has integers. The array displays five number from the min and max. How can i display all five numbers in a textview or edittext ? I tried:
nameofile.setText(al.get(x).toString());
but it only displays one?
ArrayList<Integer> al = new ArrayList<Integer>();
for (int i = minint; i <= maxint; i++)
al.add(i);
Random ran = new Random();
for (int i = 0; i < 5; i++) {
int x = al.remove(ran.nextInt(al.size()));
String myString = TextUtils.join(", ", al);
lottonumbers.setText(myString);
ArrayList<Integer> al = new ArrayList<Integer>();
al.add(0);
al.add(1);
al.add(5);
al.add(4);
al.add(3);
java.util.Collections.sort(al);//for sorting Integer values
String listString = "";
for (int s : al)
{
listString += s + " ";
}
nameofile.setText(listString);
You're currently only printing out one element (the one at index x). If you want to print them all in order, you can just join them using TextUtils.join().
Update: After seeing your edit, I think there's a better way to go about what you're trying to do. Instead of trying to pull the values one at a time, and update the list, why not just shuffle them, then use the above method?
Update 2: Okay, I think I finally understand your problem. Just a simple change, then.
ArrayList<Integer> al = new ArrayList<Integer>();
for (int i = minint; i <= maxint; i++)
al.add(i);
Random ran = new Random();
StringBuilder text = new StringBuilder(); // Create a builder
for (int i = 0; i < 5; i++) {
int x = al.remove(ran.nextInt(al.size()));
if (i > 0)
text.append(", "); // Add a comma if we're not at the start
text.append(x);
}
lottonumbers.setText(text);
al.get(x).toString() will only get the value at index "x". If you want to display all values, you need to combine all of the values from the array into a single string then use setText on that string.
You are only showing one number of your array in the TextView, you must to concat the numbers to see the others results like:
for(Integer integer : al) {
nameofile.setText(nameofile.getText() + " " + al.get(x).toString());
}
Then i think you can show all number in one String.