我老老实实地尝试过这么多教程并且做得很短。有人可以指导我如何从网址中获取一个简单的JSON数组,然后在Android工作室中填充listview。我尝试过的大部分教程都已过时且已弃用。请真正感谢任何帮助。
来自网址的Json数组:
[
{
"lot":"A",
"spaces":"100",
"rates":"7.00"
},
{
"lot":"B",
"spaces":"207",
"rates":"5.00"
}
]
我尝试过凌空,httpcall和其他各种方法。我可以在任何地方找到简单的指南吗?
答案 0 :(得分:2)
您可以使用以下代码
public class MyActivity extends Activity {
ListView list;
ArrayList<Data> myList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
list = (ListView) findViewById(R.id.list);
myList = new ArrayList<>();
LoadData sl=new LoadData();
sl.execute();
}
}
class LoadData extends AsyncTask<String, String, String>{
ProgressDialog pd;
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
pd=new ProgressDialog(Login.this);
pd.setCancelable(false);
pd.setMessage(getString(R.string.loading_login));
pd.show();
}
@Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
String buffervalue="";
try{
// StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
// StrictMode.setThreadPolicy(policy);
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost httpget = new HttpPost("url");
HttpResponse response = httpclient.execute(httpget);
InputStream inputStream = response.getEntity().getContent();
byte[] data = new byte[256];
StringBuffer buffer = new StringBuffer();
int len = 0;
while (-1 != (len = inputStream.read(data)) )
{
buffer.append(new String(data, 0, len));
}
inputStream.close();
buffervalue=buffer.toString();
}catch(Exception e){
}
return buffervalue;
}
@Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
JSONObject jsonobject;
try {
JSONArray jarr = new JSONArray(result);
int lengthJsonArr = jarr.length();
if(lengthJsonArr>0)
{
for(int i=0;i<lengthJsonArr;i++){
JsonObject obj = jarr.get(i);
Data data = new Data();
data.setLot(obj.getString("lot"));
data.setSpaces(obj.getString("spaces"));
data.setRates(obj.getString("rates"));
myList.add(data)
}
adapter.notifyDataSetChanged();
}else{
Toast.makeText(getApplicationContext(),R.string.label_internet, Toast.LENGTH_SHORT).show();
}
}
}catch(Exception e){
Toast.makeText(getApplicationContext(),"Something wrong with url...", Toast.LENGTH_SHORT).show();
}
pd.dismiss();
}
}
答案 1 :(得分:0)
在android中使用这种简单易用的技术进行json解析。
答案 2 :(得分:0)