Getting last elements in list while uing json array - json

while passing list to json object i am not able to read all the elemnts.. it shows only the list which i stored very last
List<String> list = new ArrayList<String>();
for (int i=0 ; i<columnCount ; i++)
{
while (rs.next())
{
list.add(rs.getString(rsMetaData.getColumnName(i+1)));
}
json.put(rsMetaData.getColumnName(i+1), list);
//json.accumulate(rsMetaData.getColumnName(i+1), list);
}

ResultSet is a iterator who is iterated only once, for the first column.
The List-Object is only created once and strored multiple to json. Even if you store the list for the first column, you change this first-column value in the second column.
Try this:
while (rs.next()) {
for (int i=0; i < columnCount; i++) {
String columnName = rsMetaData.getColumnName(i+1);
List<String> list = new ArrayList<String>();
if (json.get(columnName) == null) {
json.put(columnName, list);
} else {
list = (List<String>)json.get(columnName);
}
list.add(rs.getString(columnName));
}
}
BTW: Duplicate columnNames are not supported by json

Finally i got the answer ...this is my code
try
{ HashMap map= new HashMap();
List list = new ArrayList();
int col = 0;
while (rs.next())
{
values = new JSONObject();
for (int i=0 ; i<columnCount ; i++)
{
values.put(rsMetaData.getColumnName(i+1),rs.getString(rsMetaData.getColumnName(i+1)));
}
list.add(col, values.toString());
System.out.println(list.toString());
col++;
}
json.put("gaea", list);
}//try block end

Related

Why is for loop only out putting first and last entries

This is what is being asked to do...
Write an application that inputs five numbers, each between 10 and 100, inclusive. As each number is read, display it only if it’s not a duplicate of a number already read. Provide for the “worst case,” in which all five numbers are different. Use the smallest possible array to solve this problem. Display the complete set of unique values input after the user enters each new value.
This is the code I have. It compiles and runs, but only outputs the first and last entries of the unique list. Any input greatly appreciated! Thanks in advance.
import java.util.Scanner;
public class DuplicateElimination{
// sets helper functions
public static boolean isIn(int x, int[]y)
{
boolean isIn = false;// sets boolean to false
for (int i=0; i<y.length; i++)// sets for loop to run for length of array
{
if(y[i]==x)
{
isIn = true;
}
}
return isIn;
}
public static int[] append(int x, int[] y)// going to change what has already been set. creates integer array
{
int len = y.length +1;// sets length
int[] a = new int[len];// initializes new array
for (int i=0; i<y.length; i++); // goes through length of y
{
int i=0;
a[i] = y[i];
}
a[y.length] =x;
return a;
}
public static void main(String[] args)// sets main
{
Scanner input = new Scanner (System.in);// sets scanner to read input info
int[]uniqueList = new int[1];
uniqueList[0] = 0;// sets unique list to 0
System.out.print("Enter an integer between 10 and 100:");// prompts input from user
int entered = input.nextInt();// inputs value from user
System.out.printf("This is the first time %d has been entered\n", entered);// adds first entered # to unique list
uniqueList[0] = entered;// adds entered value to unique list
for (int i=0; i<4; i++)// sets loop to find unique values
{
System.out.print("Enter an integer between 10 and 100:");// prompts use
entered = input.nextInt();// inputs value
if(isIn (entered, uniqueList) == false)// calls is in function
{
System.out.printf("This is the first time %d has been entered\n", entered);
uniqueList = append(entered, uniqueList);// puts entered values in unique values on list
}
}
System.out.println("The complete list of unique values entered is:");
for(int i =0; i< uniqueList.length; i++)// runs through list to check for unique #s
{
System.out.printf("Unique value %d: is %d\n", i + 1, uniqueList[i]);// outputs list
}
}// ends main
}// ends class
in the append part change your for loop to:
for (int i=0;i<y.length;i++)
a[i]=y[i];
it didn't work because of for (int i=0; i<y.length; i++); the semi-colon is hijacking your loop as for why the result is as it is, your
{
int i=0;
a[i] = y[i];
}
a[y.length] =x;
return a;
part is just copying the first element of y into a and then copying the new element in the last cel of a
import java.util.*;
class Example{
public static void main(String args[]){
int[] xr = new int[5];
Scanner input = new Scanner (System.in);
System.out.println("Input five different integers between 10 and 100 below");
L1: for (int i = 0; i < xr.length; i++){
System.out.print("\tInput number "+(i+1)+" : ");
xr[i] = input.nextInt();
for(;xr[i]<=10 || xr[i]>=100;){
i--;
System.out.println("\t Error : You entered number is not between 10 and 100.");
continue L1;
}
for (int x = 0; x < i; x++){
if(xr[x] == xr[i]){
i--;
System.out.println("\tError : You cannot use duplicate numbers.");
continue L1;
}
}
}
System.out.println(Arrays.toString(xr));
}
}

