这是我在网上获取JSON文件的代码:
package com.example.maclocation;
import java.io.IOException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
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 android.net.ParseException;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.Toast;
public class MainActivity extends Activity {
String[] n1;
String[] n2;
String[] n3;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new ActorsAsyncTask().execute("link here");
}
class ActorsAsyncTask extends AsyncTask<String, Void, Boolean> {
这是我在网上获取JSON文件的代码:
@Override
protected Boolean doInBackground(String... urls) {
try {
//------------------>>
HttpPost post = new HttpPost(urls[0]);
HttpClient client = new DefaultHttpClient();
HttpResponse response = client.execute(post);
// StatusLine stat = response.getStatusLine();
int status = response.getStatusLine().getStatusCode();
if (status == 200) {
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
JSONObject jsono = new JSONObject(data);
JSONArray jarray = jsono.optJSONArray("coordinates");
n1 = new String[jarray.length()];
n2 = new String[jarray.length()];
n3 = new String[jarray.length()];
for (int i = 0; i < jarray.length(); i++) {
JSONObject object = jarray.getJSONObject(i);
n1[i] = object.getString("place").toString();
n2[i] = object.getString("lat").toString();
n3[i] = object.getString("lng").toString();
}
return true;
}
//------------------>>
} catch (ParseException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return false;
}
这是我在网上获取JSON文件的代码:
protected void onPostExecute(Boolean result) {
if(result == false){
Toast.makeText(getApplicationContext(), "Unable to fetch data from server", Toast.LENGTH_LONG).show();
}else{
for (int i = 0; i < n1.length; i++) {
// String xss= actorsList.
Toast.makeText(getApplicationContext(), n1[i] + "*" + n2[i]+ "*" +n3[i] , Toast.LENGTH_LONG).show();
}
}
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
问题:
是否可以更新Web服务器中托管的JSON文件?喜欢更新我当前的位置?我正在使用ADT Eclipse。
答案 0 :(得分:0)
因此,您需要在服务器端对其进行编码,可能使用php,ruby,python或您在服务器上使用的任何其他语言。
然后通过应用程序,您可以发送一个http请求传递一些参数,以确定您在托管JSON文件的同一服务器上执行的操作(以便您可以访问它),然后您可以编辑它!
本教程非常好:http://www.androidhive.info/2012/01/android-login-and-registration-with-php-mysql-and-sqlite/
在这种情况下,它是一个数据库,而不是一个JSON文件,但想法是一样的。