大家好,又见面了,我是全栈君,今天给大家准备了Idea注册码。
1、下载数据来创建一个实体类
class MyData {
String imagepath;
String title;
String desc;
public MyData(String imagepath, String title, String desc)
{
super();
this.imagepath = imagepath;
this.title = title;
this.desc = desc;
}
}
2、AsyncTask数据载入及Json解析类
class FileAsyncTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... params)
{
InputStream is = null;
ByteArrayBuffer byteArrayBuffer = new ByteArrayBuffer(4000);
try
{
URL url = new URL(params[0]);
URLConnection openConnection = url.openConnection();
//设置连接超时的时间
openConnection.setConnectTimeout(3000);
//数据读取超时的时间
openConnection.setReadTimeout(3000);
is = openConnection.getInputStream();
byte[] buffer = new byte[1024];
int len;
while (-1 != (len = is.read(buffer)))
{
byteArrayBuffer.append(buffer, 0, len);
}
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
catch (IOException e)
{
// TODO Auto-generated catch block
runOnUiThread(new Runnable()
{
public void run()
{
//设置载入异常时的控件,通常显示运行进度条
}
});
e.printStackTrace();
}
finally
{
if (is != null)
{
try
{
is.close();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
String res = new String(byteArrayBuffer.toByteArray(), 0,
byteArrayBuffer.length());
return res;
}
// 解析jsonArray数据
@Override
protected void onPostExecute(String result)
{
try
{
JSONArray jsonArray = new JSONArray(result);
for (int i = 0; i < jsonArray.length(); i++)
{
JSONObject jsonObject = jsonArray.getJSONObject(i);
String imagepath = jsonObject.getString("imagepath");
String title = jsonObject.getString("title");
String desc = jsonObject.getString("desc");
MyData myData = new MyData(imagepath, title, desc);
dataList.add(myData);//加入数据
}
myAdapter.notifyDataSetChanged();//通知适配器数据改变
}
catch (JSONException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
super.onPostExecute(result);
}
}
3、调用
private ArrayList<MyData> dataList = new ArrayList<MainActivity.MyData>();//声明全局变量dataList
FileAsyncTask fileAsyncTask = new FileAsyncTask();
fileAsyncTask.execute("http://192.168.56.1:8080/service.txt");
版权声明:本文博客原创文章,博客,未经同意,不得转载。
发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/117232.html原文链接:https://javaforall.cn
【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛
【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...