Setting array equal to JSON array - Xcode - arrays

I'm trying to figure out how to populate a table from a JSON array. So far, I can populate my table cells perfectly fine by using the following code:
self.countries = [[NSArray alloc]initWithObjects:#"Argentina",#"China",#"Russia",nil];
Concerning the JSON, I can successfully retrieve one line of text at a time and display it in a label. My goal is to populate an entire table view from a JSON array. I tried using the following code, but it still won't populate my table. Obviously I'm doing something wrong, but I searched everywhere and still can't figure it out:
NSURL *url = [NSURL URLWithString:#"http://BlahBlahBlah.com/CountryList"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON)
{
NSLog(#"%#",[JSON objectForKey:#"COUNTRIES"]);
self.countries = [JSON objectForKey:#"COUNTRIES"];
}
failure:nil];
[operation start];
I am positive that the data is being retrieved, because the NSLog outputs the text perfectly fine. But when I try setting my array equal to the JSON array, nothing happens. I know the code is probably wrong, but I think I'm on the right track. Your help would be much appreciated.
EDIT:
This is the text in the JSON file I'm using:
{
"COUNTRIES": ["Argentina", "China", "Russia",]
}
-Miles

It seems that you need some basic JSON parsing. If you only target iOS 5.0 and above devices, then you should use NSJSONSerialization. If you need to support earlier iOS versions, then I really recommend the open source JSONKit framework.
Having recommended the above, I myself almost always use the Sensible TableView framework to fetch all data from my web service and automatically display it on a table view. Saves me a ton of manual labor and makes app maintenance a breeze, so it's probably something to consider too. Good luck!

Related

Save Images in Room Database

I want to save small images in my room database and I have two issues:
How do I save an image in my database?
How do I save multiple images in my database?
I tried saving a bitmap in the way recommended by the developers page (https://developer.android.com/training/data-storage/room/defining-data)
#Parcelize
#Entity(tableName = "image_table")
data class ImgMod(
#PrimaryKey(autoGenerate = true)
var invoiceId: Long = 0L,
#ColumnInfo(name = "image")
var single_img: Bitmap?
): Parcelable
However, I receive the following error:
Cannot figure out how to save this field into database. You can consider adding a type converter for it.
Secondly, I would like to save multiple images in one database entry. But I receive the same error with the following snippets:
#ColumnInfo(name = "imageList")
var img_list: ArrayList<BitMap>
or decoded bitmap as a String
#ColumnInfo(name = "imageList")
var decoded_img_list: ArrayList<String>
I am sorry if this is a very basic question. But how do I have to configure the database/process the data to an image list?
Thank you in advance,
rot8
A very simple way to get images into the database (although I personally discourage it) would be to base-64 encode the bitmaps into a String and put it into a row of the database.
Take in account that bitmaps are very memory heavy; and base64 encoding something increases it's size some more so be careful when loading a bunch of images... I do also think Room and SQLite supports binary data as blobs, so you could just declare a column as ByteArray and it should just work.
What I've been doing in my projects is to write them into the internal or external storage of my app and then store the reference Uri as a String to later be able to retrieve the image from disk.
Something that I discourage even more is to stuff more than one value per row; having a list of stuff inside a coulmn in SQL is definetely not a pattern you should follow. Creating a "join" table should be simple enough or simply an extra column you could use to group them by should be easy enough, right?

Displaying Parse Data to ContainerList

I want to display data from Parse in a list from GamesScores class using Container in Codename One, this is what I've tried so far and it's not showing anything nor giving any errors:
Container container = findListCont();
container.setLayout(BoxLayout.y());
container.setScrollableY(true);
ParseQuery<ParseObject> query = ParseQuery.getQuery("GameScore");
List<ParseObject> results = (List<ParseObject>) query.find();
System.out.println("Size: " + results.size());
container.addComponent(results, f);
Please help me out, I'm a new in Codename One. If there tutorials on it, please share or anything to help me achieve the desired results.
I'm actually shocked this isn't failing. You are using the add constraint to place the object result as a constraint and you add the form object into the container...
You need to loop over the results and convert them to components to add into the layout. It also seems that you are using the old GUI builder which I would recommend against.
Generally something like this rough pseudo code should work assuming you are using a box Y layout:
for(ParseObject o : results) {
MultiButton mb = new MultiButton(o.getDisplayValue());
f.add(mb);
}
f.revalidate();

Unable to translate bytes [...] at index ... from specified code page to Unicode when adding to index

I am using Newtonsoft.Json to create the JSON to update add items to an index, but I get the following error when I POST the request:
{"error":{"code":"","message":"The request is invalid.","innererror":{"message":"parameters : Unable to translate bytes [E3] at index 752 from specified code page to Unicode.\r\n","type":"","stacktrace":""}}}
I know the error occurs with some non letter characters in some of the strings in the data that I am serializing. The string data comes from SQL, so I'm guessing something is going on to do with encoding that I cannot figure out.
When I inspect the JSON string, and put it in manually construct a request with the same data in Fiddler it all works fine.
Does anyone have any idea what might be the problem, and how I can work around it?
I found my own solution after a bit more digging.
Adding "StringEscapeHandling.EscapeNonAscii" to the serialization options solves the problem:
jsonSettings = new JsonSerializerSettings
{
Formatting = Newtonsoft.Json.Formatting.Indented,
ContractResolver = new CamelCasePropertyNamesContractResolver(),
DateTimeZoneHandling = DateTimeZoneHandling.Utc,
StringEscapeHandling = StringEscapeHandling.EscapeNonAscii
};

How to store data from SmartGWT ListGrid?

I've been searching for hours but I couldn't find an answer to my question: I've set up a ListGrid similar to the one shown here (Link). Right now I am using a XML-File as data source (default rows) just like in the example. It is also possible to add and delete rows to/from the grid.
Therefore I would like to store every user's data from the grid in a data store (Google Datastore). So I need to read all the rows of the current user as Strings. What would be a good way to do that? I already tried the following, but without success:
ListGrid componentsGrid = new ListGrid();
componentsGrid.setWidth(500);
componentsGrid.setHeight(224);
componentsGrid.setCellHeight(22);
componentsGrid.setDataSource(ComponentsXmlDS.getInstance());
componentsGrid.setAutoFetchData(true);
componentsGrid.setCanEdit(true);
componentsGrid.setModalEditing(true);
componentsGrid.setEditEvent(ListGridEditEvent.CLICK);
componentsGrid.setListEndEditAction(RowEndEditAction.NEXT);
componentsGrid.setAutoSaveEdits(false);
layout.addMember(componentsGrid);
//First try
componentsGrid.fetchData();
logger.log(Level.INFO, "Components: "+ componentsGrid.getResultSet().get(0).getAttribute("componentType"));
//Second try
logger.log(Level.INFO, "Components: "+ componentsGrid.getAllFields());
// Third try
logger.log(Level.INFO, "Components: "+ componentsGrid.getRecords());
Anyone having a hint? Help is greatly appreciated.
If I understand well your requirement you want to read all the rows of the grid and store their data in a db.
I think you can use:
getRecordList() which *Return the underlying data of this DataBoundComponent as a RecordList.
You will be able to iterate inside this list, extract the attribute value you want for every record and store these data in your db.
Or use the getRecords() method as you said and iterate in the array of ListGridRecord obtained.
To iterate through your RecordList you have to transform it to an array, for example with a lot of dummy objects and methods:
RecordList data = MyGrid.getRecordList();
for(Record record : data.toArray()){
MyDataObject obj = new MyDataObject()
obj.setId(record.getAttribute("thId"));
obj.setOne(record.getAttribute("anAttribute"));
obj.setTwo(record.getAttribute("anotherAttribute"));
obj.StoreToDb();
}

Byte Array copy in Jsp

I am trying to append 2 images (as byte[] ) in GoogleAppEngine Java and then ask HttpResponseServlet to display it.
However, it does not seem like the second image is being appended.
Is there anything wrong with the snippet below?
...
resp.setContentType("image/jpeg");
byte[] allimages = new byte[1000000]; //1000kB in size
int destPos = 0;
for(Blob savedChart : savedCharts) {
byte[] imageData = savedChart.getBytes(); //imageData is 150k in size
System.arraycopy(imageData, 0, allimages, destPos, imageData.length);
destPos += imageData.length;
}
resp.getOutputStream().write(allimages);
return;
Regards
I would expect the browser/client to issue 2 separate requests for these images, and the servlet would supply each in turn.
You can't just concatenate images together (like most other data structures). What about headers etc.? At the moment you're providing 2 jpegs butted aainst one another and a browser won't handle that at all.
If you really require 2 images together, you're going to need some image processing library to do this for you (or perhaps, as noted, AWT). Check out the ImageIO library.
Seem that you have completely wrong concept about image file format and how they works in HTML.
In short, the arrays are copied very well without problem. But it is not the way how image works.
You will need to do AWT to combine images in Java

Resources