0

I am trying to develop the quiz like app in the android. The questions along with 4 choice should come from server. I am trying to use json to send the data. question or choice might consist figure also. I try to use below json file. It works well in android. Now my problem is I couldnot send image using the below JSON file. Is my way to send data correct or should I use json along with php.

file.json(JSON file)

{"multiple":[{
"question": "In which course are you inrolled in?",
"choice1":"BIM",
"choice2":"BBA",
"choice3":"BIT",
"choice4":"BSCCSIT"
},
{
"question": "What comes after n?",
"choice1":"s",
"choice2":"t",
"choice3":"o",
"choice4":"p"
},
{
"question":"Who is 38th Prime Minister of Nepal?",
"choice1":"KP Oli",
"choice2":"Susil Koirala",
"choice3":"Sher Bahadur Deuba",
"choice4":"Prachanda"
}

]
}

MainActivity.java

package com.multiple;
import android.app.*;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.*;
import android.widget.AdapterView.*;
import android.widget.RelativeLayout;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.ExecutionException;
public class MainActivity extends Activity
{
    private ListView listview;
    private Button finishbtn;
    private CheckBox check1,check2,check3,check4;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        List<HashMap<String, String>> collect = new ArrayList<HashMap<String, String>>();
        final List<HashMap<String, String>> answer = new ArrayList<HashMap<String, String>>();
        listview = (ListView) findViewById(R.id.list);
        finishbtn= (Button)findViewById(R.id.button);
        populate p = new populate();
        try {
            collect = p.execute().get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    String[] str = new String[]{"first", "second", "third", "fourth", "fifth"};
        int[] val = new int[]{R.id.textView1, R.id.checkBox1, R.id.checkBox2, R.id.checkBox3, R.id.checkBox4};
        SimpleAdapter adapter = new SimpleAdapter(this, collect, R.layout.list, str, val);
        listview.setAdapter(adapter);
        finishbtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v)
            {
                int count = listview.getCount();
                Log.i("count",String.valueOf(count));
                int j=0;
                while(j<count)
                {
                    RelativeLayout relLayout = (RelativeLayout) listview.getChildAt(j);
                    for(int i=0;i< relLayout.getChildCount();i++)
                    {
                        HashMap<String,String> value= new HashMap<String,String>();
                        View vi = relLayout.getChildAt(i);
                        if(vi instanceof CheckBox)
                        {
                            CheckBox c = (CheckBox)vi;
                            if(c.isChecked())
                            {
                                String ch = (String)c.getText();
                                Log.i("list",ch);
                                value.put(String.valueOf(j+1),ch);
                                answer.add(value);
                         }
                        }
                    }
                    j++;
                }
                Select select = new Select();
                select.execute(answer);
            }
        });
    }
    public class populate extends AsyncTask< String, Void,List<HashMap<String,String>> >
        {
            public List<HashMap<String,String>>  doInBackground(String... urls)
            {
                List<HashMap<String,String>> collect= new ArrayList<HashMap<String, String>>();
                    try
                    {
                        HttpClient client = new DefaultHttpClient();
                        HttpGet post = new HttpGet("http://192.168.10.116/file.json");
                        HttpResponse res= client.execute(post);
                        HttpEntity entity = res.getEntity();
                        String response = EntityUtils.toString(entity);
                        JSONObject obj = new JSONObject(response);
                        JSONArray jsonArray = obj.optJSONArray("multiple");
                            Log.i("size of the array",String.valueOf(jsonArray.length()));
                       ArrayList<JSONObject>  array = new ArrayList<JSONObject>();
                        for(int i=0; i < jsonArray.length(); i++)
                        {
                            JSONObject jsonObject = jsonArray.getJSONObject(i);
                            array.add(jsonObject);
                        }
                        for(int i=0;i<array.size();i++){
                            JSONObject jsonObject = array.get(i);
                            String question = jsonObject.optString("question").toString();
                            String c1 = jsonObject.optString("choice1").toString();
                            String c2 = jsonObject.optString("choice2").toString();
                            String c3 = jsonObject.optString("choice3").toString();
                            String c4 = jsonObject.optString("choice4").toString();
//                            Log.i("asdfas",question);
//                            Log.i("second",c1);
//                            Log.i("third",c2);
//                            Log.i("fourth",c3);
//                            Log.i("fifth",c4);
                            HashMap<String,String>  map = new HashMap<String, String>();
                            map.put("first",question);
                            map.put("second",c1);
                            map.put("third",c2);
                            map.put("fourth",c3);
                            map.put("fifth",c4);
                            collect.add(map);
                        }
    }
                    catch(IOException ex){}
                    catch(JSONException ex){}
                return  collect;
            }
        }
}

