2

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;
}

}
cf chan
  • 108
  • 1
  • 6

3 Answers3

3

To do this, you could simply change your getItem() logic. You can do it by,

@Override
public Object getItem(int position) {
     return getCount() - position - 1;
}

Say, if total count is 2 then, {indexes : 0, 1}

For the first item (index = 0) :

2 - 0 - 1 = 1 (The last index)

For the second item (index = 1) :

2 - 1 - 1 = 0 (The first index)

siriscac
  • 1,699
  • 12
  • 21
2

I think you'd better let the server do the sequencing,using "order by" in SQL selecting.

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.

Ai Hao
  • 102
  • 5
1

I solved (made a hack for?) a similar problem by adding the new item to the 0 index of an ArrayList, which updates a ListView through an ArrayAdapter.

I do not read from the list later on however, so the list structure might be whack, but all I care about is the visual result of adding the newest entry on top of a 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);

and later on..

//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();
Kyrre
  • 670
  • 1
  • 5
  • 19