Register Register Member Login Member Login Member Login Forgot Password ??
PHP , ASP , ASP.NET, VB.NET, C#, Java , jQuery , Android , iOS , Windows Phone
 

Registered : 109,027

HOME > Mobile > Mobile Forum > สอบถาม Android POST API + รับค่า Image URL มาแสดงบน listview Imageview ช้ามากครับ



 

สอบถาม Android POST API + รับค่า Image URL มาแสดงบน listview Imageview ช้ามากครับ

 



Topic : 134431



โพสกระทู้ ( 288 )
บทความ ( 0 )



สถานะออฟไลน์




ผมทำการ call api จากนั้น นำ url รูปภาพจาก url แสดงบนหน้าแอปผ่าน listview + Imageview

ประมาณ 5-6 ราย ซึ่งไฟล์ รูปภาพขนาดไม่เกิน 100kb แต่ผมเจอปัญหาการโหลดที่ช้ามากก หน่วงประมาณ 5 วินาทีหลังกดเปิดเมนู

อันนี้มันเกิดจากอะไรหรอครับ

Code (Java)
package com.example.appname;


import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;


/**
 * A simple {@link Fragment} subclass.
 */
public class FeaturedFragment extends Fragment {
    View view;
    private String base_url = "https://domain.com/api";
    private String token_api = "xxx";
    private String MID = "";
    public static final int DIALOG_DOWNLOAD_JSON_PROGRESS = 0;
    private ProgressDialog mProgressDialog;
    ArrayList<HashMap<String, Object>> MyArrList;
    private JSONArray fResult;
    private static Context fContext;
    private List<Bitmap> fPicList;


    public FeaturedFragment(){

    }

    public static FeaturedFragment init(Context context) {
        FeaturedFragment frag = new FeaturedFragment();
        fContext = context;
        return frag;
        // Required empty ublic constructor
    }

    @SuppressLint("NewApi")
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        view = inflater.inflate(R.layout.fragment_featured, container, false);