Select.java

package com.multiple;

import android.os.AsyncTask;
import android.util.Log;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.*;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;


public class Select extends AsyncTask<List<HashMap<String, String>>, Void, Void>
{
    @Override
    protected Void doInBackground(List<HashMap<String, String>>... answer) {

        try {
        HttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost("http://192.168.10.116/check.php");


        JSONArray array = new JSONArray(answer[0]);
        ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();

        nameValuePairs.add(new BasicNameValuePair("forward",array.toString()));
            post.setEntity(new UrlEncodedFormEntity(nameValuePairs));



            HttpResponse response = client.execute(post);

        HttpEntity httpEntity = response.getEntity();
        String result = null;

            result = EntityUtils.toString(httpEntity);

        Log.i("response", result);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }
}
N CR7
  • 41
  • 1
  • 12

3 Answers3

0

Your json seems fine. You can tweek it a bit my making each choice a class(with member variables "type" and "value") instead of a string directly in that class you can have a variable say "type" which can have value "text" or "image". In case if the value is image you can take the content in field "value" which would be the image url and show it in an imageview, in case if the field "type" is "text", you can take the content in "value" and show it in a textView.

pvn
  • 2,016
  • 19
  • 33
0

The question you're asking isn't obvious, but if I get it right, you have problem of sending image within a JSON response.

The Problem

You can't send arbitrary binary data within JSON because JSON uses some of the characters that the binary might contain such as quotes, so before you can send a image within the JSON response the image needs to be encoded in some format that doesn't contain any of those special characters used by JSON

Base64 is a popular choice, but obviously not the most space efficient in JSON context, you can read more about it here

The answer

Image within JSON

There's multiple ways you can achieve the result, and the choice is application dependent, if you have the image you're going to use within the same server that is sending the question, it is easier to just base64 encode the image within the JSON result

Image URL within JSON

If it doesn't matter to you, or you don't care for extra roundtrips to the server you could just send a URL to the image within the response, and afterward fetch the image using the url

To keep things simple I'd suggest to just use Base64, so basically in your PHP server you wrap the binary string with base64_encode in the following fashion:

Sending binary data within JSON

<?php

$binaryData = file_get_contents("image.png");

$dataObject = [
    "question" => "What is up?",
    "image" => base64_encode($binaryData)
];

echo json_encode($dataObject);

?>

Then within your Android application you can just first read the image as string and then use base64 decoder on it and decode it to bitmap, simple enough!

Getting binary data from JSON representation

JsonObject o = new JsonObject(responseString);

String b64String = o.get("image").getAsString();

byte[] rawData = Base64.decode(b64String.getBytes(), Base64.DEFAULT);

Bitmap bitmap = BitmapFactory.decodeByteArray(rawData, 0, rawData.length);

And you're ready to go!

This code hasn't been tested but should give you an idea how to send images or just about anything within JSON file

Community
  • 1
  • 1
Pasi Matalamäki
  • 1,843
  • 17
  • 14
0

This is what i do.

Store images on the web server or use a service like cloudinary.

Send image url in your json file. check the image tag in sample json below.

[
    {
        _id: "561cc08cdf3d8595314dcb92",
        location: "mumbai",
        image: "https://s3.amazonaws.com/uifaces/faces/twitter/holdenweb/128.jpg",
        address: "04250 Vernice Views, North Thaddeus port, Maryland",
        mobile: "9999999999",
        country_code: "91",
        last_name: "Collins",
        first_name: "Jarrell",
        __v: 0,
        active: true,
        updated_date: "2015-10-13T08:27:56.878Z",
        created_date: "2015-10-13T08:27:56.878Z",
        id: "561cc08cdf3d8595314dcb92"
    },
    {
        _id: "561cc08cdf3d8595314dcb93",
        location: "mumbai",
        image: "https://s3.amazonaws.com/uifaces/faces/twitter/aka_james/128.jpg",
        address: "7639 Marianna Pike, Hills chester, New Mexico",
        mobile: "9999999999",
        country_code: "91",
        last_name: "Nienow",
        first_name: "Pedro",
        __v: 0,
        active: true,
        updated_date: "2015-10-13T08:27:56.878Z",
        created_date: "2015-10-13T08:27:56.878Z",
        id: "561cc08cdf3d8595314dcb93"
    }
]

Let Android app handle downloading image from server using URL in your json.

Parag Naik
  • 571
  • 6
  • 6