2015-10-14 126 views
0

我正在嘗試在android中開發類似應用程序的測驗。與4選擇一起的問題應該來自服務器。我正在嘗試使用json發送數據。問題或選擇也可能包含數字。我嘗試使用下面的json文件。它在android中運行良好。現在我的問題是我無法使用下面的JSON文件發送圖像。是我的方式來發送數據正確或應該使用JSON一起使用PHP。使用json將多選數據從服務器發送到android?

file.json(JSON文件)

{"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; 
    } 
} 

回答

0

您的JSON似乎鰭即你可以稍微微調一下,我可以讓每個選項都是一個類(帶有成員變量「type」和「value」),而不是直接在該類中的字符串,你可以使用一個變量「type」,其值可以是「text」或「圖片」。如果值是圖片,您可以將字段「value」中的內容作爲圖片url並將其顯示在imageview中,如果字段「type」爲「text」,則可以將內容以「值「並在textView中顯示它。

0

你所問的問題並不明顯,但如果我弄清楚了,你有在JSON響應中發送圖像的問題。

的問題

你不能在JSON發送任意的二進制數據,因爲JSON使用某些字符的二進制可能包含諸如引號,這樣纔可以JSON響應內發送圖像圖像需要在不包含任何由JSON用於那些特殊字符

Base64是一種流行的選擇,但顯然不是在JSON背景下最節省空間的某種格式進行編碼,你可以閱讀更多關於它here

答案

圖像中JSON

有可以實現的結果多種方式,而選擇是應用相關的,如果你有你要在同一服務器中使用的形象,正在發送的問題,它更容易只是Base64編碼,JSON結果中的圖片內JSON

圖像URL如果沒有無光呃給你,或者你不關心額外的往返服務器,你可以發送一個URL到響應中的圖像,然後使用url獲取圖像

爲了保持簡單,我建議只需使用Base64編碼,所以基本上在你的PHP服務器你BASE64_ENCODE包二進制字符串中使用以下方式:

內JSON

<?php 

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

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

echo json_encode($dataObject); 

?> 

發送二進制數據,然後你的Android應用程序中你可以先閱讀將圖像作爲字符串,然後在其上使用base64解碼器和de將它編碼爲位圖,夠簡單!

從JSON表示

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); 

獲取二進制數據,你準備好去!

此代碼尚未經過測試,但應該給你一個想法如何發送圖片或只是JSON文件

0

內的任何這是我做的。

將圖像商品儲存在網絡服務器上,或使用cloudinary這類服務。

在您的json文件中發送圖像url。檢查下面示例json中的圖像標籤。

[ 
    { 
     _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" 
    } 
] 

讓Android應用程序使用您的json中的URL從服務器下載圖像。