title: Android custom listview display last item on first position
body: <p>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.</p>
  
  <p><strong>AllProductActivity.java</strong></p>
  
  <pre><code>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&lt;HashMap&lt;String, String&gt;&gt; productsList;
  
  //Array list taht hold search result
  ArrayList&lt;HashMap&lt;String, String&gt;&gt; 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 &gt; 9)
      {
      StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
      StrictMode.setThreadPolicy(policy);
      }
  
      // Hashmap for ListView
      productsList = new ArrayList&lt;HashMap&lt;String, String&gt;&gt;();
  
      // 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&lt;productsList.size();i++){
                  String listItemName = productsList.get(i).get(TAG_NAME).toString();
                  if(textLength&lt;= 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&lt;?&gt; 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&lt;String, String, String&gt; {
  
      /**
       * 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&lt;NameValuePair&gt; params = new ArrayList&lt;NameValuePair&gt;();
          // 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 &lt; 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&lt;String, String&gt; map = new HashMap&lt;String, String&gt;();
  
                      // adding each child node to HashMap key =&gt; 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&lt;HashMap&lt;String,String&gt;&gt;(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); 
      }
  }
  </code></pre>
  
  <p><strong>LazyAdapter.java</strong></p>
  
  <pre><code>public class LazyAdapter extends BaseAdapter {
  
  private Activity activity;
  private ArrayList&lt;HashMap&lt;String, String&gt;&gt; data;
  private static LayoutInflater inflater=null;
  public ImageLoader imageLoader;
  
  public LazyAdapter(Activity a, ArrayList&lt;HashMap&lt;String, String&gt;&gt; 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&lt;String, String&gt; song = new HashMap&lt;String, String&gt;();
      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 &gt; lastPosition) ?
          //  R.anim.up_from_bottom : R.anim.down_from_top);
      vi.startAnimation(animation);
  
      return vi;
  }
  
  }
  </code></pre>