我正在学习android并尝试开发一个项目。出于项目目的,我想使用远程数据初始化数组。虽然我不知道,是否可能!
假设这是一个数组
String values[] = {"a","b","c","d","e"};
此阵列已初始化但我想初始化它以使用来自远程服务器的一些数据。远程服务器数据是JSON编码的。
有可能吗?
如果可能,我该怎么办?
如果不可能,那该怎么办?
答案 0 :(得分:0)
您可以改用ArrayList
,
// initialize ArrayList of Strings
ArrayList<String> myArray = new ArrayList<>();
// add data to your Array list
myArray.add(yourDatahere);
您可以根据需要为myArray
添加尽可能多的数据,因为ArrayList
尺寸是动态的。
添加更多数据,
myArray.add(yourDatahere);
myArray.add(yourDatahere);
myArray.add(yourDatahere);
myArray.add(yourDatahere);
myArray.add(yourDatahere);
从ArrayList打印数据
for (ArrayList<String> data : myArray){
System.out.println(data);
}
使用myArray.get(position)
答案 1 :(得分:0)
你可以这样做 -
将你的json转换为字符串然后 -
jsonString.replace("},{", " ,");
String values[] = jsonString.split(" ");
它将删除内部&#34;},{&#34;你将获得最终的字符串,如{&#34; a&#34;,&#34; b&#34;,&#34; c&#34;} 只是玩这个。
答案 2 :(得分:0)
private String sendRequest(String targetUrl) {
//Here, you define how method you'll use. In this case, I'm using POST
HttpPost method = new HttpPost(targetUrl);
HttpParams httpParameters = new BasicHttpParams();
//If you need, place here your TIMEOUT.
HttpConnectionParams.setConnectionTimeout(httpParameters,
<TIME TO OUT IN MILLIS>);
HttpConnectionParams.setSoTimeout(httpParameters, <TIME TO OUT IN MILLIS>);
//Define here your client in order to make requests to your servers
HttpClient client = new DefaultHttpClient(httpParameters);
//If you're using POST method, may be you need to add parameters in your request where it'll be used by your server in order to return a response to you.
List<NameValuePair> postParams = new ArrayList<NameValuePair>();
postParams.add(new BasicNameValuePair("<PARAMETER'S NAME>", "<PARAMETER'S VALUES>"));
//You may add multiple parameters here
//Here starts your request
try {
//Define your entity
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(postParams);
entity.setContentEncoding(HTTP.UTF_8);
method.setEntity(entity);
} catch (UnsupportedEncodingException e) {
//In case of any error
Log.e("REQUEST_ERROR", "Something was wrong: " + e);
}
try {
//The string wich will receive your result
String result;
//Send your request
HttpResponse response = client.execute(method);
StatusLine statusLine = response.getStatusLine();
if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
BasicManagedEntity entity = (BasicManagedEntity) response.getEntity();
//Get the result
result = EntityUtils.toString(entity);
//Return your result in order to be processed
return result;
} catch(ConnectTimeoutException cte) {
return null;
} catch (UnknownHostException e) {
return null;
} catch (Exception e) {
return null;
}
}
在此之后,通过写:
来调用此函数 String result = sendRequest(<URL HERE>);
现在您已经能够处理您的JSON数据了。通过知道您的响应是String类型但是采用JSON格式,您需要添加此代码以从String中获取JSON类型:
JSONObject obj = new JSONObject();
obj = new JSONObject(result);
我不知道你的JSON是如何形成的,但我认为你在JSON中将它作为一个数组得到了,对吧?
在这种情况下,您可以执行以下操作:
String[] array;
JSONArray jArray = obj.getJSONArray("<KEY_TO_LETTERS_ARRAY>");
int size = jArray.length();
if (size > 0) {
array = new String[size];
for(int i = 0; i < jArray.length(); i++) {
array[i] = new String(jArray.getString(i));
}
}
同样重要的是,在使用数组之前,请确定它是否为null,因为在最后一段代码中,只有当JSON数组的大小大于0时才初始化数组
if(array != null) {
//It's ok
} else {
//Something wrong
}
现在,您的数组已初始化。
享受它。
答案 3 :(得分:-1)
public String readJSONFeed(String URL)throws JSONException {
StringBuilder stringBuilder = new StringBuilder();
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(URL);
httpPost.setHeader("Content-Type",
"application/json");
JSONObject params=new JSONObject();
params.put("latitude", 43.6014049);
params.put("longitude",1.4478449);
try {
httpPost.setEntity(new StringEntity(params.toString()));
HttpResponse response = httpClient.execute(httpPost);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
InputStream inputStream = entity.getContent();
BufferedReader reader = new BufferedReader(
new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
stringBuilder.append(line);
}
inputStream.close();
} else {
Log.d("JSON", "Failed to download file");
}
} catch (Exception e) {
Log.d("readJSONFeed", e.getLocalizedMessage());
}
return stringBuilder.toString();
}
private class ReadJSONFeedTask extends AsyncTask<String, Void, String> {
String url=.......................;
protected void onPreExecute(){
super.onPreExecute();
}
protected String doInBackground(String... urls) {
try {
return readJSONFeed(url);
}catch (JSONException jsonException){
return null;
}
}
protected void onPostExecute(String result) {
try {
JSONObject jsonObject = new JSONObject(result);
// code to parse the jsonObject and assign it to your array
}catch (Exception e) {
Log.d("ReadWeatherJSONFeedTask", e.getLocalizedMessage());
}
}
}
这是我编写的示例代码,使用Post方法从Web服务获取一些数据。根据您的json结构,您可以添加一些代码来解析来自JSONObject的正确数据。当然,您可以使用GET方法获取数据并使用其他一些参数。我希望这对您有所帮助。 顺便说一下,我使用AsyncTask类来下载异步数据。