How to convert JSON array to Java String array - java

I have a php file which fetches all rows from a specific column. The result is then put into an array and then json_encoded. When I Toast the output from the php file it shows a JSON string with the correct values. I need to convert this to a Java String array so I can iterate through it one by one on a button click.
I've tried multiple solutions on here but to no avail so any help will be greatly appreciated!
getImage.php
$sql = "SELECT advert_File_Path FROM Ads";
$result = $mysql_con->query($sql) or die('Query problem: '.mysqli_error($mysql_con));
//create array
$resultarray = array();
while($row = mysqli_fetch_assoc($result)){
$resultarray[] = $row;
}
echo json_encode($resultarray);
MainActivity.java (only the code that is relevant)
private void loadNextAdvert()
{
Toast.makeText(this, "Please wait, image may take a few seconds to load...", Toast.LENGTH_LONG).show();
dbhelper = (DbHelper) new DbHelper(new DbHelper.AsyncResponse() {
#Override
public void processFinish(String output) {
if(output.equalsIgnoreCase("exception") || output.equalsIgnoreCase("unsuccessful")){
Toast.makeText(MainActivity.this, "Connection error", Toast.LENGTH_SHORT).show();
}else{
//initializes ArrayList
stringList = new ArrayList<>();
try {
//initializes JSONArray with output from php getImage file
jsonArray = new JSONArray(output);
if(jsonArray != null){
int len = jsonArray.length();
for(int i=0; i<len; i++){
stringList.add(jsonArray.get(i).toString());
}
}
} catch (JSONException e) {
e.printStackTrace();
}
Toast.makeText(MainActivity.this, String.valueOf(stringList), Toast.LENGTH_LONG).show();
}
}
}).execute(loadPic);
}
The Toast which should display the contents of the ArrayList just appears as '[]'.

Managed to solve it myself. So here goes,
Step 1. I had to remove commented code from my php file as it was breaking through somehow, thats where the came from at the end of the JSON array.
Step 2. I had to remove an additional echo from the php file which I was using for error checking. I think I'm right in saying the only echo you want to have is the json_encode.
Step 3. Checked the length of JSONarray in Java and it was logging 5 so I now knew it was reading correctly.
Step 4. Added Pavneet_Singh's code snippet to replace stringList.add(jsonArray.get(i).toString());
with stringList.add(jsonArray.getJSONObject(i).optString("advert_File_Path"));
Step 5. Converted stringList from an ArrayList to a String array using this code stringArray = new String[stringList.size()];
stringArray = stringList.toArray(stringArray);
Happy days! I've spent far too long trying to figure this out haha the first two steps are pretty noobish but it's sometimes the most obvious things in life that are the hardest to find. Hopefully this can help someone else too!

use stringList.add(jsonArray.getString(i));

Try this:
JSONArray arr = new JSONArray(putNesessaryValueHere);
List<String> list = new ArrayList<String>();
for(int i = 0; i < arr.length(); i++){
list.add(arr.getJSONObject(i).getString("name"));
}

Try this :
ArrayList<String> arrayList = new ArrayList<String>();
JSONArray jsonArray = new JSONArray();
for(int i = 0, count = jsonArray.length(); i< count; i++)
{
try {
JSONObject jsonObject = jsonArray.getJSONObject(i);
arrayList.add(jsonObject.toString());
}
catch (JSONException e) {
e.printStackTrace();
}
}

Related

Can't receive proper format of String from JSON