        return view;
    }
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // Permission StrictMode
        if (android.os.Build.VERSION.SDK_INT > 9) {
            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
            StrictMode.setThreadPolicy(policy);
        }
        new DownloadJSONFileAsync().execute(); // Download JSON File


    }


    // Show All Content
    public void ShowAllContent(ProgressDialog dialog)
    {
        Log.e("Show all content", "content");
        final ListView lstView1 = (ListView)view.findViewById(R.id.listView1);
        lstView1.setAdapter(new ImageAdapter( fContext, fResult, fPicList)); //ตอนแรกเป็นแบบนี้
        dialog.dismiss();
    }



    public static class ImageAdapter extends BaseAdapter
    {
        private Context context;
        private ArrayList<HashMap<String, Object>> MyArr = new ArrayList<HashMap<String, Object>>();
        private JSONArray result;
        private List<Bitmap> pictures;

        public ImageAdapter(Context ctx, JSONArray result, List<Bitmap> pics) {
            context = ctx;
            this.result = result;
            pictures = pics;
        }

        public int getCount() {
            // TODO Auto-generated method stub
            return result.length();
        }

        public Object getItem(int position) {
            // TODO Auto-generated method stub
            try {
                return result.getJSONObject(position);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return null;
        }

        public long getItemId(int position) {
            // TODO Auto-generated method stub
            try {
                return result.getJSONObject(position).getLong("Re_id");
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return 0;
        }
        public View getView(int position, View convertView, ViewGroup parent) {
            // TODO Auto-generated method stub
            //Log.e("Log","test");


            LayoutInflater inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

            try {
                JSONObject obj = result.getJSONObject(position);

                if (convertView == null) {
                    convertView = inflater.inflate(R.layout.featured_layout, null);
                }
                ImageView img = convertView.findViewById(R.id.ImageStore);
                TextView storetitle = convertView.findViewById(R.id.storetitle);
              
                img.setImageBitmap(pictures.get(position));
                storetitle.setText(obj.getString("Title"));




                return convertView;
            } catch (JSONException e) {
                e.printStackTrace();
            }




            return convertView;
        }

    }



    // Download JSON in Background
    public class DownloadJSONFileAsync extends AsyncTask<String, Void, Void> {

        protected void onPreExecute() {
            super.onPreExecute();
             //showDialog(DIALOG_DOWNLOAD_JSON_PROGRESS);
            mProgressDialog = new ProgressDialog( getActivity() );
            mProgressDialog.setMessage("Loading.....");
            mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
            mProgressDialog.setCancelable(true);
            mProgressDialog.show();
        }



        @Override
        protected Void doInBackground(String... params) {
            // TODO Auto-generated method stub

            String url2 = base_url+"/featured.php";
            HttpClient client2 = new DefaultHttpClient();
            HttpPost httpPost2 = new HttpPost(url2);

            List<NameValuePair> params2 = new ArrayList<NameValuePair>();
            params2.add(new BasicNameValuePair("action", "getFeatured"));
            params2.add(new BasicNameValuePair("token_api", token_api));


            JSONArray data;
            try {
                data = new JSONArray(getJSONUrl(url2,params2));
                fResult = data;
                MyArrList = new ArrayList<HashMap<String, Object>>();
                HashMap<String, Object> map;
                fPicList = new ArrayList<>();
                for(int i = 0; i < data.length(); i++){
                    JSONObject c = data.getJSONObject(i);

                    map = new HashMap<String, Object>();
                      map.put("Title", (String)c.getString("Title"));

                    // Thumbnail Get ImageBitmap To Object
                    map.put("ImagePathThum", (String)c.getString("Image"));
                    map.put("ImageThumBitmap", (Bitmap)loadBitmap(c.getString("Image")));

                    MyArrList.add(map);


                    URL url = null;
                    try {
                        url = new URL(data.getJSONObject(i).getString("Image"));
                        Bitmap bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
                        fPicList.add(bmp);
                    } catch (MalformedURLException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }

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

            return null;
        }

        protected void onPostExecute(Void unused) {
            ShowAllContent(mProgressDialog);
  
        }



    }


    /*** Get JSON Code from URL ***/
    public String getJSONUrl(String url, List<NameValuePair> params) {
        StringBuilder str = new StringBuilder();
        HttpClient client = new DefaultHttpClient();
        HttpPost HttpPost = new HttpPost(url);
        try {
            HttpPost.setEntity(new UrlEncodedFormEntity(params));
            HttpResponse response = client.execute(HttpPost);
            StatusLine statusLine = response.getStatusLine();
            int statusCode = statusLine.getStatusCode();
            if (statusCode == 200) { // Download OK
                HttpEntity entity = response.getEntity();
                InputStream content = entity.getContent();
                BufferedReader reader = new BufferedReader(new InputStreamReader(content));
                String line;
                while ((line = reader.readLine()) != null) {
                    str.append(line);
                }
            } else {
                Log.e("Log", "Failed to download file..");
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return str.toString();
    }


    /***** Get Image Resource from URL (Start) *****/
    private static final String TAG = "Image";
    private static final int IO_BUFFER_SIZE = 4 * 1024;
    public static Bitmap loadBitmap(String url) {
        Bitmap bitmap = null;
        InputStream in = null;
        BufferedOutputStream out = null;

        try {
            in = new BufferedInputStream(new URL(url).openStream(), IO_BUFFER_SIZE);

            final ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
            out = new BufferedOutputStream(dataStream, IO_BUFFER_SIZE);
            copy(in, out);
            out.flush();

            final byte[] data = dataStream.toByteArray();
            BitmapFactory.Options options = new BitmapFactory.Options();
            //options.inSampleSize = 1;

            bitmap = BitmapFactory.decodeByteArray(data, 0, data.length,options);
        } catch (IOException e) {
            Log.e(TAG, "Could not load Bitmap from: " + url);
        } finally {
            closeStream(in);
            closeStream(out);
        }

        return bitmap;
    }

    private static void closeStream(Closeable stream) {
        if (stream != null) {
            try {
                stream.close();
            } catch (IOException e) {
                android.util.Log.e(TAG, "Could not close stream", e);
            }
        }
    }

    private static void copy(InputStream in, OutputStream out) throws IOException {
        byte[] b = new byte[IO_BUFFER_SIZE];
        int read;
        while ((read = in.read(b)) != -1) {
            out.write(b, 0, read);
        }
    }
    /***** Get Image Resource from URL (End) *****/

    /* @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }
*/



}





Tag : Mobile, HTML, Ajax, Android, Mobile









ประวัติการแก้ไข
2019-10-30 11:22:23
Move To Hilight (Stock) 
Send To Friend.Bookmark.
Date : 2019-10-30 10:33:35 By : ilikeit View : 515 Reply : 3
 

 

No. 1



โพสกระทู้ ( 74,058 )
บทความ ( 838 )

สมาชิกที่ใส่เสื้อไทยครีเอท

สถานะออฟไลน์
Twitter Facebook

น่าจะชเาเพราะตัว Emulator นะครับ






แสดงความคิดเห็นโดยอ้างถึง ความคิดเห็นนี้
Date : 2019-10-30 16:01:30 By : mr.win
 


 

No. 2



โพสกระทู้ ( 288 )
บทความ ( 0 )



สถานะออฟไลน์


ครับ
ตอนนี้เปลี่ยนไปใช้ piccaso ดีขึ้นเยอะเยอะครับเลย โค้ดสั้นกว่า โหลดไวกว่า

^^

ขอบคุณครับ
แสดงความคิดเห็นโดยอ้างถึง ความคิดเห็นนี้
Date : 2019-10-31 11:27:52 By : ilikeit
 

 

No. 3



โพสกระทู้ ( 74,058 )
บทความ ( 838 )

สมาชิกที่ใส่เสื้อไทยครีเอท

สถานะออฟไลน์
Twitter Facebook


แสดงความคิดเห็นโดยอ้างถึง ความคิดเห็นนี้
Date : 2019-10-31 14:56:40 By : mr.win
 

   

ค้นหาข้อมูล


   
 

แสดงความคิดเห็น
Re : สอบถาม Android POST API + รับค่า Image URL มาแสดงบน listview Imageview ช้ามากครับ
 
 
รายละเอียด
 
ตัวหนา ตัวเอียง ตัวขีดเส้นใต้ ตัวมีขีดกลาง| ตัวเรืองแสง ตัวมีเงา ตัวอักษรวิ่ง| จัดย่อหน้าอิสระ จัดย่อหน้าชิดซ้าย จัดย่อหน้ากึ่งกลาง จัดย่อหน้าชิดขวา| เส้นขวาง| ขนาดตัวอักษร แบบตัวอักษร
ใส่แฟลช ใส่รูป ใส่ไฮเปอร์ลิ้งค์ ใส่อีเมล์ ใส่ลิ้งค์ FTP| ใส่แถวของตาราง ใส่คอลัมน์ตาราง| ตัวยก ตัวห้อย ตัวพิมพ์ดีด| ใส่โค้ด ใส่การอ้างถึงคำพูด| ใส่ลีสต์
smiley for :lol: smiley for :ken: smiley for :D smiley for :) smiley for ;) smiley for :eek: smiley for :geek: smiley for :roll: smiley for :erm: smiley for :cool: smiley for :blank: smiley for :idea: smiley for :ehh: smiley for :aargh: smiley for :evil:
Insert PHP Code
Insert ASP Code
Insert VB.NET Code Insert C#.NET Code Insert JavaScript Code Insert C#.NET Code
Insert Java Code
Insert Android Code
Insert Objective-C Code
Insert XML Code
Insert SQL Code
Insert Code
เพื่อความเรียบร้อยของข้อความ ควรจัดรูปแบบให้พอดีกับขนาดของหน้าจอ เพื่อง่ายต่อการอ่านและสบายตา และตรวจสอบภาษาไทยให้ถูกต้อง

อัพโหลดแทรกรูปภาพ

Notice

เพื่อความปลอดภัยของเว็บบอร์ด ไม่อนุญาติให้แทรก แท็ก [img]....[/img] โดยการอัพโหลดไฟล์รูปจากที่อื่น เช่นเว็บไซต์ ฟรีอัพโหลดต่าง ๆ
อัพโหลดแทรกรูปภาพ ให้ใช้บริการอัพโหลดไฟล์ของไทยครีเอท และตัดรูปภาพให้พอดีกับสกรีน เพื่อความโหลดเร็วและไฟล์ไม่ถูกลบทิ้ง

   
  เพื่อความปลอดภัยและการตรวจสอบ กระทู้ที่แทรกไฟล์อัพโหลดไฟล์จากที่อื่น อาจจะถูกลบทิ้ง
 
โดย
อีเมล์
บวกค่าให้ถูก
<= ตัวเลขฮินดูอารบิก เช่น 123 (หรือล็อกอินเข้าระบบสมาชิกเพื่อไม่ต้องกรอก)







Exchange: นำเข้าสินค้าจากจีน, Taobao, เฟอร์นิเจอร์, ของพรีเมี่ยม, ร่ม, ปากกา, power bank, แฟลชไดร์ฟ, กระบอกน้ำ

Load balance : Server 04
ThaiCreate.Com Logo
© www.ThaiCreate.Com. 2003-2024 All Rights Reserved.
ไทยครีเอทบริการ จัดทำดูแลแก้ไข Web Application ทุกรูปแบบ (PHP, .Net Application, VB.Net, C#)
[Conditions Privacy Statement] ติดต่อโฆษณา 081-987-6107 อัตราราคา คลิกที่นี่