Android ทำ Scroll ListView Endless Loading ให้เวลาเลื่อนลงมาแล้วค่อยโหลดข้อมูลเพิ่มยังไงครับ [มีภาพตัวอย่าง]
รบกวนช่วยดูโค้ดทีครับ
ผมลองเอามาใส่เพิ่มดู มันก็โหลดนะครับ เวลาเลื่อนscroll ลงมา แต่มันเหมือนโหลดข้อมูลมาใหม่ทั้งหมดเลยครับ
Code (Android-Java)
public class Tab_One extends Activity {
private ListView lstView;
private ImageAdapter imageAdapter;
public static final int DIALOG_DOWNLOAD_JSON_PROGRESS = 0;
private ProgressDialog mProgressDialog;
public int currentPage = 1;
public int displayPerPage = 10;
public int position_scroll = 0;
public boolean loading = false;
public boolean stoping = false;
ArrayList<HashMap<String, Object>> DataList = new ArrayList<HashMap<String, Object>>();
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tab1);
//new DownloadJSONAsync().execute();
ShowData();
}
public void ShowData()
{
// ListView and imageAdapter
lstView = (ListView) findViewById(R.id.list);
// lstView.setClipToPadding(false);
imageAdapter = new ImageAdapter(getApplicationContext());
lstView.setAdapter(imageAdapter);
// OnClick Item
lstView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> myAdapter, View myView, int position,long mylng) {
// TODO Auto-generated method stub
// Open Intent
Intent newActivity = new Intent(Tab_One.this,Tab_Two.class);
newActivity.putExtra("n_id",DataList.get(position).get("n_id").toString());
startActivity(newActivity);
}
});
// ONSCROLLLISTENER
lstView.setOnScrollListener(new OnScrollListener() {
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
@Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
int lastInScreen = firstVisibleItem + visibleItemCount;
if ((lastInScreen == totalItemCount) && !(loading)) {
if (stoping == false) {
// FETCH THE NEXT BATCH OF FEEDS
new DownloadJSONAsync().execute();
loading = true;
position_scroll = totalItemCount - 1;
}
}
}
});
}
@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DIALOG_DOWNLOAD_JSON_PROGRESS:
mProgressDialog = new ProgressDialog(this);
mProgressDialog.setMessage("Downloading.....");
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
mProgressDialog.setCancelable(true);
mProgressDialog.show();
return mProgressDialog;
default:
return null;
}
}
// Download JSON in Background
public class DownloadJSONAsync extends AsyncTask<Object, Integer, Object> {
protected void onPreExecute() {
super.onPreExecute();
showDialog(DIALOG_DOWNLOAD_JSON_PROGRESS);
}
@Override
protected Object doInBackground(Object... params) {
// TODO Auto-generated method stub
// INCREMENT CURRENT PAGE
//currentPage += 1;
String url = "http://10.0.2.2/project_one/android/get_news_update.php";
List<NameValuePair> parameter = new ArrayList<NameValuePair>();
parameter.add(new BasicNameValuePair("PerPage", String.valueOf(displayPerPage))); // Display Per Page
parameter.add(new BasicNameValuePair("currentPage", String.valueOf(currentPage)));
try {
JSONArray data = new JSONArray(getJSONUrl(url,parameter));
// if end last page
if(data.length() <=0 )
{
//currentPage = currentPage - 1;
loading = true;
}
else
{
displayPerPage += displayPerPage;
loading = false;
}
DataList = new ArrayList<HashMap<String, Object>>();
HashMap<String, Object> map;
for(int i = 0; i < data.length(); i++){
JSONObject c = data.getJSONObject(i);
map = new HashMap<String, Object>();
map.put("n_id", c.getString("n_id"));
map.put("n_title", c.getString("n_title"));
// Thumbnail Get ImageBitmap To Object
map.put("n_pic", (String)c.getString("n_pic"));
Bitmap newBitmap = loadBitmap(c.getString("n_pic"));
map.put("n_pic", newBitmap);
DataList.add(map);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Object result) {
ShowData();
// get listview current position - used to maintain scroll position
int currentPosition = lstView.getFirstVisiblePosition();
lstView.setSelection(currentPosition + position_scroll);
dismissDialog(DIALOG_DOWNLOAD_JSON_PROGRESS);
removeDialog(DIALOG_DOWNLOAD_JSON_PROGRESS);
}
}
class ImageAdapter extends BaseAdapter
{
private Context context;
public ImageAdapter(Context c)
{
// TODO Auto-generated method stub
context = c;
}
public int getCount() {
// TODO Auto-generated method stub
return DataList.size();
}
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
DataHolder holder = null;
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.activity_tab1_rows, null);
holder = new DataHolder();
holder.N_TITLE = (TextView) convertView.findViewById(R.id.title);
holder.N_PIC = (ImageView) convertView.findViewById(R.id.list_image);
convertView.setTag(holder);
}else{
holder = (DataHolder) convertView.getTag();
}
// Image
holder.N_PIC.getLayoutParams().height = 100;
holder.N_PIC.getLayoutParams().width = 100;
holder.N_PIC.setScaleType(ImageView.ScaleType.CENTER_CROP);
try
{
holder.N_PIC.setImageBitmap((Bitmap)DataList.get(position).get("n_pic"));
} catch (Exception e) {
// When Error
holder.N_PIC.setImageResource(android.R.drawable.ic_menu_report_image);
//Log.e(TAG, "Could not load pic from: " + DataList.get(position).get("n_pic"));
}
// Title
//holder.N_TITLE.setPadding(10, 0, 0, 0);
holder.N_TITLE.setText(DataList.get(position).get("n_title").toString());
//holder.N_TITLE.setText("ID : " + DataArr.get(position).get("ImageID"));
return convertView;
}
}
public class DataHolder {
TextView N_TITLE;
ImageView N_PIC;
}
/*** Get JSON Code from URL ***/
public String getJSONUrl(String url,List<NameValuePair> parameter) {
StringBuilder str = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
try {
httpPost.setEntity(new UrlEncodedFormEntity(parameter));
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 = "ERROR";
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) *****/
}
ประวัติการแก้ไข 2013-02-05 14:17:25
Date :
2013-02-04 19:04:05
By :
gravity99
ตอนนี้ผมรับไม่ได้ด้วยซิ ไม่งั้นจะได้ลองช่วยเอามารันดูหน่อยครับ หรือไม่ลองไล่ ๆ ดูครับ
Date :
2013-02-05 09:37:57
By :
mr.win
ตอนนี้ พอได้ในระดับนึงแล้วครับ คือลองเอาตัวอย่างจาก Android Split Page Data มาผสมกัน (โค้ดล่าสุดที่ทำ อยู่คอมเม้นก่อนหน้าครับ ผมกดแก้ไขไป )
ผลที่ได้คือ เวลาเลื่อน scroll ลงมาสุดมันจะโหลดเปลี่ยนหน้าครับ แต่ที่อยากได้จริงๆคือไม่ต้องเปลี่ยนหน้า ให้มันโหลดข้อมูลใหม่มา แล้วคงข้อมูลเดิมไว้ อ่ะครับ
เลยอยากขอคำแนะนำหน่อยครับ ว่ามีวิธีไหนบ้างที่จะเก็บข้อมูลเก่าไว้ แล้วไปดึงข้อมูลใหม่มาโชว์เพิ่ม อ่ะครับ
Date :
2013-02-05 14:39:17
By :
gravity99
Load balance : Server 03