I'm trying to read my .json file in .jsp file. The text I want to read is (from polish): "wewnętrzny". Instead of it I receive something like: "wewn�?trzny".
The code I'm using seems to not be working:
try {
JSONObject jsonObject = (JSONObject) parser.parse(new FileReader(FILE_PATH));
JSONArray tab = (JSONArray) jsonObject.get("tab");
for (int i = 0; i < tab.size(); i++) {
JSONObject jsonObjectRow = (JSONObject) tab.get(i);
byte[] raw = jsonObjectRow.get("a").toString().getBytes(ISO_8859_1);
String a = new String(raw, UTF_8);
out.println(a);
}
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
I've tried several encodings and all the solutions from: https://www.baeldung.com/java-string-encode-utf-8. Unfortunatelly, nothing made it work properly.
How can I fix this issue?
Ok, I figured it out!
In code it should be only:
String a = jsonObjectRow.get("a").toString();
And the file should be saved in windows-1250 encoding!
Thank's #marcinj for your advice!

How can I get the json data in an array in an array in Java?

I want to get the data in android studio with Wordpress rest api. But I can't get the data in an array that is inside a series. I tried the for loop but it didn't work. The underlined series in the image below is the category name and is variable. I want to get the name name: data under this series, but I failed. I will be glad if you help me.
final String GET_URL = Server.WORDPRESS_REST_API_URL + Server.SERVER_URL + Get.SERVER_JSON_RECENTLY_POSTS;
Log.d("serverurl", GET_URL);
StringRequest request = new StringRequest(Request.Method.GET, GET_URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if (!response.equals(null)) {
Log.d("Your Array Response", response);
try {
JSONObject jsonObj = new JSONObject(response);
JSONArray jsonArray = jsonObj.getJSONArray(Get.SERVER_JSON_RECENTLY_POSTS_ARRAY);
for (int j = 0; j < jsonArray.length(); j++) {
Log.d("jsonarrays", String.valueOf(jsonArray) + j);
JSONObject jsonObject = jsonArray.getJSONObject(j);
JSONObject jsonObjects = jsonObject.getJSONObject("categories");
JSONObject jsonObjects2 = jsonObjects.getJSONObject("name");
Log.d("jsonobjects", String.valueOf(jsonObjects2));
}
} catch (JSONException e) {
e.printStackTrace();
Log.d("Your error",e.getMessage());
}
}
else {
Log.d("Your Array Response", "Data Null");
}
First of all, I'd recommend you name your variables according to what they mean in the JSON, it will make things a lot easier for you (and us) to visualize.
It seems like your categories is an array as well and inside your for loop, you are not iterating through it. Your variable that holds the categories should be JSONArray, and position 0 of the array would be the JSONObject you are trying to get.
If I understand your code correctly, jsonObjects should be the array I'm talking about, iterate through it and try getting the property your want from the JSONObjects inside.

How do i add elements to my ArrayList one after the other?

Basically i have this code that's supposed to do this: Each time i call getAddedInvoices it's gonna add another element to the list, but my problem is that i'm new to the ArrayList so i'm not sure about how the thing works and it keeps adding elements like on top of each other instead of one after the other, This is the Code:
List<InvoiceData> data = new ArrayList<InvoiceData>();
public List<InvoiceData> getAddedInvoices() {
int f=0;
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
String jsonString = ReadingURL("http://pos.avancari.co.cr/app/buscar.productos.php");
try{
JSONArray jsonItems = new JSONArray(jsonString);
for(int i =0; i<jsonItems.length();i++){
if(jsonItems.getJSONObject(i).getString("itemCode").equals(addedcode)){
InvoiceData row = new InvoiceData();
row.id = addedcant;
row.invoiceNumber = i;
row.productName = jsonItems.getJSONObject(i).getString("itemDesc");
row.productCode = jsonItems.getJSONObject(i).getString("itemCode");
row.precio = jsonItems.getJSONObject(i).getString("itemPrice");
data.add(row);
f++;
}
else{
System.out.println("No entra a condicional con: "+addedcode);
}
}
return data;
}catch (Exception e){
e.printStackTrace();
return null;
}
}
That was the function, and then i just call it like this:
Invoices invoices = new Invoices();
List<InvoiceData> data = invoices.getAddedInvoices();
It's adding the selected elements correctly but idk why it just holds one and just replaces it with the new one instead of keep adding them.
Thanks in Advance
*Edit: The problem is that in the "if", even if it goes 5 fives times doesn't detect that it's another add apparently, because i added another data.add and this time i got size: 2 (which i didn't have before, it just said 1)
Here is my suggestion, make getAddedInvoices as void return type, do not return the data as its already global.
In this line you are reassigning which can be a problem.
List data = invoices.getAddedInvoices();
Since "data" is already global, just use it after invoices.getAddedInvoices() is called instead of getting a return value assigned again.
Your issue, if I understand what you want, is that you overwrite your data everytime you call your method.
Since java methods pass non-primitive objects by reference, you can do like this :
//In your target class or as a field
List<InvoiceData> data = new ArrayList<InvoiceData>();
// That's another method
public void addInvoices(ArrayList<InvoiceData> pData) {
int f=0;
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
String jsonString =
ReadingURL("http://pos.avancari.co.cr/app/buscar.productos.php");
try{
JSONArray jsonItems = new JSONArray(jsonString);
for(int i =0; i<jsonItems.length();i++){
if(jsonItems.getJSONObject(i).getString("itemCode").equals(addedcode)){
InvoiceData row = new InvoiceData();
row.id = addedcant;
row.invoiceNumber = i;
row.productName = jsonItems.getJSONObject(i).getString("itemDesc");
row.productCode = jsonItems.getJSONObject(i).getString("itemCode");
row.precio = jsonItems.getJSONObject(i).getString("itemPrice");
pData.add(row);
f++;
}
else{
System.out.println("No entra a condicional con: "+addedcode);
}
}
}catch (Exception e){
e.printStackTrace();
}
}
Then call it like this :
invoices.addInvoices(data);

Error properly reading JSON file in Android

I am having an odd issue reading in the following JSON formatted API - Trivia API (this URL is passed in through the Async). I will explain in more detail below, but basically my code appears to be not properly reading in a JSON file, which results in me being unable to loop through it and set my question objects accordingly.
Logs revealed that the reading of the input stream at IOUtils seems to not finish reading the entire JSON file, often stopping by the 11th question object within the file.
I think this has to do with a Log limit, as when I add more to the Log (such as "This is the json String -") it prints less, but this does not explain why it is not properly looping through the question objects and setting them accordingly. Other logs revealed that it does not even loop through the questions, it only goes through one time and only sets the title.
I am clueless as to what is happening as I have parsed other JSON files literally the exact same way as this.
#Override
protected ArrayList<Question> doInBackground(String... strings) {
HttpURLConnection connection = null;
ArrayList<Question> result = new ArrayList<>();
try {
URL url = new URL(strings[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
String json = IOUtils.toString(connection.getInputStream(), "UTF-8");
Log.d("demo", "This is the json String - " + json);
JSONObject root = new JSONObject(json);
JSONArray questions = root.getJSONArray("questions");
for (int i = 0; i < questions.length(); i++) {
JSONObject questionsJSONObject = questions.getJSONObject(i);
Question question = new Question();
question.setText(questionsJSONObject.getString("text"));
//Choice array
JSONObject choicesObject = questionsJSONObject.getJSONObject("choices");
String[] temp = new String[choicesObject.getJSONArray("choice").length()];
for (int j = 0; j < choicesObject.getJSONArray("choice").length(); j++) {
temp[j] = choicesObject.getJSONArray("choice").getJSONObject(j).toString();
}
question.setChoices(temp);
//End of Choice array
question.setAnswer(questionsJSONObject.getInt("answer");
question.setUrlToImage(questionsJSONObject.getString("image"));
result.add(question);
}
}
} catch (Exception e) {
//Handle Exceptions
} finally {
//Close the connections
}
Log.d("demo", "toString - " + result.toString());
return result;
}

Unable to set json string to TextView in onPostExecute in asyncTask

The problem that I'm facing right now is I simply want to set the string data from a json array in onPostExecute(). I skeemed through many tutorials on it, however, I am unable to set the Text that resides in the MainActivity. I've added the sample code below . I wonder if the data is wrong .
#SuppressWarnings("unchecked")
protected void onPostExecute(JSONObject jsonobject) {
try {
jsonarray = jsonobject.getJSONArray("grape");
outerjson = jsonarray;
String ids = jsonobject.optString("id");
String tpes = jsonobject.optString("type");
for (int i = 0; i < jsonarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
jsonobject = jsonarray.getJSONObject(i);
String str = "";}
// Step 3.
map1 = new HashMap<String, String>();
// this is the last step 4.
try {
JSONArray jArray = new JSONArray(str);
for (int i = 0; i < jArray.length(); i++) {
JSONObject json = null;
json = jArray.getJSONObject(i);
map1.put("id", json.getString("id"));
map1.put("type", json.getString("type"));
}
result.setText(jsonarray.toString());
///set the json in here
}catch (JSONException e) {}
} catch (JSONException e) {}
progressDialog.dismiss();
}
Not enough information, but I will try:
Make your code cleaner by using a container entity: MyData data = gson.fromJson(jsonobject, MyData.class).
Do not ignore exceptions
Make sure you are calling result.setText(string); within a main UI thread
Follow these 3 steps and, find the error, you will.

Categories

Resources