I have multiple strings like st1, st2, st3, st4, st5, st6, st7. now i want to get that strings dynamically through for loop using its counter(in my case int i). like "st"+ i , but the android doesnot accept it so what should i do to get the string dynamically. for more info here is the chunk of the code
String image1 = cData.getString(cData.getColumnIndex("fld_image_url1"));
String image2 = cData.getString(cData.getColumnIndex("fld_image_url2"));
String image3 = cData.getString(cData.getColumnIndex("fld_image_url3"));
String image4 = cData.getString(cData.getColumnIndex("fld_image_url4"));
ArrayList<String> imagesArray = new ArrayList<String>();
//for adding the string in the arraylist dynamically
for(int i=1;i<=4;i++){
if("image"+i!=null){
imagesArray.add(String.valueOf("image"+ i));
}
}
How about something like:
List<String> imagesArray = new ArrayList<String>();
for (int i = 1; i <= 4; i++) {
String image = cData.getString(cData.getColumnIndex("fld_image_url" + i));
if (image != null) {
imagesArray.add(image);
}
}
if you want to get value from cursor dynamically then change your code as:
//for adding the string in the arraylist dynamically
for(int i=1;i<=4;i++){
int count = cData.getColumnIndex("fld_image_url"+i));
if(count != -1)
imagesArray.add(cData.getString(count));
}
Related
I parse json data successfully , i can show it on my recyclerView.
it's my data source:
(had solved the issue)
I want to set a search condition about month > 5
I had set a String.equal("compareString"); before, it worked.
But when i set the month in this case, it's not working.
do i set something wrong? any help will be grateful.
private void showRoute(String route) {
try {
JSONObject jsonObject = new JSONObject(route);
String arrayData = jsonObject.getString("JsonData");
JSONArray jsonArray = new JSONArray(arrayData);
Log.d(TAG, "JSONArray" + ">>>>>>>>>>" + jsonArray);
for (int i = 467; i < jsonArray.length(); i++) {
int month=5;//set search condition, i want to show a list , it's month > 5
//here is my search condition
if (Integer.parseInt(jsonArray.getJSONObject(i).getString("STARTMONTH"))>=month) {
String EDUTITLE = jsonArray.getJSONObject(i).getString("EDUTITLE");
String STARTMONTH = jsonArray.getJSONObject(i).getString("STARTMONTH");
String STARTDAY = jsonArray.getJSONObject(i).getString("STARTDAY");
String STARTDATE = jsonArray.getJSONObject(i).getString("STARTDATE");
String SPONSER = jsonArray.getJSONObject(i).getString("SPONSER");
String EDUSCORE = jsonArray.getJSONObject(i).getString("EDUSCORE");
String EDUIN = jsonArray.getJSONObject(i).getString("EDUIN");
String HOLDER = jsonArray.getJSONObject(i).getString("HOLDER");
ActivityListItem listItem = new ActivityListItem(EDUTITLE, STARTMONTH, STARTDAY, STARTDATE, SPONSER, EDUSCORE, EDUIN, HOLDER);
arrayList.add(listItem);
}else {
recyclerView.setVisibility(View.GONE);
textForEmpty.setVisibility(View.VISIBLE);
}
//arrayListOrigin.add(listItem);
}
} catch (JSONException ex) {
ex.printStackTrace();
}
}
and another question , if my data is 467~500 , my list will show 467~500 from up to down , what if i want to let it shows 500~467 from up to down , what should i do is more correct ?
I try some code like: it show empty
String month="5";
if (month.equals(jsonArray.getJSONObject(i).getString("STARTMONTH"))) {
other code...
}
but if i try to compare EDUIN like this: it works...
String eduin="0";
if (eduin.equals(jsonArray.getJSONObject(i).getString("EDUIN"))) {
other code...
}
i don't get it now :(
The issue is your if condition may not be executed because of this line
String arrayData = jsonObject.getString("JsonData");
In your response "JsonData" is a JSONArray not a String .
Try this instead.
JSONObject jsonObject = new JSONObject(route);
JSONArray jsonArray = jsonObject.getJSONArray("JsonData") ;
for (int i = 467; i < jsonArray.length(); i++) {
//rest of your code
}
Now if you want to item from 500 to 467 reverse the loop
for(int i = jsonArray.length()-1; i >= 467; i--){
if(Integer.parseInt(jsonArray.getJSONObject(i).getString("STARTMONTH"))>=month){
// rest of the code..
}}
outside the loop hide recycleview like this
if (arrayList.size() == 0) {
//hide recycleview
recyclerView.setVisibility(View.GONE);
textForEmpty.setVisibility(View.VISIBLE);
}
Or
Much more easier way
ArrayList<Element> tempElements = new ArrayList<Element>(arrayList);
Collections.reverse(tempElements);
int size = mcq.size();
String arr[] = null;
int i;
{
for (i = 0; i < size; i++) {
if (op1.isPressed()) {
arr[i] = tv1.getText().toString();
// Log.e("Array",arr[i]);
} else if (op2.isPressed()) {
arr[i] = tv2.getText().toString();
//Log.e("Array",arr[i]);
} else if (op3.isPressed()) {
arr[i] = tv3.getText().toString();
// Log.e("Array",arr[i]);
} else if (op4.isPressed()) {
arr[i] = tv4.getText().toString();
//Log.e("Array",arr[i]);
}
I am trying to store the data in an array when the button is pressed,but it always shows null.And when the for loop is over I want to display my array.
here , Arrays in Java have a size so u cannot do like this. Instead of this
use list,
ArrayList<String> arr = new ArrayList<String>();
Inorder to do using String array :
String[] arr = new String[SIZEDEFNE HERE];
For ur answer :
ArrayList<String> arr = new ArrayList<String>();
int i;
{
for (i = 0; i < size; i++) {
if (op1.isPressed()) {
arr.add(tv1.getText().toString());
} else if (op2.isPressed()) {
arr.add(tv2.getText().toString());
} else if (op3.isPressed()) {
arr.add(tv3.getText().toString());
} else if (op4.isPressed()) {
arr.add(tv4.getText().toString());
}
Retrive value using
String s = arr.get(0);
This is because your string array is null. Declare it with the size as
String[] arr = new String[size];
Try Array List. use the following code in your main java
final ArrayList<String> list = new ArrayList<String>();
Button button= (Button) findViewById(R.id.buttonId);
final EditText editText = (EditText) findViewById(R.id.editTextId)
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
list.add(editText.getText().toString());
}
});
To avoid duplication in arraylist .You can use arraylist for faster then String array
ArrayList<String> list = new ArrayList<String>();
list.add("Krishna");
list.add("Krishna");
list.add("Kishan");
list.add("Krishn");
list.add("Aryan");
list.add("Harm");
System.out.println("List"+list);
HashSet hs = new HashSet();
hs.addAll(list);
list.clear();
list.addAll(hs);
I am using this -> http://www.ezzylearning.com/tutorial.aspx?tid=1763429 to create my own custom listview.
For my project, I am using while loop to get data and getting data back.
The original code is :
DownloadClass data[] = new DownloadClass[] {
new DownloadClass("test", "test"),
new DownloadClass("test", "Sunny")
};
However for my case..
DownloadClass data[] = new DownloadClass[] {};
SQLFunctions entry = new SQLFunctions(this);
entry.open();
highestID = entry.getHighestId();
for (int l = 1; l < highestID; l++) {
Long longVal = Long.valueOf(l);
new DownloadClass(entry.getName(longVal).toString(), entry.getURL(longVal).toString());
}
The listview appears to be empty because I know the data is not inserted. Any help is appreciated. Thanks.
EDIT :
my DownloadClass :
public class DownloadClass {
public String name;
public String url;
public DownloadClass(){
super();
}
public DownloadClass(String name, String url) {
super();
this.name = name;
this.url = url;
}
}
My new Activity
DownloadClass data[] = new DownloadClass[]; // need to work on this
SQLFunctions entry = new SQLFunctions(this);
entry.open();
highestID = entry.getHighestId();
Log.e("HIGHEST ID", highestID.toString());
if (highestID > 1) {
for (int l = 0; l < highestID; l++) {
Long longVal = Long.valueOf(l);
//String name = entry.getName(longVal);
//String id = entry.getURL(longVal);
//Log.e("NAME", name + " - " + id);
data[l] = new DownloadClass(entry.getName(longVal).toString(),entry.getURL(longVal).toString());
}
}
entry.close();
You're not ever adding your new DownloadClass object to your array. You also need to allocate size if you're going to use an array instead of an ArrayList (which to be honest is probably what you want).
As you iterate through the loop you need to assign the new object to a position in the array.
data[i] = new DownloadClass(...);
Try this and let me know what happen..
DownloadClass data[];
SQLFunctions entry = new SQLFunctions(this);
entry.open();
highestID = entry.getHighestId();
data[] = new DownloadClass[highestID];
for (int l = 0; l < highestID; l++) {
Long longVal = Long.valueOf(l);
data[i] = new DownloadClass(entry.getName(longVal).toString(), entry.getURL(longVal).toString());
}
Also start your loop with 0 index.. instead of 1..
Update:
First of all you are dynamically creating array of object. SO you have to know the size of array.
Second your loop is start with index 1, it should be 0.
This code is giving an error saying "error receiving broadcast intent in activity"
I cant find any eroors though...........any ideas ?
i've added the loop condition as seven as i only want the first seven scan results
class WifiReceiver extends BroadcastReceiver {
public void onReceive(Context con, Intent intent) {
sb = new StringBuilder();
wifiList = mainWifi.getScanResults();
for(int i = 0; i < wifiList.size(); i++)
{
sb.append((wifiList.get(i)).SSID.toString());
sb.append(' ');
sb.append('!');
sb.append("\n\n");
}
String net = sb.toString();
if(wifiList.size() > 0)
{
char excl = '!';
int excl1 = excl;
String[] aray = null;
for(int j = 0; j<7; j++)
{
int index = net.indexOf(excl1);
String a = net.substring(0, index);
aray[j] = a;
String temp = net.substring(index+1);
net = temp;
}
String one = aray[0];
String two = aray[1];
String three = aray[2];
String four = aray[3];
String five = aray[4];
String six = aray[5];
String seven = aray[7];
tv1.setText(one);
}
else
{
tv1.setText("No Networks Detected");
}
}
}
PS : I've only added into one TextView as this is a test module
The "aray" array is not being intialized correctly. You need to initialize "aray" before accessing it:
String[] aray = new String[7];
You are also going outside the dimensions of the array. this:
String seven = aray[7];
should be:
String seven = aray[6];
An even better solution would be to use an ArrayList.
ArrayList al = new ArrayList();
al.add(yourString);
I'm using XML to store a database of phrases where 5 of these phrases will be displayed to the user at a time. I need to ensure these 5 phrases are unique and, of course, just getting random data can't ensure that. I think I could do it if I could convert the string array that I'm using into a List, but I can't find good info on how to do that. Does anyone have any input on this?
public String getResults(){
// Get a random string from our results XML and return the string.
Resources r = getResources();
String[] resultsList = r.getStringArray(R.array.bossResults);
List<String> resultsArrayList = new ArrayList<String>(Arrays.asList(resultsList));
//ArrayList resultsArrayList = ;
String q = resultsList[rgenerator.nextInt(resultsList.length)];
return q;
//resultsList.remove(q);
}
private OnClickListener mAddListener = new OnClickListener()
{
public void onClick(View v)
{
//Declare our TextViews for population from the random results from XML
TextView t1 = new TextView(getApplicationContext());
t1=(TextView)findViewById(R.id.textView1);
TextView t2 = new TextView(getApplicationContext());
t2=(TextView)findViewById(R.id.textView2);
TextView t3 = new TextView(getApplicationContext());
t3=(TextView)findViewById(R.id.textView3);
TextView t4 = new TextView(getApplicationContext());
t4=(TextView)findViewById(R.id.textView4);
TextView t5 = new TextView(getApplicationContext());
t5=(TextView)findViewById(R.id.textView5);
// Get a random result for each textview
String result1 = getResults();
String result2 = getResults();
String result3 = getResults();
String result4 = getResults();
String result5 = getResults();
}
}
The easiest way is probably to rewrite getResults() to return all the strings you need (and additionally not load the "bossResults" array 5 times).
public List<String> getResults(int count){
// Get a random string from our results XML and return the string.
List<String> ret = new ArrayList<String>();
Resources r = getResources();
List<Integer> picked = new List<Integer>();
String[] resultsList = r.getStringArray(R.array.bossResults);
while (ret.size() < count) {
int i = rgenerator.nextInt(resultsList.length);
if (picked.contains(i)) { continue; }
picked.add(i);
ret.add(resultsList[i]);
}
return ret;
}
It might be slow for large values of count.
EDIT: It falls into an infinite loop if count is greater than the size of the array!
The easiest way is to remember which items you already selected and if you select one of them again, just discard it. This could be very slow, if the count of items to choose from is low. If that was the case, you could shuffle the whole array and return first n items.
I would make a change to getResults() to do all the work for you in one pass. This way it could remember what values have already been chosen, and shrink the values it then chooses from in the future....something like this:
public List<String> getResults(int count) {
List<String> results = new ArrayList<String>();
Resources r = getResources();
String[] resultsList = r.getStringArray(R.array.bossResults);
List<String> resultsArrayList = new ArrayList<String>(Arrays.asList(resultsList));
for(int i = 0; i < count; ++i) {
int next = rgenerator.nextInt(resultsArrayList.size());
String nextVal = resultsArrayList.remove(next);
results.add(nextVal);
}
return results;
}