This might be a simple Java issue I'm struggling with but I'm looking to the community to assist me here as I have hit a brick wall with this situation.
I successfully have data coming in off of a MySQL database and brought to the application through JSON. During parsing I was trying to create another array to be passed onto an ArrayAdapter to be used in a ListView. Here is the code I'm having an issue with:
try{
jArray = new JSONArray(result);
JSONObject json_data=null;
for(int i=0;i<jArray.length();i++){
json_data = jArray.getJSONObject(i);
ct_id=json_data.getString("ID");
ct_name=json_data.getString("Player2N");
Games game_data[] = new Games[]
{
new Games(ct_id, ct_name)
};
}
GameAdapter adapter = new GameAdapter(this, R.layout.listview_item_row, game_data);
listView1 = (ListView)findViewById(R.id.listView1);
View header = (View)getLayoutInflater().inflate(R.layout.listview_header_row, null);
listView1.addHeaderView(header);
listView1.setAdapter(adapter);
}
This line: GameAdapter adapter = new GameAdapter(this, R.layout.listview_item_row, game_data);
More specifically the game_data is highlighted red in Eclipse. Where I am curious is why does game_data get out of reach after end of loop? I'm just trying to add specific fields within the row from JSON to the adapter here.
I also tried going through the loop within setting up the array but still no dice as new Games[] gets an error. Here is an example:
Games game_data[] = new Games[]
{
for(int i=0;i<jArray.length();i++){
json_data = jArray.getJSONObject(i);
ct_id=json_data.getString("ID");
ct_name=json_data.getString("Player2N");
// Games game_data[] = new Games[]
// {
new Games(ct_id, ct_name);
// };
}
error: Variable must either provide dimension expressions or array initializer.
Hope this helps...
try{
jArray = new JSONArray(result);
JSONObject json_data=null;
Games game_data[];
game_data[] = new Games[jArray.length()];
for(int i=0;i<jArray.length();i++){
json_data = jArray.getJSONObject(i);
ct_id=json_data.getString("ID");
ct_name=json_data.getString("Player2N");
game_data[i] = new Games(ct_id, ct_name);
}
GameAdapter adapter = new GameAdapter(this, R.layout.listview_item_row, game_data);
listView1 = (ListView)findViewById(R.id.listView1);
View header = (View)getLayoutInflater().inflate(R.layout.listview_header_row, null);
listView1.addHeaderView(header);
listView1.setAdapter(adapter);
}
I am thinking that Games is your POJO class so you can better do something like this,
Create a List of the POJO class
private List<Games> games= new ArrayList<Games>();
Now you can add your content in the games list.
for(int i=0;i<jArray.length();i++){
json_data = jArray.getJSONObject(i);
ct_id=json_data.getString("ID");
ct_name=json_data.getString("Player2N");
games.add(new Games(ct_id, ct_name));
}
And finally pass the list in the Adapter.
GameAdapter adapter = new GameAdapter(this, R.layout.listview_item_row, games);
error: Variable must either provide dimension expressions or array initializer.
=> This error is obvious because you haven't define any dimensions value to create an array and also haven't passed any initialization to this array.
So I think you are doing wrong, instead do it like:
Games game_data[] = new Games(ct_id, ct_name);
This is the correct way to call a constructor.
And i don't know what you have written inside the Games class so i just have mentioned about the calling of constructor.
Related
I am rather new to JSON at the moment, but I need to convert a JSON response that contains the same key, but different values to an ArrayList to use it with my spinner.
I tried it like here: Converting JSONarray to ArrayList
But i get the whole json string, but just need the value part.
I can't figure out how to do this and found no answer that worked for me :/
What I want would be a List like:
City1
City2
City3
But i have in my spinner:
{"city":"name1"}
{"city":"name2"}
{"city":"name3"}
Code I have is:
JSONArray obj = new JSONArray(response);
Spinner availableCitySpin;
availableCitySpin = (Spinner) findViewById(R.id.avCitySp);
List<String> cityValues = new ArrayList<String>();
if (jarr != null) {
for (int i=0;i< jarr.length();i++){
cityValues.add(jarr.getString(i).toString());
}
}
ArrayAdapter<String> cityAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, cityValues);
cityAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
availableCitySpin.setAdapter(cityAdapter);
availableCitySpin.setSelection(0);
Change your code to something like this:
...
for (int i=0;i< jarr.length();i++){
JSONObject cityObject = jarr.getJSONObject(i);
cityValues.add(cityObject.getString("city"));
}
...
Try this:
First use split
For example: String[] result = splits[0].split(":");
you will get two item in array result. result[0]= {"city" and result[1] = "name1"}
If you want to get the key use result[0]
remove sign from result[0] using replace. Example: data = result[0].replace("\"","").replace("{","");
use it in loop, should work
I am parsing JSON into a textview and i need some help trying to put that into a listview instead. I know this might be very easy for some, but my main focus of confusion is that in a textview, you are setting the text using the setText function. I am also new to android, so I don't have this basic down yet, but I appreciate any help in advance, thank you.
public void onClick(View arg0) {
TextView tv1 = (TextView) findViewById(R.id.textView1);
TextView tv2 = (TextView) findViewById(R.id.textView2);
try {
String buildings = getJSON("http://iam.colum.edu/portfolio/api/course?json=True");
//JSONObject jsonObject = new JSONObject(buildings);
JSONArray queryArray = new JSONArray(buildings);
//queryArray = queryArray.getJSONArray(0);
List<String> list = new ArrayList<String>();
for (int i=0; i<queryArray.length(); i++) {
list.add( queryArray.getString(i) );
}
String finaltext="";
StringBuilder sb = new StringBuilder();
for (int i=0; i<queryArray.length(); i++) {
// chain each string, separated with a new line
sb.append(queryArray.getString(i) + "\n");
}
// display the content on textview
tv1.setText(sb.toString());
//tv1.setText(arr[0]);
} catch (Exception e) {
e.printStackTrace();
Log.d("JSONError", e.toString());
}
}});
Basically you add your ListView in your layout file, and then in the code you set an Adapter on the ListView, which holds the data. And then all the magic is going to be done for you.
Please read
http://developer.android.com/guide/topics/ui/layout/listview.html
http://developer.android.com/guide/topics/ui/declaring-layout.html#AdapterViews
So in your case it would look something like this:
ListView listView = (ListView) findViewById(R.id.listview);
...
JSONArray queryArray = new JSONArray(buildings);
//queryArray = queryArray.getJSONArray(0);
ArrayList<String> list = new ArrayList<String>();
for (int i=0; i<queryArray.length(); i++) {
list.add( queryArray.getString(i) );
}
ArrayAdapter adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, list);
listView.setAdapter(adapter);
adapter.notifyDataSetChanged();
This will take the content of your list and create one ListView item for each entry. The text is set to the layout file android.R.layout.simple_list_item_1 which is provided by android.
If you change the content of the ArrayAdapter (and thus the ListView) you have to call adapter.notifyDataSetChanged() to inform the system that the content has changed.
To change the layout, or add an Adapter for other data sources, please refer to the documentation.
I'm parsing the json object taken from server. I want to put the list in reverse order. In order to do that I made a code like this.
ArrayList<HashMap<String, String>> contactList = new ArrayList<HashMap<String, String>>();
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(url);
try {
// Getting Array of Contacts
products = json.getJSONArray(TAG_PRODUCTS);
// looping through All Contacts
for(int i = products.length(); i >0; i--){
JSONObject c = products.getJSONObject(i);
// Storing each json item in variable
String cid = c.getString(TAG_CID);
String name = c.getString(TAG_NAME);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_CID, cid);
map.put(TAG_NAME, name);
// adding HashList to ArrayList
contactList.add(map);
Log.d("value", contactList.toString());
}
} catch (JSONException e) {
e.printStackTrace();
}
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(this, contactList,
R.layout.list_item,
new String[] { TAG_NAME,}, new int[] {
R.id.name});
setListAdapter(adapter);
If I try to do it in the right order, the list will appear. But if I try reverse, I won't get any output. The problem is in for looping. But cannot findout where it is actually.
Yes, the problem is in the loop. The first pass through should throw some sort of "out of bounds" exception, because products.getJSONObject(products.length()) does not exist. Look in logcat for the details, and/or step through your code with a debugger. Remember, with zero-indexed collections (arrays, lists, etc.) the smallest index value is 0 and the largest is 1 less than the total number of elements in the collection.
The fix is to change this:
for(int i = products.length(); i >0; i--){
to this:
for(int i = products.length() - 1; i >= 0; i--){
change your for loop Syntax as Below
for(int i = products.length() - 1; i >= 0; i--){
// your Code
}
Change your loop like this
for(int i = products.length()-1; i >=0; i--){
It should work
Add this between parsing of json and creating of adapter:
Collections.reverse(contactList);
To reverse list:-
ArrayList<Element> tempElements = new ArrayList<Element>(mElements);
Collections.reverse(tempElements);
I receive some data as a JSON response from a server. I extract the data I need and I want to put this data into a string array. I do not know the size of the data, so I cannot declare the array as static. I declare a dynamic string array:
String[] xCoords = {};
After this I insert the data in the array:
for (int i=0; i<jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
xCoords[i] = json_data.getString("xCoord");
}
But I receive the
java.lang.ArrayIndexOutOfBoundsException
Caused by: java.lang.ArrayIndexOutOfBoundsException
What is the way to dynamically insert strings into a string array?
Use ArrayList although it is not really needed but just learn it:
ArrayList<String> stringArrayList = new ArrayList<String>();
for (int i=0; i<jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
stringArrayList.add(json_data.getString("xCoord")); //add to arraylist
}
//if you want your array
String [] stringArray = stringArrayList.toArray(new String[stringArrayList.size()]);
Try like this
String stringArray[];
stringArray=new String[jArray.length()];
String xCoords[]=new String[jArray.length()];;
for (int i=0; i<jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
xCoords[i] = json_data.getString("xCoord");
}
String Array in Java has a defined size that should be given while declaration, you cannot change it later by adding or removing elements and the pure concept of the dynamic array does not exit in java. Read detailed article here...
This is the right way to declare an array of fixed size.
String[] myString = new String[5];
fruits[0]="hello";
fruits[1]="hello";
fruits[2]="hello";
fruits[3]="hello";
fruits[4]="hello";
Instead, you can use a List to perform a similar task. The list is purely dynamic and you can add multiple values on runtime.
This is the right way to declare a list in Android using JAVA.
ArrayList<String> fruits = new ArrayList<String>();
fruits.add("Value 1");
fruits.add("Value 2");
fruits.add("Value 3");
fruits.add("Value 4");
fruits.add("Value 5");
fruits.add("Value 6");
fruits.add("Value 7");
// add as much values as per requirement
// you can also use loops to add multiple values
I've got a little problem, and i don't see it.
I retrieve Json data (the JSONArray) and i wanted to make a List of all the names in the JSONArray, something like this.
List list = new ArrayList<String>();
for(int i=0;i < data.length();i++){
list.add(data.getJSONObject(i).getString("names").toString());
}
And i wanted to take this list in an `ListView' so i did this :
ArrayList<String> test = history_share.list;
names_list = (String[]) test.toArray();
ArrayAdapter<String> adapter = new ArrayAdapter(this,
android.R.layout.simple_list_item_1, names_list);
setListAdapter(adapter);
(history_share is one of the method i created to take json data from an api .
Eclipse doesn't see any error, and me neither.
Can somebody help me please ?
Why do your methods have underscores in their names? Methods by convention begin with a lowercase letter. For example myMethod(). Class names begin with uppercase letters like MyClass. You should stick to that.
Also history_share is not a method the way you posted your code plus you won't be able to retrieve anything from a method by calling it that way.
A getter method just returns the defined member. I'm very surprised that Eclipse doesn't highlight that. Are you sure error checking is turned on?
Update: Naming your classes like already existing classes is generally a very bad idea and it gets even worse if you plan to use the original class somewhere or any class deriving that class. In the original Connection class I cant spot any static member called list which leads to the assumption that you've created your own Connection class. This doesn't have to be the problem here but it may raise problems in the future if you continue to do that.
for(int i=0;i < data.length();i++){
list.add(data.getJSONObject(i).getString("names").toString());
}
.getString("names") returns String, remove .toString()
Also,
ArrayAdapter<String> adapter = new ArrayAdapter(this,
android.R.layout.simple_list_item_1, names_list);
replace with
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, names_list);
You try this using ArrayList with Hashmap:
ArrayList<HashMap<String, String>> comunitylist = new ArrayList<HashMap<String, String>>();
String url =_url + _uid + uid;
JSONParstring jParser = new JSONParstring();
// getting JSON string from URL
String json = jParser.getJSONFromUrl(url,apikey);
Log.e("kPN", json);
try
{
JSONObject jobj = new JSONObject(json);
Log.e("kPN", json.toString());
System.out.print(json);
JSONArray comarray = jobj.getJSONArray(TAG_COMMU);
for(int i = 0; i <= comarray.length(); i++){
JSONObject c = comarray.getJSONObject(i);
Log.w("obj", c.toString());
JSONObject d = c.getJSONObject(TAG_PERSON);
Log.w("obj", d.toString());
String name =d.getString(TAG_NAME);
Log.w("name", name);
String nick =d.getString(TAG_NICK);
String home = d.getString(TAG_HOME);
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_NAME, name);
map.put(TAG_NICK, nick);
}
}
catch (JSONException ie)
{
}
list=(ListView)findViewById(R.id.list);
adapter=new Lazycommunity(this,listz);
list.setAdapter(adapter);
list.setOnItemClickListener(new OnItemClickListener() {
#SuppressWarnings("unchecked")
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
//Having Trouble with this line, how to retrieve value???
HashMap<String, String> map2 = (HashMap<String, String>) list.getAdapter().getItem(position);
Intent in = new Intent(getApplicationContext(), Communityprofile.class);
in.putExtra(TAG_NAME, map2.get(TAG_NAME));
in.putExtra(TAG_IMG, map2.get(TAG_IMG));
startActivity(in);
}
});