How can I enumerate an ASP listview control?

Below I take a list and convert it to a data table and bind it to an ASP listview control.
I'd like a function to convert it back to a List from an asp listview control and cannot figure out how to get the items? In Visual Studio debugging, the dataitems are null? It has the proper count but no values? I'd like to enumerate through all rows.
private void createLvwTable(List<string> table)
{
int index = 0;
DataTable dt = new DataTable();
foreach (string row in table)
{
string[] cells = row.Split('|');
if (index == 0) // header column
{
for (int j = 0; j < cells.Length; j++)
{
dt.Columns.Add(cells[j]);
//dt.Rows.Add();
}
}
else
{
DataRow dr = dt.NewRow();
for (int j = 0; j < cells.Length; j++)
{
dr[j] = cells[j];
}
dt.Rows.Add(dr);
}
index++;
}
lvwOutput.DataSource = dt;
lvwOutput.DataBind();
}
This is idiotic IMO so there is most likely a better way, but it appears you have to bind the data to an object during the listview creation. I couldn't find a good answer anywhere, this is a compilation of hours of searching and trying different combinations of semi-related answers.
On the html side you have to set the 'onitemdatabound' to a c# function. The code below also does not need to have the segmentation I'm going with a "|", I left that in to make it easier to read if you copy/paste my function.
I'd be happy to still read replies on how to do this better so I can learn.
html:
<asp:ListView ID="lvwOutput" runat="server" onitemdatabound="lvwOutput_ItemDataBound">
asp:
private List<string> lvwOutputItemsDataBoundToList = new List<string>();
private List<string> lvwOutputItemsDataBoundToListOriginal = new List<string>();
protected void lvwOutput_ItemDataBoundToList(object sender, ListViewItemEventArgs e)
{
if (e.Item.ItemType == ListViewItemType.DataItem)
{
ListViewDataItem dataItem = (ListViewDataItem)e.Item;
object o = (object)dataItem.DataItem;
System.Data.DataRowView rowView = e.Item.DataItem as System.Data.DataRowView;
object[] itemArray = rowView.Row.ItemArray;
string itemBound = "";
foreach(object item in itemArray)
{
itemBound += item.ToString() + "|";
}
if (itemBound.EndsWith("||"))
{
int index = itemBound.Length;
itemBound = itemBound.Remove(index - 2);
}
if (itemBound.EndsWith("|"))
{
int index = itemBound.Length;
itemBound = itemBound.Remove(index - 1);
}
lvwOutputItemsDataBoundToList.Add(itemBound);
}
ViewState["lvwOutputItemsDataBoundToList"] = lvwOutputItemsDataBoundToList;
}
private void filter()
{
lvwOutputItemsDataBoundToList = (List<string>)ViewState["lvwOutputItemsDataBoundToList"];
lvwOutputItemsDataBoundToListOriginal = lvwOutputItemsDataBoundToList;
foreach (string item in lvwOutputItemsDataBoundToList)
{
string[] itemSplit = item.Split('|');
}
}
To enumerate the ListViewItems see ListView.ListViewItemCollection Class and ListViewItem.SubItems Property.
List<string> lstItems = new List<string>():
foreach(ListViewItem itemRow in lvwOutput)
{
for (int i = 0; i < itemRow.SubItems.Count; i++)
{
lstItems.Add(itemRow.SubItems[i].Text);
}
}

Storing user id in a custom addapter class in a list

