0

I'm a Newbie, so, there are a lot of things that I don't know.

  • I'm building my first application, using PHP and Java, and my Database is allocated on Phpmyadmin.

  • To get the data that I want, I have to create a PHP Query, and output everything using Json. To get the Json Data I use Java.

  • I have been searching about my question for hours, and unfortunately, I couldn't find a specific way to what I want, in my situation. I would like to update my ListView automatically when a new record is inserted into my Database.

  • Lets imagine that you are watching a Listview, and when the owner from the application inserts a new record on the table that shows the Listview data, automatically the Listview shows a new record.

  • My problem is that I am using Json to get the Data, and I can't change that. And I would like to find a solution for that.

  • So, I would like to know if it is possible or not to do that. I will post my full code here:

Json Tags - Calling the URL and the Json Tags here:

public class ListUsersActivity extends ListActivity {

    private ProgressDialog pDialog;
    private ImageView img;
    // URL to get contacts JSON
    private static String url = "http://192.168.1.67/example/db_config.php";

    // JSON Node names
    private static final String TAG_CONTACTS = "contacts";
    private static final String TAG_ID = "id";
    private static final String TAG_NAME = "name";
    private static final String TAG_IMAGE = "pic_url";
    private static final String TAG_USERID = "user_id";
    private static final String TAG_BIRTH_DATE = "birth_date";

    // contacts JSONArray
    JSONArray contacts = null;

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

OnCreate - Calling the Asynctask function, and creating a new arraylist for my Contact list

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

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

    ListView lv = getListView();

    // Calling async task to get json

    new GetContacts().execute();
}

Asynctask - Getting all the Data json

private class GetContacts extends AsyncTask {

@Override
protected void onPreExecute() {
    super.onPreExecute();

    // Showing progress dialog
    pDialog = new ProgressDialog(ListUsersActivity.this);
    pDialog.setMessage("Please wait...");
    pDialog.setCancelable(false);
    pDialog.show();
}

@Override
protected Void doInBackground(Void... arg0) {
    // Creating service handler class instance
    NewSession app = (NewSession) getApplication();
    String username = app.getUsername();

    ServiceHandler sh = new ServiceHandler();

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

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

    if (jsonStr != null) {
        try {
            JSONObject jsonObj = new JSONObject(jsonStr);

            // Getting JSON Array node
            contacts = jsonObj.getJSONArray(TAG_CONTACTS);

            // looping through All Contacts
            for (int i = 0; i < contacts.length(); i++) {
                JSONObject c = contacts.getJSONObject(i);

                String id = c.getString(TAG_ID);
                String name = c.getString(TAG_NAME);
                String user_id = c.getString(TAG_USERID);
                String birth_date = c.getString(TAG_BIRTH_DATE);
                String pic_url_get = c.getString(TAG_IMAGE);

                HashMap<String, String> contact = new HashMap<String, String>();

                // adding each child node to HashMap key => value
                contact.put(TAG_ID, id);
                contact.put(TAG_USERID, user_id);
                contact.put(TAG_BIRTH_DATE, getAge(birth_date) + " anos");
                contact.put(TAG_IMAGE, "http://*****/images/" + user_id + "/" + pic_url_get);

                // adding contact to contact list
                contactList.add(contact);
            }
        } catch (JSONException e) {
            e.printStackTrace();   
        }
    } else {
        Log.e("ServiceHandler", "Couldn't get any data from the url");
    }

    return null;
}

Calling the adapter

  @Override
    protected void onPostExecute(Void result) {
        super.onPostExecute(result);


        // Dismiss the progress dialog
        if (pDialog.isShowing())
            pDialog.dismiss();
        /**
         * Updating parsed JSON data into ListView
         * */



        costumeadapter adapter =  new costumeadapter(
                        ListUsersActivity.this,
                        contactList,
                        R.layout.list_row,
                        new String[]{ TAG_NAME, TAG_BIRTH_DATE, TAG_USERID},
                        new int[]{ R.id.name,R.id.email, R.id.id });
        setListAdapter(adapter);
    }

}

I tried so far

  • To build a Timer and refresh my GetContacts calling class every second, but it doesn't work because the user is not able to scroll, and the application crashes

  • I tried to use notifyDataSetChanged but I didn't work because I dont know exactly how can i implement that.

I hope you guys can help me.

Thanks.

Michael Jackson
  • 356
  • 3
  • 18
  • possible duplicate of [notifyDataSetChanged example](http://stackoverflow.com/questions/3669325/notifydatasetchanged-example) – Jared Burrows Apr 30 '15 at 15:08

2 Answers2

0

Just use

adapter.notifydatasetchanged()

You have to add it after setListAdapter() like:

setListAdapter(adapter);
adapter.notifydatasetchanged();
Paritosh
  • 2,097
  • 3
  • 30
  • 42
0

Of course it is possible.

To build a Timer and refresh my GetContacts calling class every second, but it doesn't work because the user is not able to scroll, and the application crashes

Because you're doing it on the main thread. Do it in an AsyncTask or a separate thread, that should work.

I tried to use notifyDataSetChanged but I didn't work because I dont know exactly how can i implement that.

It's simple, you call it in the adapter: adapter.notifydatasetchanged() after you update it (more detail here).

Community
  • 1
  • 1
m0skit0
  • 25,268
  • 11
  • 79
  • 127
  • Can you please give me an example of how can i build a separate thread? – Michael Jackson Apr 30 '15 at 17:13
  • That's way too broad to answer here. There are entire books on how to use threads correctly in Java and Android. Check [this tutorial](http://developer.android.com/guide/components/processes-and-threads.html). – m0skit0 Apr 30 '15 at 17:26