Android自定义listview在第一个位置显示最后一个项目 [英] Android custom listview display last item on first position
问题描述
当我将新产品插入列表视图时,该产品将显示在列表视图的最后一个位置.现在,我想在列表视图的第一个位置上显示最新添加的产品.例如,我的阵列产品最初在列表视图中显示为0> 1> 2> 3,现在我想以3> 2> 1> 0进行显示.我应该如何在代码中显示呢?感谢您的帮助.
when i insert a new product into listview, the product will be display on the last position in the listview. Now i want to display the most recent added product on the first position in my listview. For example, my array product initially display like this in the listview, 0 > 1 > 2 > 3, now i want to display like this, 3 > 2 > 1 > 0. how should i do it in my code? thanks for helping.
AllProductActivity.java
public class AllProductActivity extends ListActivity {
// Progress Dialog
//private ProgressDialog pDialog;
private SweetAlertDialog pDialog;
// Creating JSON Parser object
JSONParser2 jParser = new JSONParser2();
// array list that hold original data
ArrayList<HashMap<String, String>> productsList;
//Array list taht hold search result
ArrayList<HashMap<String, String>> searchResults;
ListView list;
LazyAdapter adapter;
// url to get all products list
private static String url_all_products = "http://gemini888.tk/test4/android_connect/get_all_products.php";
// JSON Node names
public static final String TAG_SUCCESS = "success";
public static final String TAG_PRODUCTS = "products";
public static final String TAG_PID = "uid";
public static final String TAG_NAME = "itemname";
public static final String TAG_PRICE = "price";
public static final String TAG_PATH = "path";
// products JSONArray
JSONArray products = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.all_products);
final EditText searchBox = (EditText) findViewById(R.id.searchBox);
list = (ListView)findViewById(android.R.id.list);
final TextView noProduct = (TextView) findViewById(android.R.id.empty);
//testing
if (android.os.Build.VERSION.SDK_INT > 9)
{
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
// Hashmap for ListView
productsList = new ArrayList<HashMap<String, String>>();
// Loading products in Background Thread
new LoadAllProducts().execute();
searchBox.addTextChangedListener(new TextWatcher() {
@Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
@Override
public void beforeTextChanged(CharSequence s, int start,
int count, int after) {
// TODO Auto-generated method stub
}
@Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
// get text in edittext
String searchString = searchBox.getText().toString();
int textLength = searchString.length();
//clear initial data
searchResults.clear();
for(int i=0; i<productsList.size();i++){
String listItemName = productsList.get(i).get(TAG_NAME).toString();
if(textLength<= listItemName.length()){
if(searchString.equalsIgnoreCase(listItemName.substring(0,textLength))){
searchResults.add(productsList.get(i));
}
}else {
noProduct.setText("no items found in our market! Please search again. Make sure all words are spelled correctly.");
}
}
adapter.notifyDataSetChanged();
}
});
// on seleting single product
// launching Edit Product Screen
list.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String pid = ((TextView) view.findViewById(R.id.pid)).getText()
.toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(),
ViewDetailsActivity.class);
// sending pid to next activity
in.putExtra(TAG_PID, pid);
// starting new activity and expecting some response back
startActivityForResult(in, 100);
}
});
}
// Response from Edit Product Activity
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// if result code 100
if (resultCode == 100) {
// if result code 100 is received
// means user edited/deleted product
// reload this screen again
Intent intent = getIntent();
finish();
startActivity(intent);
}
}
/**
* Background Async Task to Load all product by making HTTP Request
* */
class LoadAllProducts extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
@Override
protected void onPreExecute() {
super.onPreExecute();
//pDialog = new ProgressDialog(AllProductActivity.this);
//pDialog.setMessage("Loading products. Please wait...");
//pDialog.setIndeterminate(false);
//pDialog.setCancelable(false);
//pDialog.show();
pDialog = new SweetAlertDialog(AllProductActivity.this, SweetAlertDialog.PROGRESS_TYPE);
pDialog.getProgressHelper().setBarColor(Color.parseColor("#A5DC86"));
pDialog.setTitleText("Loading products. Please wait...");
//pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting All products from url
* */
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);
// Check your log cat for JSON reponse
Log.d("All Products: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
products = json.getJSONArray(TAG_PRODUCTS);
// looping through All Products
for (int i = 0; i < products.length(); i++) {
JSONObject c = products.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_PID);
String iname = c.getString(TAG_NAME);
String price = c.getString(TAG_PRICE);
String path = c.getString(TAG_PATH);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_PID, id);
map.put(TAG_NAME, iname);
map.put(TAG_PRICE, price);
map.put(TAG_PATH, path);
// adding HashList to ArrayList
productsList.add(map);
}
} else {
// no products found
// Launch Add New product Activity
Intent i = new Intent(getApplicationContext(),
NewProductActivity.class);
// Closing all previous activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
runOnUiThread(new Runnable() {
public void run() {
searchResults = new ArrayList<HashMap<String,String>>(productsList);
adapter=new LazyAdapter(AllProductActivity.this, searchResults);
list.setAdapter(adapter);
}
});
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// app icon in action bar clicked; go home
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
LazyAdapter.java
public class LazyAdapter extends BaseAdapter {
private Activity activity;
private ArrayList<HashMap<String, String>> data;
private static LayoutInflater inflater=null;
public ImageLoader imageLoader;
public LazyAdapter(Activity a, ArrayList<HashMap<String, String>> d) {
activity = a;
data=d;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
imageLoader=new ImageLoader(activity.getApplicationContext());
}
private class ViewHolder{
ImageView thumb_image;
TextView pid, itemname, price;
}
ViewHolder viewHolder;
@Override
public int getCount() {
return data.size();
}
@Override
public Object getItem(int position) {
return position;
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View vi=convertView;
if(convertView==null){
vi = inflater.inflate(R.layout.list_item, null);
viewHolder = new ViewHolder();
viewHolder.pid = (TextView)vi.findViewById(R.id.pid);
viewHolder.itemname = (TextView)vi.findViewById(R.id.name);
viewHolder.price = (TextView)vi.findViewById(R.id.price);
viewHolder.thumb_image = (ImageView)vi.findViewById(R.id.imageView1); //
vi.setTag(viewHolder);
}else
viewHolder=(ViewHolder) vi.getTag();
HashMap<String, String> song = new HashMap<String, String>();
song = data.get(position);
viewHolder.pid.setText(song.get(AllProductActivity.TAG_PID));
viewHolder.itemname.setText(song.get(AllProductActivity.TAG_NAME));
viewHolder.price.setText(song.get(AllProductActivity.TAG_PRICE));
imageLoader.DisplayImage(song.get(AllProductActivity.TAG_PATH), viewHolder.thumb_image); //
Animation animation;
animation = AnimationUtils.loadAnimation(activity, R.anim.left_to_right);
//animation = AnimationUtils.loadAnimation(activity, (position > lastPosition) ?
// R.anim.up_from_bottom : R.anim.down_from_top);
vi.startAnimation(animation);
return vi;
}
}
推荐答案
我认为您最好让服务器在SQL选择中使用"order by"来进行排序.
I think you'd better let the server do the sequencing,using "order by" in SQL selecting.
如果您在android应用中执行排序,则一旦数据库中的某些内容发生更改或业务逻辑得到改善,您就必须在应用中重写您的排序代码,并让所有用户在该应用上进行更新.您可以在上更改排序算法服务器随时随地.
If you do the sequencing in android app, once something changed in your database,or business logic improved,you have to rewrite your sequencing codes in app,and let all your users update there app.You can change the sequencing algorithm on server anytime you like.
这篇关于Android自定义listview在第一个位置显示最后一个项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!