I have the following JSON-String:
{"Employee_Reports":[{"UserId":"10"},{"UserId":"12"},{"UserId":"13"},{"UserId":"14"},{"UserId":"15"},{"UserId":"1"},{"UserId":"5"},{"UserId":"11"}{"UserId":""}]}
I want to store all the UserId in a string array in a custom adapter class:
JSONObject jObject = new JSONObject(route_response);
JSONArray jsonArray = jObject.optJSONArray("Employee_Reports");
for(int i=0; i < jsonArray.length(); i++)
{
status = new String[jsonArray.length()];
for(int t=0; t<jsonArray.length(); t++) {
jObject = jsonArray.getJSONObject(t);
status[t] = jObject.getString("UserId");
It's not working as it shows an error.

Reading a URL to html file

txt file containing urls that need to be open and display the contents in a 4x4 board in an html file. Having some trouble with this as I am new too html. the first board reads the words and the second is supposed to display the pictures in a randomized order.
this is the .text file
A,ant
B,bear
C,cat
D,dog
E,elephant
F,fox
G,goat
H,horse
I, iguana
J, Jaguar
K,kangaroo
L, lion
M,monkey
N,newt
O,ostrich
P,penguin
A,http://a-z-animals.com/media/animals/images/470x370/ant8.jpg
B,http://a-z-animals.com/media/animals/images/470x370/bear5.jpg
C,http://a-z-animals.com/media/animals/images/470x370/cat1.jpg
D, http://a-z-animals.com/media/animals/images/470x370/dog5.jpg
E, http://a-z-animals.com/media/animals/images/470x370/african_elephant.jpg
F, http://a-z-animals.com/media/animals/images/470x370/fox.jpg
G,goat, http://a-z-animals.com/media/animals/images/470x370/goat.jpg
H, http://a-z-animals.com/media/animals/images/470x370/horse8.jpg
I, http://www.vivanatura.org/Iguana_iguana_juv1.jpg
J, http://upload.wikimedia.org/wikipedia/commons/thumb/f/fc/Jaguar.jpg/800px-Jaguar.jpg
K,http://images.nationalgeographic.com/wpf/media-live/photos/000/005/cache/gray-kangaroo_554_600x450.jpg
L, http://upload.wikimedia.org/wikipedia/commons/thumb/7/73/Lion_waiting_in_Namibia.jpg/800px-Lion_waiting_in_Namibia.jpg
M,http://upload.wikimedia.org/wikipedia/commons/d/d7/Crab-eating_Macaque_tree.jpg http://upload.wikimedia.org/wikipedia/commons/4/49/Notophthalmus_viridescensPCCA20040816-3983A.jpg
O,http://upload.wikimedia.org/wikipedia/commons/9/92/Ostriches_cape_point_cropped.jpg
P,http://upload.wikimedia.org/wikipedia/commons/b/be/Pygoscelis_papua.jpg
heres what i have so far, any hep would be much appreciated.
/*Muhammed Motala
* ics 240 prof. Jasthi
* THis program reads lines from a pre-existing text files and writes the
* contents to an HTMl file, while putting each line of code into a box forming two 4x4 board's.
*/
import java.io.*;
import java.util.*;
import javax.swing.*;
public class TicTacTwice {
public static void main (String [] args) throws IOException {
Scanner sc = new Scanner(new File("/Users/Muhammed/Documents/Tic_Tac_Twice/tic_tac_twice2.txt"));
BufferedWriter output = null;
String myLine = null;
String [] words = new String[100];
int counter = 0;
int counter1 = 0;
boolean run = true;
do {
try {
while(sc.hasNextLine()) { //reads each line in the txt file
String product = sc.nextLine();
myLine = product;
if (product.contains(" ")) { // if the line contains a space
String[] array1 = product.split(" "); // if contains space add to array
words[counter] = array1[1];
counter++;
}
if (product.contains("http://")) {
String [] array1 = product.split(",");
words[counter] = array1[1];
counter++;
System.out.println(array1[1]);
}
else if (product.contains(",")) { // if contains comma split into separate array
String [] array1 = product.split(",");
words[counter] = array1[1];
counter++;
}
}
sc.close();
FileWriter fw = new FileWriter("/Users/Muhammed/Documents/tic_tac_twice.html");
BufferedWriter bw = new BufferedWriter(fw);
bw.write("<html"); // html code upon writing of the file
bw.write("<head>");
bw.write("<table>");
bw.write("<h1> TICK TAC TWICE <h1>");
bw.write("<h1> Board 1 <h1>");
bw.write("</table>");
bw.write("</head>");
bw.write("<body>");
bw.write("<style>table, th, td{border:1px solid black;padding:5px}"
+ "table{border-spacing:15px}</style>");
bw.write("<table style=width:300px>");
for (int i = 0; i < 4; i++) { // array to create board1 and
// populate with the read in lines
bw.write("<tr>");
for (int j = 0; j < 4; j++) {
bw.write("<td>");
bw.write(words[counter1]);
counter1++;
bw.write("</td>");
}
bw.write("<tr>");
}
bw.write("<style>table, th, td{border:1px solid black;padding:5px}"
+ "table{border-spacing:15px}</style>");
bw.write("<table style=width:300px>");
for (int i = 0; i < 4; i++) { // creates board 2 and populates with
// words that are stored in array
bw.write("<tr>");
for (int j = 0; j < 4; j++) {
bw.write("<td>");
bw.write(words[counter1]);
bw.write("<td><img src=\"" + words[counter] +
"\" alt=\"some_text\"width=200 height=200></img>");
counter1++;
bw.write("</td>");
}
bw.write("<tr>");
}
bw.write("<h1> Board 2 <h1>");
bw.write("</body>");
bw.write("</html>");
bw.close();
run = false;
}
catch (Exception e) { // exception handler
System.out.print(e.toString());
}
}
while(run);
}
}

ActionScript - Comparing & Removing Duplicates of Complex Arrays?

when comparing simple arrays, i use something like the following function to concatenate and remove duplicates:
//Merge
public function merge(a1:Array, a2:Array):Array
{
var result:Array = a1.concat(a2);
var dictionary:Dictionary = new Dictionary();
for each (var item:Object in result)
dictionary[item] = true;
result = new Array();
for (var key:Object in dictionary)
result.push(key);
dictionary = null;
return result;
}
however, this approach doesn't work on complex arrays.
is there a well known algorithm, or is it even possible to write a function of recursion that can compare a Vector.<Object> with another? one that will always work even if the some objects being compared have additional key/value pairs?
[EDIT]
to be more clear, using a dictionary to determine if items in a simple array only works on primitive data types (int, number, string, etc.) or object references, so the above example works if it's passed 2 arrays resembling something like this:
var arr1:Array = new Array(1, 2, 3, 4, 5);
var arr2:Array = new Array(8, 7, 6, 5, 4);
resulting in a merged array with the following values:
1, 2, 3, 8, 7, 6, 5, 4
in contrast, i'm asking if it's possible to pass a function 2 complex arrays or Vector.<Object> all containing unique objects that may have identical key/value pairs and remove redundencies in the resulting Vector.<Object>. for example:
var vec1:Vector.<Object> = new Vector.<Object>();
vec1.push({city:"Montreal", country:"Canada"});
vec1.push({city:"Halifax", country:"Canada"});
var vec2:Vector.<Object> = new Vector.<Object>();
vec2.push({city:"Halifax", country:"Canada"});
vec2.push({city:"Toronto", country:"Canada"});
merging the above 2 vector objects would result in the following vector by determining and removing objects with identical key/value pairs:
{city:"Montreal", country:"Canada"}
{city:"Halifax", country:"Canada"}
{city:"Toronto", country:"Canada"}
i'm searching for an algorithm which could handle the removal of these similar objects without having to know about their specific key/value names or how many key/value pairs there are within the object.
Sure you can, you can build a similar example with any type of Vector:
public function mergeObjectVectors(v1:Vector.<Object>,
v2:Vector.<Object>):Vector.<Object>
{
var dictionary:Dictionary = new Dictionary();
var concat:Vector.<Object> = v1.concat(v2);
var result:Vector.<Object> = new Vector.<Object>();
for each(var i:Object in concat)
{
if (!dictionary[i])
{
dictionary[i] = true;
result.push(i);
}
}
return result;
}
However if you plan on accepting vectors of any type, it's different:
public function testing():void
{
var v1:Vector.<Object> = new Vector.<Object>();
v1.push({name:"Object 1"});
v1.push({name:"Object 2"});
// Vector w duplicates
var v2:Vector.<Object> = new Vector.<Object>();
var o:Object = {name:"Object 3"};
v2.push(o);
v2.push(o);
v2.push(o);
var resultVector:Vector.<Object> = mergeAnything(v1, v2, Class(Vector.<Object>));
var resultArray:Array = mergeAnything(v1, v2, Array);
var resultObject:Object = mergeAnything(v1, v2, Object);
}
public function mergeAnything(o1:Object, o2:Object, resultClass:Class):*
{
var dictionary:Dictionary = new Dictionary();
var result:Object = new resultClass();
var i:int;
for each(var o:Object in o1)
{
if (!dictionary[o])
{
dictionary[o] = true;
result[i++] = o;
}
}
for each(o in o2)
{
if (!dictionary[o])
{
dictionary[o] = true;
result[i++] = o;
}
}
return result;
}
The first example will be more resource-efficient.
EDIT:
This should do it, try it with your example:
public function mergeObjectVectors(v1:Vector.<Object>, v2:Vector.<Object>):Vector.<Object>
{
var concat:Vector.<Object> = v1.concat(v2);
var result:Vector.<Object> = new Vector.<Object>();
var n:int = concat.length;
loop:for (var i:int = 0; i < n; i++)
{
var objectToAdd:Object = concat[i];
var m:int = result.length;
for (var j:int = 0; j < m; j++)
{
var addedObject:Object = result[j];
if (this.areObjectsIdentical(objectToAdd, addedObject))
{
continue loop;
}
}
result.push(objectToAdd);
}
return result;
}
private function areObjectsIdentical(o1:Object, o2:Object):Boolean
{
var numComparisons:int = 0;
for (var s:String in o1)
{
numComparisons++;
if (o1[s] != o2[s])
{
return false;
}
}
for (s in o2)
{
numComparisons--;
}
return !numComparisons;
}