当我将新产品插入列表视图时,产品将显示在列表视图中的最后一个位置。现在我想在listview的第一个位置显示最新添加的产品。例如,我的数组产品最初在列表视图中显示如下,0> 1> 2> 3,现在我想要这样显示,3> 2> 1>我应该如何在我的代码中执行此操作?谢谢你的帮助。
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;
}
}
答案 0 :(得分:3)
为此,您只需更改getItem()
逻辑即可。你可以这样做,
@Override
public Object getItem(int position) {
return getCount() - position - 1;
}
比方说,如果总计数是2,则{index:0,1}
对于第一项(index = 0):
2 - 0 - 1 = 1(最后一个指数)
对于第二项(index = 1):
2 - 1 - 1 = 0(第一个指数)
答案 1 :(得分:2)
我认为你最好让服务器进行排序,使用&#34;命令&#34;在SQL中选择。
如果您在Android应用程序中进行排序,一旦数据库中的内容发生变化或业务逻辑得到改善,您必须在应用程序中重写您的排序代码,并让所有用户在那里更新app.You可以更改排序算法服务器随时随地。
答案 2 :(得分:1)
我通过将新项添加到ArrayList的0索引来解决(做了一个hack for?)类似的问题,ArrayList通过ArrayAdapter更新ListView。
我之后没有从列表中读取,因此列表结构可能很糟糕,但我关心的是在ListView顶部添加最新条目的可视结果
ListView mListView = (ListView) findViewById(R.id.mListView);
//new ArrayAdapter using the activity, a design element for the list, and the list with data
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, list);
//assign the adapter to the listView
mListView.setAdapter(adapter);
以及稍后......
//add the entry to the 0th index of the list. This will make the entry appear at the top
list.add(0,""+ resetsToList +": "+currentCount+"");
//tell the adapter that the dataset has changed. This will update the listView
adapter.notifyDataSetChanged();