在android中更新ui时获取数据的方法

在android中更新ui时获取数据的方法,android,performance,android-layout,Android,Performance,Android Layout,所以这个问题困扰了我一段时间,因为我似乎找不到一种简单、方便和自然的方法来更新ui,同时从外部位置(Web服务器)获取数据 我将概述我的情景: 我有一个Web服务器,它为JSONArray和JSONObject提供服务。它总是返回这个,因为我不喜欢空指针。我试图编写一个扩展AsyncTask的类。我成功地做到了这一点,看起来是这样的: public class Server extends AsyncTask<String, Integer, Object>{ pr

所以这个问题困扰了我一段时间,因为我似乎找不到一种简单、方便和自然的方法来更新ui,同时从外部位置(Web服务器)获取数据

我将概述我的情景:

我有一个Web服务器,它为JSONArray和JSONObject提供服务。它总是返回这个,因为我不喜欢空指针。我试图编写一个扩展
AsyncTask
的类。我成功地做到了这一点,看起来是这样的:

public class Server extends AsyncTask<String, Integer, Object>{

        private String fetch_url;
        private String return_type;
        private Activity ct;

        public Server() {
        }

        public Server(Activity ct) {
            this.ct = ct;
        }

        @Override
        protected void onPreExecute()
        {


        }


        @Override
        protected Object doInBackground(String... url) {
            this.fetch_url = url[0];
            this.return_type = url[1];

            if(return_type.equals("json_object")) {
                return urlToJsonObject(this.fetch_url);
            } else {
                return urlToJsonArray(this.fetch_url);
            } 



        }




        private String convertStreamToString(InputStream is) {
           /*
            * To convert the InputStream to String we use the BufferedReader.readLine()
            * method. We iterate until the BufferedReader return null which means
            * there's no more data to read. Each line will appended to a StringBuilder
            * and returned as String.
            */

    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
           StringBuilder sb = new StringBuilder();

           String line = null;
           try {
               while ((line = reader.readLine()) != null) {
                   sb.append(line + "\n");
               }
           } catch (IOException e) {
               e.printStackTrace();
           } finally {
               try {
                   is.close();
               } catch (IOException e) {
                   e.printStackTrace();
               }
           }

           return sb.toString();
        }

    protected JSONObject urlToJsonObject(String url) {
        JSONObject arr = null;

        HttpClient httpclient = new DefaultHttpClient();

        // Prepare a request object
        HttpGet httpget = new HttpGet(url); 

        // Execute the request
        HttpResponse response;
        try {
            response = httpclient.execute(httpget);

            // Get hold of the response entity
            HttpEntity entity = response.getEntity();

            if (entity != null) {

                // A Simple JSON Response Read
                InputStream instream = entity.getContent();
                String result= convertStreamToString(instream);

                // A Simple JSONArray Creation
                arr = new JSONObject(result);

                // Closing the input stream will trigger connection release
                instream.close();


            }


        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return arr;
    }

    protected JSONArray urlToJsonArray(String url) {
        JSONArray arr = null;

        HttpClient httpclient = new DefaultHttpClient();

        // Prepare a request object
        HttpGet httpget = new HttpGet(url); 

        // Execute the request
        HttpResponse response;
        try {
            response = httpclient.execute(httpget);

            // Get hold of the response entity
            HttpEntity entity = response.getEntity();

            if (entity != null) {

                // A Simple JSON Response Read
                InputStream instream = entity.getContent();
                String result= convertStreamToString(instream);

                // A Simple JSONArray Creation
                arr = new JSONArray(result);

                // Closing the input stream will trigger connection release
                instream.close();


            }


        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return arr;
    }

    }
公共类服务器扩展异步任务{
私有字符串获取url;
私有字符串返回类型;
私人活动ct;
公共服务器(){
}
公共服务器(活动ct){
this.ct=ct;
}
@凌驾
受保护的void onPreExecute()
{
}
@凌驾
受保护对象doInBackground(字符串…url){
this.fetch_url=url[0];
this.return_type=url[1];
if(返回_type.equals(“json_对象”)){
返回urlToJsonObject(this.fetch_url);
}否则{
返回urlToJsonArray(this.fetch_url);
} 
}
私有字符串convertStreamToString(InputStream为){
/*
*要将InputStream转换为字符串,我们使用BufferedReader.readLine()命令
*我们迭代直到BufferedReader返回null,这意味着
*没有更多的数据可读取。每行都将附加到StringBuilder
*并作为字符串返回。
*/
BufferedReader reader=新的BufferedReader(新的InputStreamReader(is));
StringBuilder sb=新的StringBuilder();
字符串行=null;
试一试{
而((line=reader.readLine())!=null){
sb.追加(第+行“\n”);
}
}捕获(IOE异常){
e、 printStackTrace();
}最后{
试一试{
is.close();
}捕获(IOE异常){
e、 printStackTrace();
}
}
使某人返回字符串();
}
受保护的JSONObject urlToJsonObject(字符串url){
JSONObject arr=null;
HttpClient HttpClient=新的DefaultHttpClient();
//准备一个请求对象
HttpGet HttpGet=新的HttpGet(url);
//执行请求
HttpResponse响应;
试一试{
response=httpclient.execute(httpget);
//获取响应实体
HttpEntity=response.getEntity();
如果(实体!=null){
//一个简单的JSON响应读取
InputStream instream=entity.getContent();
字符串结果=convertStreamToString(流内);
//一个简单的JSONArray创建
arr=新的JSONObject(结果);
//关闭输入流将触发连接释放
流内关闭();
}
}捕获(客户端协议例外e){
//TODO自动生成的捕捉块
e、 printStackTrace();
}捕获(IOE异常){
//TODO自动生成的捕捉块
e、 printStackTrace();
}捕获(JSONException e){
//TODO自动生成的捕捉块
e、 printStackTrace();
}
返回arr;
}
受保护的JSONArray url到JSONArray(字符串url){
JSONArray arr=null;
HttpClient HttpClient=新的DefaultHttpClient();
//准备一个请求对象
HttpGet HttpGet=新的HttpGet(url);
//执行请求
HttpResponse响应;
试一试{
response=httpclient.execute(httpget);
//获取响应实体
HttpEntity=response.getEntity();
如果(实体!=null){
//一个简单的JSON响应读取
InputStream instream=entity.getContent();
字符串结果=convertStreamToString(流内);
//一个简单的JSONArray创建
arr=新JSONArray(结果);
//关闭输入流将触发连接释放
流内关闭();
}
}捕获(客户端协议例外e){
//TODO自动生成的捕捉块
e、 printStackTrace();
}捕获(IOE异常){
//TODO自动生成的捕捉块
e、 printStackTrace();
}捕获(JSONException e){
//TODO自动生成的捕捉块
e、 printStackTrace();
}
返回arr;
}
}
数据输入后,我使用getter和setter将其转换为我自己的模型。然后我想用这些结果更新我的ui,但由于某些原因,我总是收到空指针

例如:

  • 我有一个网格布局,我想填充多个相册
  • 首先,我从我的Web服务器获取这些记录
  • 然后处理每个相册
  • 然后,如果一个单独的相册被添加到GridLayout,它需要更新。而不是在阻塞ui时一次完成所有操作

从外部源获取数据并在加载ui时更新ui的一种好的中央方法是什么?有人能给我指点技术、教程、方法、见解等吗?我对此很好奇。

我看到你已经有了一个构造函数,所以你可以用它来接受需要更新的
活动的引用或
视图的引用。创建
异步任务时,传递
活动的引用
,然后调整构造函数以接受该引用。然后,您可以使用它调用
Activity
内的
onPostExecute()
onProgressUpdate()
方法,这些方法将在完成时更新
UI

看一个更好的例子