Question

I successfully get json data and already show it in a listview. Now my requirement is to set data one entry at a time in list on click of add button.

Here is my main activity in which data is set to listview

public class MainActivity extends ListActivity { 
private ProgressDialog pDialog;
// URL to get contacts JSON
private static String url = "";

// JSON Node names
private static final String TAG_DATA = "data";
private static final String TAG_OWNER = "owner";
private static final String TAG_ID = "id";
private static final String TAG_LOGIN = "login";

// contacts JSONArray
JSONArray data = null;

// Hashmap for ListView
ArrayList<HashMap<String, String>> dataList;



@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    dataList = new ArrayList<HashMap<String, String>>();

    ListView lv = getListView();

    // Listview on item click listener
    lv.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view,
                int position, long id1) {
            // TODO Auto-generated method stub

            // getting values from selected ListItem
            String login = ((TextView) view.findViewById(R.id.login))
                        .getText().toString();
            String id = ((TextView) view.findViewById(R.id.id))
                        .getText().toString();

             // Starting single contact activity
             Intent in = new Intent(getApplicationContext(),
                       SingleContactActivity.class);

            in.putExtra(TAG_ID, id);
            in.putExtra(TAG_LOGIN, login);

            startActivity(in);

        }
    });

    lv.setOnItemLongClickListener(new OnItemLongClickListener() {

        public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
                int pos, long id) {
            // TODO Auto-generated method stub
            Log.v("long clicked","pos: " + pos);
            removeItemFromList(pos);   
            return true;
        }

        private void removeItemFromList(int pos) {
            // TODO Auto-generated method stub
            final int deletePosition = pos;

               AlertDialog.Builder alert = new AlertDialog.Builder(MainActivity.this);

               alert.setTitle("Delete");
               alert.setMessage("Do you want delete this item?");
               alert.setPositiveButton("YES", new OnClickListener() {

                   @Override
                   public void onClick(DialogInterface dialog, int which) {
                       // TOD  Auto-generated method stub

                           // main code on after clicking yes
                           dataList.remove(deletePosition);
                           setListAdapter(getListAdapter());
                   }
               });
               alert.setNegativeButton("CANCEL", new OnClickListener() {
                   @Override
                   public void onClick(DialogInterface dialog, int which) {
                       // TODO Auto-generated method stub
                       dialog.dismiss();
                   }
               });

               alert.show();
        }
    });
    // Calling async task to get json
    new GetData().execute();
}



/**
 * Async task class to get json by making HTTP call
 * */
private class GetData extends AsyncTask<Void, Void, Void> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        // Showing progress dialog
        pDialog = new ProgressDialog(MainActivity.this);
        pDialog.setMessage("Please wait...");
        pDialog.setCancelable(false);
        pDialog.show();

    }

    @Override
    protected Void doInBackground(Void... arg0) {
        // Creating service handler class instance
        ServiceHandler sh = new ServiceHandler();

        // Making a request to url and getting response
        String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);

        Log.d("Response: ", "> " + jsonStr);

        if (jsonStr != null) {
            try {
                JSONArray json = new JSONArray(jsonStr);

                Log.d("in json object block", jsonStr);

                // looping through All Contacts
                for(int i=0;i<json.length();i++){                        
                    HashMap<String, String> map = new HashMap<String, String>();    
                    JSONObject e = json.getJSONObject(i);
                    // adding contact to contact list
                    JSONObject  owner = e.getJSONObject("owner");
                  //  map.put("id",  String.valueOf(i));
                    map.put("login", "Login is:" + owner.getString("login"));
                    map.put("id", "ID is: " +  owner.getString("id"));
                   // map.put("owner", "OWNER is" + e.getString("") );
                    dataList.add(map);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        } else {
            Log.e("ServiceHandler", "Couldn't get any data from the url");
        }

        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        super.onPostExecute(result);
        // Dismiss the progress dialog
        if (pDialog.isShowing())
            pDialog.dismiss();
        /**
         * Updating parsed JSON data into ListView
         * */
        ListAdapter adapter = new SimpleAdapter(
                MainActivity.this, dataList,
                R.layout.list_item, new String[] { TAG_OWNER, TAG_LOGIN,
                        TAG_ID }, new int[] { R.id.owner,
                        R.id.login, R.id.id });
       setListAdapter(adapter);

       }
     }


}
Was it helpful?

Solution

create a button on main layout. Implement onclicklistener for the button and call populateListView() inside the onlick method.

Creat a new list. When you click a button add an item to a new list. call notifydatasetchanged(). When you click a button check whether the item is already added in the new list or not. Use newly created list in your adapter so that every time new item will be added.

Thanks

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top