|
|
|
สอบถาม Android POST API + รับค่า Image URL มาแสดงบน listview Imageview ช้ามากครับ |
|
|
|
|
|
|
|
ผมทำการ 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
|
|
|
|
|
Date :
2019-10-30 10:33:35 |
By :
ilikeit |
View :
577 |
Reply :
3 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
น่าจะชเาเพราะตัว Emulator นะครับ
|
|
|
|
|
Date :
2019-10-30 16:01:30 |
By :
mr.win |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
ครับ
ตอนนี้เปลี่ยนไปใช้ piccaso ดีขึ้นเยอะเยอะครับเลย โค้ดสั้นกว่า โหลดไวกว่า
^^
ขอบคุณครับ
|
|
|
|
|
Date :
2019-10-31 11:27:52 |
By :
ilikeit |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Date :
2019-10-31 14:56:40 |
By :
mr.win |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Load balance : Server 05
|