2016-05-13 67 views
0

我想解析包含字符串和圖像的JSON對象。我的代碼正在工作,但它加載圖像太慢。我想加載另一個asynctask或服務的圖像,以減少加載時間。我怎樣才能做到這一點?哪一個是最好的方法使用asynctask或服務?這裏是我的代碼JSON解析並獲取android中的圖像

public class Traffic extends Fragment { 
private ListView listView; 
private HttpURLConnection connection = null; 
private BufferedReader bufferedReader = null; 
private InputStream inputStream = null; 
private ArrayList<TrafficModelClass> trafficList; 
private TrafficAdapter trafficAdapter; 
private View view; 
private ProgressDialog progressDialog; 
@Nullable 
@Override 
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 
    view = inflater.inflate(R.layout.traffic,container,false); 
    listView = (ListView) view.findViewById(R.id.trafficListView); 
    progressDialog = ProgressDialog.show(view.getContext(),"" ,"Wait..." , true); 
    new GetTrafficNews().execute(); 
    trafficList = new ArrayList<TrafficModelClass>(); 
    trafficAdapter = new TrafficAdapter(view.getContext() , R.id.trafficListView , trafficList); 
    listView.setAdapter(trafficAdapter); 
    return view; 
} 
public class GetTrafficNews extends AsyncTask<String , Void , String> { 


    @Override 
    protected String doInBackground(String... params) { 
     try { 
      URL url = new URL("http://www.dtexeshop.com/Journalist/GetTrafficNews.php"); 
      connection = (HttpURLConnection) url.openConnection(); 
      connection.setRequestMethod("POST"); 
      connection.setDoInput(true); 
      inputStream = connection.getInputStream(); 
      bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1")); 
      StringBuffer stringBuffer = new StringBuffer(); 
      String line=""; 

      while((line=bufferedReader.readLine()) != null){ 
       stringBuffer.append(line); 
      } 

      String finalJson = stringBuffer.toString(); 
      JSONObject parentJson = new JSONObject(finalJson); 
      JSONArray parentJsonArray = parentJson.getJSONArray("traffic"); 

      for (int i = 0; i < parentJsonArray.length(); i++) { 
       JSONObject finalJsonObject = parentJsonArray.getJSONObject(i); 

       TrafficModelClass modelClass = new TrafficModelClass(); 
       modelClass.setUserName(finalJsonObject.getString("UserName")); 
       modelClass.setDateTime(finalJsonObject.getString("DateTime")); 
       modelClass.setHeadline(finalJsonObject.getString("Headline")); 
       String string_url ="http://www.dtexeshop.com/Journalist/images/"+ finalJsonObject.getString("ImageName"); 
       URL urlImage = new URL(string_url); 
       Bitmap image = BitmapFactory.decodeStream(urlImage.openConnection().getInputStream()); 
       modelClass.setBitmapImage(image); 
       modelClass.setDescription(finalJsonObject.getString("Description")); 

       trafficList.add(modelClass); 
       if(i==1){ 
        progressDialog.dismiss(); 
       } 
      } 
      inputStream.close(); 

     } catch (MalformedURLException e) { 
      e.printStackTrace(); 
     } catch (ProtocolException e) { 
      e.printStackTrace(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } catch (JSONException e) { 
      e.printStackTrace(); 
     }finally { 
      if (connection != null) { 
       connection.disconnect(); 
      } 
      if (bufferedReader != null) { 
       try { 
        bufferedReader.close(); 
       } catch (IOException e) { 
        e.printStackTrace(); 
       } 
      } 
     } 
     return null; 
    } 

    @Override 
    protected void onPreExecute() { 
     super.onPreExecute(); 
    } 

    @Override 
    protected void onPostExecute(String s) { 
     trafficAdapter.notifyDataSetChanged(); 
     progressDialog.dismiss(); 
    } 
} 

}

回答

0

我會建議你使用畢加索庫來獲取圖像,這是給你完美的一個。它不會延遲加載時間,它會根據網絡加載圖像。

只需使用這行代碼:

Picasso.with(context).load("url").into(imageview); 

,並添加這種依賴於你的應用程序。

compile 'com.squareup.picasso:picasso:2.5.2' 
0

首先,你不應該叫progressDialog.dismiss()在非UI線程,在UI組件的所有操作都應該在UI線程來完成。在我看來,最常見和最現代的方法是用RxJava框架來執行這些操作。它可以讓你以功能性的方式編寫這樣的運算符。但是一旦你熟悉它,你就不想停止使用它。我的解決辦法是這樣的:

createDownloadObservable(url) // download json 
    .map(json -> parseJson(json) // parse json text into a json object 
    .map(jsonObject -> extractTrafficModel(jsonObject))) // extract list of TrafficModels from jsonObject 
    .flatMap(trafficModelList -> Observable.from(trafficModelList)) // push every TrafficModel item in a pool 
    .map(trafficModelItem -> downloadImage(trafficModelItem)) // download and set image for each TrafficModel item 
    .toList() // aggreagate all items in a list 
    .subscribe(new Subscriber() { 
     public void onNext(List<TrafficModel> trafficModelList) { 
      // here you are! You can do what you want to with this traffic model list 
     } 

     public void onError(Throable e) { 
      // if some error appeared while passing the algorithm, you can process it here 
     } 
    }) 
+0

也許一些線路是缺少的,你可以請編輯它... –