AsynkTask's mission, but how does it open up a picture upload?



  • Here's the code.

    public class PromoProductsActivity extends AppCompatActivity {
    

    private static final String ServletURL = "здесь адрес сервера";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_promo_products);

    // получаем Intent и название магазина, которое он хранит
    Intent intent = getIntent();
    String shopName = intent.getStringExtra("shopName");
    
    new ServletTask().execute(shopName);
    

    }

    private class ServletTask extends AsyncTask<String, Void, List<Product>>{

    @Override
    protected List&lt;Product&gt; doInBackground(String... params) {
        //String shopName = params[0];
        String shopName = "all";
        List&lt;Product&gt; productList = new ArrayList&lt;&gt;();
        try {
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpGet httpGet = new HttpGet(ServletURL +shopName);
    
            HttpResponse httpResponse = httpClient.execute(httpGet);
            HttpEntity httpEntity = httpResponse.getEntity();
            String outputString = EntityUtils.toString(httpEntity);
            JSONArray output = new JSONArray(outputString);
            for (int i = 0; i &lt; output.length(); i++) {
                try {
                    JSONObject object = (JSONObject) output.get(i);
                    Product product = new Product(object.getString("productName"), object.getString("newPrice"),
                            object.getString("startPromo"), object.getString("endPromo"), object.getString("urlPhoto"));
                    productList.add(product);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return productList;
    }
    
    @Override
    protected void onPostExecute(List&lt;Product&gt; productList) {
        LinearLayout itemLayout = (LinearLayout) findViewById(R.id.itemLayout);
        LayoutInflater inflater = getLayoutInflater();
    
        for (Product p : productList){
            View item = inflater.inflate(R.layout.item, itemLayout, false);
            // поле с названием продукта
            TextView product_name_tv = (TextView) item.findViewById(R.id.product_name_tv);
            product_name_tv.setText(p.getProductName());
            // поле с новой ценой продукта
            TextView new_price_tv = (TextView) item.findViewById(R.id.new_price_tv);
            new_price_tv.setText(p.getNewPrice());
            // поле с датой начала акции
            TextView start_promo_tv = (TextView) item.findViewById(R.id.start_promo_tv);
            start_promo_tv.setText(p.getProductName());
            // поле с датой конца акции
            TextView end_promo_tv = (TextView) item.findViewById(R.id.end_promo_tv);
            end_promo_tv.setText(p.getProductName());
            // поле с картинкой товара
            ImageView product_photo = (ImageView) item.findViewById(R.id.product_photo);
            try {
                product_photo.setImageBitmap(BitmapFactory.decodeStream(new URL(p.getUrlPhoto()).openConnection().getInputStream()));
            } catch (IOException e) {
                e.printStackTrace();
            }
    
            // устанавливаем размеры каждого пункта с товаром и отображаем на экране
            item.getLayoutParams().width = ViewGroup.LayoutParams.MATCH_PARENT;
            itemLayout.addView(item);
        }
    }
    

    }

    In this case, receive the NetworkOnMainThreadException, which means another flow?
    If I write from the lamp

    product_photo.setImageURI(Uri.parse(p.getUrlPhoto()));

    It's kind of working, but instead of a picture of the crabs. The glass says it can't decode the picture.
    Can you tell me how to download the ImageView picture?



  • Method onPostExecute mainly (UI) flow. We'll sit back when you're online.

    product_photo.setImageBitmap(BitmapFactory.decodeStream(new URL(p.getUrlPhoto()).openConnection().getInputStream()));

    You're right. NetworkOnMainThreadException

    If you need to look at it. ImageView You have two options:

    1. One more challenge, too, doInBackground I need you to download the picture to make her. ImageView Total onPostExecute♪ That's it. bad A way.
    2. Using one of the libraries for purposes. For example https://github.com/nostra13/Android-Universal-Image-Loader :

      ImageLoader imageLoader = ImageLoader.getInstance();
      imageLoader.displayImage(imageUri, imageView);
      

    This and similar libraries will take care of the flow, asynchronity and other. And they'll cut the code once.




Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2