Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I have one problem in code regarding Arraylist. I have two methods one method works with server to get data and inside this method i'm adding data to ArrayList. Second method is getter that will return Arraylist. But when I display data with using Log.d() inside first method ArrayList has data. But when i try call second method ArrayList is empty. Help me!!! Thank you in advance!!!
Below shows piece of code first method that will fetch data from server
try {
JSONArray jsonArray= new JSONArray(response);
for(int i=0; i<jsonArray.length(); ++i)
{
ordersLists.setId(jsonArray.getJSONObject(i).getString("id"));
ordersLists.setMain_cat(jsonArray.getJSONObject(i).getString("main_cat"));
ordersLists.setSub_cat(jsonArray.getJSONObject(i).getString("sub_cat"));
ordersLists.setDate(jsonArray.getJSONObject(i).getString("date"));
ordersLists.setPrice(jsonArray.getJSONObject(i).getInt("price"));
ordersLists.setComment(jsonArray.getJSONObject(i).getString("comment"));
ordersLists.setCity(jsonArray.getJSONObject(i).getInt("city"));
arrayList.add(ordersLists);
}
Second method is getter.
public ArrayList<OrdersLists> getArrayList()
{
return arrayList;
}
From what I understood from your question , I think the solution is to replace this line if your first method from
arrayList.add(ordersLists);
to
the name of your object that has the arrayList .setArrayList(ordersLists);
where the setter method setArrayList in this form below :
public void setArrayList(ArrayList<String> arrayList)
{
this.arrayList= arrayList;
}
https://www.codejava.net/coding/java-getter-and-setter-tutorial-from-basics-to-best-practices
Let me know if that helped!
In your code, you initialize i = 0 then try to make a decrement.
But I think that you can't have an index below zero.
for(int i = 0; i < jsonArray.length(); ++i) {
}
Try this instead:
for(int i = 0; i < jsonArray.length(); i++){
}
try this
JSONArray jsonArray= new JSONArray(response);
for(int i=0; i<jsonArray.length(); i++)
{
ordersLists = new OrdersLists();
ordersLists.setId(jsonArray.getJSONObject(i).getString("id"));
ordersLists.setMain_cat(jsonArray.getJSONObject(i).getString("main_cat"));
ordersLists.setSub_cat(jsonArray.getJSONObject(i).getString("sub_cat"));
ordersLists.setDate(jsonArray.getJSONObject(i).getString("date"));
ordersLists.setPrice(jsonArray.getJSONObject(i).getInt("price"));
ordersLists.setComment(jsonArray.getJSONObject(i).getString("comment"));
ordersLists.setCity(jsonArray.getJSONObject(i).getInt("city"));
arrayList.add(ordersLists);
}
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
is there a way to say that if you reach the null reference, then do something ?
e.g. if i have a linkedlist with just one object and after this comparison, if you reached null then do something...
for(int i = 0; i < queue.size(); i++) {
if (queue.get(i).compareTo(newitem) == -1) {
continue;
}
}
for instance another if-clause in the loop saying
if (queue.equals(null)) {
queue.add(newitem);
}
this is btw the linkedlist
public OrderedQueue() {
queue = new LinkedList<T>(); // generate an empty queue
}
You can always check that the object in your list is null to do a special operation:
for(Element e : queue) {
if(e == null) {
// special operation
} else {
// normal operation
}
}
Also use a for-each loop to iterate over elements.
In your case, using the get(i) method is not very efficient on a LinkedList. Using a for each allows you to abstract the actual type of the Iterable you are iterating over.
Replace everything with:
if (!queue.contains(newItem)) {
queue.add(newItem);
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I am attempting to use an arraylist inside of a hashmap to create and iterate counters for different characters fed to the processLine method. I think I have declared all of the variables and the catch statements should handle the cases in which there isn't an entry in the hashmap, but I am still getting a NullPointerException on the curCounts.set(i, 1); line in the second catch statement. I've probably made some dumb mistake, but I can't figure out what it is.
HashMap<Character, ArrayList<Integer>> charCounts;
public DigitCount() { charCounts = new HashMap<>(); }
public void processLine (String curLine) {
int length = curLine.length();
char curChar;
ArrayList<Integer> curCounts;
Integer curCount;
for(int i = 0; i < length; i++){
curChar = curLine.charAt(i);
try {
curCounts = charCounts.get(i);
} catch (NullPointerException ex) {
curCounts = new ArrayList<>();
}
try {
curCount = curCounts.get(i);
curCount++;
curCounts.set(i, curCount);
} catch (NullPointerException ex) {
curCounts.set(i, 1);
}
charCounts.put(curChar, curCounts);
}
linesProcessed++;
System.out.println("---------------------------" + linesProcessed);
}
Edit: Yes, I did call DigitCount.
public static void main(String args[]) throws Exception
{
//creates an instance of the digitCount object and starts the run method
DigitCount counter = new DigitCount();
counter.run(args[0]);
}
if charConts doesn't contain i (as in charCounts.get(i)), then it won't throw a NullPointerException, it will return null. Therefore you should be using an if and not a trycatch as in:
curCounts = charCounts.get(i);
if(curCounts==null)
curCounts = new ArrayList<>();
Edit: Alternatively if you are using java 8 you can do
curCounts = charCounts.getOrDefault(i,new ArrayList<Integer>());
and it will automatically default to creating a new ArrayList if it doesn't contain one
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Hello my problem is that
DepositoBancario(String s){
String[]v = s.split("[ :]");
Integer n= v.length;
if(n!=2) throw new IllegalArgumentException("Error"+s);
banco= new String(v[0]);
interes= new List(v[1]);
}
This constructor is for be able to build and object by a file and I want transform the element v[1] in List(interes).
Thanks for your help guys.
You don't need to create a String with new String("") you can just set banco = v[0]
List is an Interface and can not be instantiated via a constructor. What you need is a ArrayList for example. But this class doesn't have a Constructor for a Strign neither. What is in that String v[1]?
I believe you have one or more elements (interes) and you wants to convert them into list of elements. You can use something like this.
import java.util.ArrayList;
import java.util.List;
public class DepositoBancario {
String banco;
List<String> interes;
public DepositoBancario(String s){
String[]v = s.split("[ :]");
Integer n= v.length;
if(n!=2) throw new IllegalArgumentException("Error"+s);
banco= v[0];
if(v[1] != null){
interes = new ArrayList<String>();
}
for(int i=1;i<n;i++)
interes.add(v[i]);
}
}
Note : Please consider the suggestion of markusw they are valuable.
First, You code won't compile unless You are using some custom implementation of List.
For what I can understand from You question it should be something like
import java.util.List;
import java.util.ArrayList;
public class DepositoBancario {
private String banco;
private List<String> interes;
DepositoBancario(String s) {
String[]v = s.split("[ :]"); // split input string by colon or space
if(v.length != 2) { // check if there are just two fields
throw new IllegalArgumentException("Invalid syntax, two fields expected: " + s);
}
banco = v[0];
interes = new ArrayList<String>();
interes.add(v[1]);
}
}
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
I've a doubt about how ArrayList contains method works. Let's take an example:
List<String> lstStr = new ArrayList<String>();
String tempStr1 = new String("1");
String tempStr2 = new String("1");
lstStr.add(tempStr1);
if (lst.contains(tempStr2))
System.out.println("contains");
else
System.out.println("not contains");
it returns 'not contains'.
Another example:
List<LinkProfileGeo> lst = new ArrayList<LinkProfileGeo>();
LinkProfileGeo temp1 = new LinkProfileGeo();
temp1.setGeoCode("1");
LinkProfileGeo temp2 = new LinkProfileGeo();
temp2.setGeoCode("1");
lst.add(temp1);
if (lst.contains(temp2))
System.out.println("contains");
else
System.out.println("not contains");
It returns contains. So how does contains method works ?
Thanks
You are adding your string to the list lstStr
lstStr.add(tempStr1);
but you are using contains method on lst
if (lst.contains(tempStr2))
Your idea of testing is correct, as contains internally uses equals to find the element, so if the string is matched using equals then it should return true. But it seems you are using two different lists, one for adding and another one for checking contains.
Here is the relevant source code from ArrayList if you're interested. As #user2777005 noted, you had a typo in your code. You should use lstStr.contains(), NOT lst.contains().
public int indexOf(Object o) {
if (o==null) {
for (int i=0; i<a.length; i++)
if (a[i]==null)
return i;
} else {
for (int i=0; i<a.length; i++)
if (o.equals(a[i]))
return i;
}
return -1;
}
public boolean contains(Object o) {
return indexOf(o) != -1;
}
the second part is a duplicate of: How does a ArrayList's contains() method evaluate objects?
You need to override the equals method to make it work as you desire.
in first section of code :
String tempStr1 = new String("1");
String tempStr2 = new String("1");
both tempStr1 and tempStr2 refer two different-2 object of string. after that String object that is refered by tempStr1 is added to the List by the codelstStr.add(tempStr1); .so the List have only one String object that is reffered by tempStr1 not tempStr2.but
contains(); method work on equals() method.that is lstStr.contains(temp2); return true if content of String object which is refered by temp2 is same as the one of content of String object which is added to the List and return false when matching not found.here lstStr.contains(temp2);return true because content of String object temp2 is equal to content of String object temp1 which is added to List.but in your code insteed of lstStr.contains(temp2); it is mentioned as:
lst.contains(temp2);
Here you are using different List reference variable (lst) instead of (lstStr).thats why it return false and executed else part.
in 2nd section of code setGeoCode() is not defined.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
Can anybody tell me what's wrong with my code
latest_songs,top_songs and hit_songs are arraylist.song() is a static method in Parseurl where i fetch the json array.it working fine & return proper data.
latest_Songs = ParseUrl.song(url1);
Log.i("ring,latest=", latest_Songs.toString());
top_Songs = ParseUrl.song(url2);
Log.i("ring,top=", top_Songs.toString());
hit_Songs = ParseUrl.song(url3);
Log.i("ring,hits=", hit_Songs.toString());
it works fine when i run latest_songs and top_songs.problem is with hit_songs.as i write this in my project both arraylist(latest_songs and top_songs) data overrided with hits_songs.where i am doing wrong.
this is ParseUrl from where i retrieve data in each arraylist
public class ParseUrl {
static ArrayList<String> songs_List = new ArrayList<String>();
static ArrayList<String> songs_Names = new ArrayList<String>();
static ArrayList<String> songs_Urls = new ArrayList<String>();
static File tempFiles;
File ringtones;
public static ArrayList<String> song(String url) {
songs_Names.clear();
songs_Urls.clear();
JSONObject json = JsonParse.getSongfromUrl(url);
try {
JSONArray latestSongs = json.getJSONArray("ringtones");
for (int count = 0; count < latestSongs.length(); count++) {
JSONObject song = latestSongs.getJSONObject(count);
songs_List.add(song.toString());
JSONArray name = song.names();
songs_Names.add(name.toString());
String songUrl = name.toString();
String URL = songUrl.substring(2, songUrl.lastIndexOf("\""));
songs_Urls.add(song.getString(URL));
}
} catch (JSONException e) {
e.printStackTrace();
}
return songs_Names;
}
Your arraylist is a static variable inside your class.So there is only one arraylist in memory.Each time you call the song method , you are modifying the same list.That means your latest_songs,top_songs,hit_songs, all will be pointing to same list.That is the reason your list is getting over ridden.
Try creating a list inside your method and return it rather than going for static variables.
Are you changing the url value anywhere?
Because you are assigning ParseUrl.song(url) to all the three array lists. Unless url is changed somewhere, all three array lists will have the same value since ParseUrl.song(url) will give the same result.