我正在尝试在Android中开发类似app的测验。问题和4选择应该来自服务器。我正在尝试使用json发送数据。问题或选择也可能包含数字。我尝试使用下面的json文件。它在android中运行良好。现在我的问题是我无法使用下面的JSON文件发送图像。我的方式是正确发送数据还是我应该使用json和php。
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 :(得分:0)
你的json似乎很好。你可以调整一下我的每个选择一个类(成员变量“type”和“value”)而不是直接在该类中的字符串你可以有一个变量说“type”,它可以有值“text”或“图片”。如果值是图像,您可以将字段“值”中的内容作为图像网址并在图像视图中显示,如果字段“类型”是“文本”,则可以在“值“并在textView中显示。
答案 1 :(得分:0)
您提出的问题并不明显,但如果我做对了,您就会遇到在JSON响应中发送图片的问题。
问题
您无法在JSON中发送任意二进制数据,因为JSON使用二进制文件可能包含的一些字符(如引号),因此在您可以在JSON响应中发送图像之前,图像需要以某种格式编码不包含JSON
使用的任何特殊字符Base64是一个受欢迎的选择,但显然不是JSON环境中最节省空间的,你可以阅读更多关于它here
答案
JSON中的图片
有多种方法可以实现结果,并且选择取决于应用程序,如果您要在发送问题的同一服务器中使用图像,则更容易对其中的图像进行base64编码JSON结果
JSON中的图片网址
如果对您没关系,或者您不关心服务器的额外往返,您可以在响应中向图像发送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解码器并将其解码为位图,这很简单!
从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文件中发送图像或任何内容
答案 2 :(得分:0)
这就是我的所作所为。
将图像存储在网络服务器上或使用cloudinary等服务。
在json文件中发送图片网址。检查下面示例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处理从服务器下载图像。