Updating a ListFragment from another class - android

I have a Class that helps download data and store them in a Content Provider, and I've a ListFragment that loads the data from the provider, when the user login, the data is downloaded and everything works fine, but when there's an update in the data, the class meant to download downloads the data and saves it, but when I call the ListFragment to update, it crashes. Any help would be appreciated, my code is below:
This is the class that downloads the data
public class OrderDataRetrieval {
final Context context;
ProgressDialog pDiag;
public OrderDataRetrieval(final Context myContext){
context = myContext;
}
public void getData(String getToken, final Uri uri1, final Uri uri2, final Uri uri3){
pDiag = new ProgressDialog(context.getApplicationContext());
pDiag.setMessage("Loading...");
pDiag.setCancelable(false);
String order_URL = "http://xxxxxxxxxxxxxxxxx.json?token=" + getToken + "&contain=nnnnn,mmmm&uuuuu=0";
//pDiag.show();
Cache cache = AppController.getInstance().getRequestQueue().getCache();
final Entry entry = cache.get(order_URL);
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.GET,
order_URL, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
//pDiag.dismiss();
if (response != null) {
context.getContentResolver().delete(uri2, null, null);
context.getContentResolver().delete(uri3, null, null);
context.getContentResolver().delete(uri1, null, null);
Log.d("REPLY", response.toString());
handleResponse(response, uri1, uri2, uri3);
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// TODO Auto-generated method stub
//pDiag.dismiss();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(jsonObjReq);
}
public void handleResponse(JSONObject response, Uri uri1, Uri uri2, Uri uri3){
try {
JSONObject respOrd = response.getJSONObject("response");
JSONObject dataOrd = respOrd.getJSONObject("data");
JSONArray ordersArr = dataOrd.getJSONArray("orders");
Log.d("TEST", uri1.toString());
Log.d("TAGURL", uri2.toString());
for (int i = 0; i < ordersArr.length(); i++) {
ContentValues value = new ContentValues();
JSONObject ordItmObj = (JSONObject) ordersArr.get(i);
final String id = ordItmObj.getString("id");
value.put("order_id", ordItmObj.getString("id"));
value.put("source_number", ordItmObj.getString("number"));
value.put("order_type", ordItmObj.getString("order_type"));
value.put("order_picked", ordItmObj.getString("picked"));
value.put("order_delivered", ordItmObj.getString("delivered"));
value.put("source_code", ordItmObj.getString("source_customer_code"));
value.put("source_email", ordItmObj.getString("source_customer_email"));
value.put("source_name", ordItmObj.getString("source_customer_name"));
value.put("source_phone", ordItmObj.getString("source_customer_phone_number"));
value.put("source_address", ordItmObj.getString("source_customer_address_line_1") + " " + ordItmObj.getString("source_customer_city"));
value.put("destination_code", ordItmObj.getString("destination_customer_code"));
value.put("destination_email", ordItmObj.getString("destination_customer_email"));
value.put("destination_name", ordItmObj.getString("destination_customer_name"));
value.put("destination_phone", ordItmObj.getString("destination_customer_phone_number"));
value.put("destination_address", ordItmObj.getString("destination_customer_address_line_1") + " " + ordItmObj.getString("destination_customer_city"));
context.getContentResolver().insert(uri1, value);
JSONArray ordItem = ordItmObj.getJSONArray("OrderItem");
for (int j = 0; j < ordItem.length(); j++) {
JSONObject itm = (JSONObject) ordItem.get(j);
ContentValues valueItem = new ContentValues();
valueItem.put("order_id", id);
valueItem.put("item_name", itm.getString("name"));
valueItem.put("item_quantity", itm.getString("quantity"));
valueItem.put("item_details", itm.getString("details"));
context.getContentResolver().insert(uri2, valueItem);
}
JSONArray ordIssues = ordItmObj.getJSONArray("Issue");
for (int h = 0; h < ordIssues.length(); h++) {
JSONObject issues = (JSONObject) ordIssues.get(h);
ContentValues valueIssues = new ContentValues();
valueIssues.put("order_id", id);
valueIssues.put("issue_type", issues.getString("issue_type_id"));
valueIssues.put("issue_description", issues.getString("description"));
context.getContentResolver().insert(uri3, valueIssues);
}
}
Intent intent = new Intent();
intent.setAction("RELOAD");
context.sendBroadcast(intent);
//pends.getActivity().
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
And below is the ListFragment that needs to be updated, PendingFragment pends = PendingFragment.getInstance();
pends.getResults(); when that line is called, it crashes the app
public class PendingFragment extends ListFragment{
Context activityContext;
private ProgressDialog pDialog;
private PendingOrderListAdapter listAdapter;
private List<PendingTrackItem> trackItems;
SharedPreferences pref;
private BroadcastReceiver myReciever = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
getResults();
}
};
public void onDestroyView() {
super.onDestroyView();
getActivity().getApplicationContext().unregisterReceiver(myReciever);
};
private static PendingFragment pending;
public PendingFragment(){
}
public static PendingFragment getInstance(){
if (null == pending) {
pending = new PendingFragment();
}
return pending;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
View pending = inflater.inflate(R.layout.pending_frag, container, false);
setHasOptionsMenu(true);
return pending;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onViewCreated(view, savedInstanceState);
ListView list = getListView();
trackItems = new ArrayList<PendingTrackItem>();
listAdapter = new PendingOrderListAdapter(getActivity(), trackItems);
list.setAdapter(listAdapter);
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
TextView add_id = (TextView) view.findViewById(R.id.orderId);
TextView orderNumber = (TextView) view.findViewById(R.id.orderNumber);
pref = getActivity().getSharedPreferences("myId", Context.MODE_PRIVATE);
Editor edit = pref.edit();
edit.putString("int1", add_id.getText().toString());
edit.commit();
Intent i = new Intent(getActivity(), OrderFragmentActivity.class);
i.putExtra("key1", orderNumber.getText().toString());
startActivity(i);
}
});
}
public void getResults(){
Uri uri = Uri.parse("content://" + getString(R.string.AUTORITY_ORDER) + "/order");
Log.d("URL PRINT", uri.toString());
final Cursor cursor = getActivity().getContentResolver().query(uri, null, null, null, "_id");
Log.d("CURSOR DATA:", cursor.toString());
JSONArray array = new JSONArray();
if (cursor != null && cursor.getCount() > 0) {
while(cursor.moveToNext()){
JSONObject object = new JSONObject();
try {
object.put("destination_address", cursor.getString(0));
object.put("destination_code", cursor.getString(1));
object.put("destination_email", cursor.getString(2));
object.put("destination_name", cursor.getString(3));
object.put("destination_phone", cursor.getString(4));
object.put("_id", cursor.getString(5));
object.put("order_delivered", cursor.getString(6));
object.put("order_id", cursor.getString(7));
object.put("order_picked", cursor.getString(8));
object.put("order_type", cursor.getString(9));
object.put("source_address", cursor.getString(10));
object.put("source_code", cursor.getString(11));
object.put("source_email", cursor.getString(12));
object.put("source_name", cursor.getString(13));
object.put("source_number", cursor.getString(14));
object.put("source_phone", cursor.getString(15));
array.put(object);
Log.d("ARRAY", String.valueOf(array.length()));
} catch (JSONException e) {
e.printStackTrace();
}
}
parseJsonFeed(array);
cursor.close();
/*FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ClosedFragment cF = new ClosedFragment();
ft.replace(android.R.id.list, cF);
ft.commit();
cF.getResults();*/
}
}
public void parseJsonFeed(JSONArray jArr){
Log.d("jsonArr", jArr.toString());
try {
trackItems.clear();
for (int i = 0; i < jArr.length(); i++) {
JSONObject rest = (JSONObject) jArr.get(i);
String check = rest.getString("order_delivered");
PendingTrackItem item = new PendingTrackItem();
String sourceAdrress, destinationAddress;
sourceAdrress = rest.getString("source_address");
destinationAddress = rest.getString("destination_address");
Log.d("ORDER_CHECK", rest.toString());
if (check.equals("false")) {
item.setId(rest.getString("order_id"));
item.setNumber(rest.getString("source_number"));
if (sourceAdrress.matches(" ")) {
item.setSourceAddress(rest.getString("destination_address"));
item.setSourceName(rest.getString("destination_name"));
} else if (destinationAddress.matches(" ")) {
item.setSourceAddress(rest.getString("source_address"));
item.setSourceName(rest.getString("source_name"));
} else {
item.setSourceAddress(rest.getString("source_address"));
item.setSourceName(rest.getString("source_name"));
}
trackItems.add(item);
}
}
//Log.d("ITEm", String.valueOf(trackItems.size()));
TextView txt = (TextView) getActivity().findViewById(R.id.txtCount);
txt.setText(String.valueOf(trackItems.size()));
listAdapter.notifyDataSetChanged();
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
#Override
public void onResume() {
// TODO Auto-generated method stub
activityContext = getActivity().getApplicationContext();
SharedPreferences pref = this.getActivity().getSharedPreferences("myData", Context.MODE_PRIVATE);
String getToken = pref.getString("key1", "no data");
IntentFilter filter = new IntentFilter("RELOAD");
getActivity().getApplicationContext().registerReceiver(myReciever, filter);
getResults();
//getData(getToken, uri, itemUri, issuesUri);
super.onResume();
}
}
The crash report is
10-08 13:29:34.370: E/AndroidRuntime(9723): Process: com.deliveryscience.pod, PID: 9723
10-08 13:29:34.370: E/AndroidRuntime(9723): java.lang.IllegalStateException: Fragment PendingFragment{41f49628} not attached to Activity
10-08 13:29:34.370: E/AndroidRuntime(9723): at android.support.v4.app.Fragment.getResources(Fragment.java:603)
10-08 13:29:34.370: E/AndroidRuntime(9723): at android.support.v4.app.Fragment.getString(Fragment.java:625)
10-08 13:29:34.370: E/AndroidRuntime(9723): at com.deliveryscience.pod.fragments.PendingFragment.getResults(PendingFragment.java:109)
10-08 13:29:34.370: E/AndroidRuntime(9723): at com.deliveryscience.pod.handlers.OrderDataRetrieval.handleResponse(OrderDataRetrieval.java:122)
10-08 13:29:34.370: E/AndroidRuntime(9723): at com.deliveryscience.pod.handlers.OrderDataRetrieval$1.onResponse(OrderDataRetrieval.java:53)
10-08 13:29:34.370: E/AndroidRuntime(9723): at com.deliveryscience.pod.handlers.OrderDataRetrieval$1.onResponse(OrderDataRetrieval.java:1)
10-08 13:29:34.370: E/AndroidRuntime(9723): at com.android.volley.toolbox.JsonRequest.deliverResponse(JsonRequest.java:65)
10-08 13:29:34.370: E/AndroidRuntime(9723): at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:99)
I am stuck at finding a way to refresh the ListFragment

Follow below steps
1) register a broadcast receiver in ListFragment.
2) from Downloading data class, send a broadcast message with same intent you registered your receiver with.
instead of below code, use sendBroadcast
PendingFragment pends = PendingFragment.getInstance();
pends.getResults();
3) do the needful update from onReceive of Receiver class.
Alternatively you can use Handler to communicate between Download class and Fragment.
instead of

Related

Message is displayed two times after using notifyDataSetChanged

I am working on an instant chat application.My problem is that when i am sending message through my chat application,Message is displayed two times instead of one.Screen shot is given below :
As you can see in the acreenshot that the message hiii is displayed two times but i have sent only once.
1.Adapter_Message.java
public class Adapter_Message extends BaseAdapter {
private Context context;
private List<Bean_Message> messagesItems;
public Adapter_Message(Context context, List<Bean_Message> navDrawerItems) {
this.context = context;
this.messagesItems = navDrawerItems;
}
#Override
public int getCount() {
return messagesItems.size();
}
#Override
public Object getItem(int position) {
return messagesItems.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#SuppressLint("InflateParams")
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Bean_Message m = messagesItems.get(position);
LayoutInflater mInflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
// Identifying the message owner
if (messagesItems.get(position).isSelf()) {
// message belongs to you, so load the right aligned layout
convertView = mInflater.inflate(R.layout.list_item_message_right, null);
} else {
// message belongs to other person, load the left aligned layout
convertView = mInflater.inflate(R.layout.list_item_message_left, null);
}
TextView lblFrom = (TextView) convertView.findViewById(R.id.lblMsgFrom);
TextView txtMsg = (TextView) convertView.findViewById(R.id.txtMsg);
txtMsg.setText(m.getMessage());
lblFrom.setText(m.getFromName());
return convertView;
}
}
2.Chat_Activity.java
public class ChatActivity extends FragmentActivity implements
EmojiconGridFragment.OnEmojiconClickedListener, EmojiconsFragment.OnEmojiconBackspaceClickedListener {
public static final String TAG = ChatActivity.class.getSimpleName();
// EditText edMessage;
EmojiconEditText edMessage;
Button sendMessage;
private Socket mSocket;
String sID, lID, md5StringRoomID, message, friendName, loggedInUser;
String frndID;
int smallerID, largerID;
//AlmaChatDatabase almaChatDatabase;
// Chat messages list adapter
private Adapter_Message adapter;
private List<Bean_Message> listBeanMessages;
private ListView listViewMessages;
boolean isSelf; // to check whether the message is owned by you or not.true means message is owned by you .
Bean_Message msg;
int loggedInUserID;
private String URL_FEED_Message = "";
APIConfiguration apiConfiguration;
SharedPreferences preferences;
HashMap<String, Integer> emoticons;
// instance initialization block
{
try {
mSocket = IO.socket(Constants.CHAT_SERVER_URL);
Log.e("Socket", String.valueOf(mSocket));
} catch (URISyntaxException e) {
throw new RuntimeException(e);
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);
sendMessage = (Button) findViewById(R.id.btnSendMessage);
preferences = getApplicationContext().getSharedPreferences(Prefs_Registration.prefsName, Context.MODE_PRIVATE);
//Handling emoticons
/* emoticons = new HashMap<String,Integer>();
emoticons.put(":-)",R.drawable.s1);*/
String id = preferences.getString(Prefs_Registration.get_user_id, null);
// Converting String id to integer
loggedInUserID = Integer.parseInt(id);
//loggedInUserID = almaChatDatabase.getUserID(); // Getting ID of the Logged in user from the database
Log.e("UserID", "Id of Logged in user " + loggedInUserID);
listBeanMessages = new ArrayList<Bean_Message>();
adapter = new Adapter_Message(getApplicationContext(), listBeanMessages);
listViewMessages = (ListView) findViewById(R.id.list_view_messages);
listViewMessages.setAdapter(adapter);
// Getting the ID of the friend from the previous screen using getExtras
Bundle bundle = getIntent().getExtras();
frndID = bundle.getString("ID");
Log.e("FriendID", frndID);
final int friendID = Integer.parseInt(frndID);
friendName = bundle.getString("name");
Log.e("FriendName", friendName);
loggedInUser = preferences.getString(Prefs_Registration.get_user_name, null);
//loggedInUser = almaChatDatabase.getUserName(); // Name of logged in user
Log.e("LoggedInUser", loggedInUser);
// Converting first lowercase letter of every word in Uppercase
final String loggedInUpper = upperCase(loggedInUser);
//To find the current time
Date d = new Date();
final long time = d.getTime();
// Comparing the loggedInUserId and friendID
if (friendID < loggedInUserID) {
smallerID = friendID;
largerID = loggedInUserID;
} else {
smallerID = loggedInUserID;
largerID = friendID;
}
sID = String.valueOf(smallerID);
lID = String.valueOf(largerID);
String combinedID = sID + lID;
Log.e("combined ID", combinedID);
md5StringRoomID = convertPassMd5(combinedID); // Encrypting the combinedID to generate Room ID
Log.e("md5StringRoomID", md5StringRoomID);
// Using the API for loading old chat messages
apiConfiguration = new APIConfiguration();
String api_message = apiConfiguration.getApi_message(); // Getting the API of messages
URL_FEED_Message = api_message + md5StringRoomID; // md5String is the encrypted room ID here
Log.e("URL_FEED_MESSAGE", URL_FEED_Message);
Log.e("Network request", "Fresh Request");
// We first check for cached request
Cache cache = AppController.getInstance().getRequestQueue().getCache();
Cache.Entry entry = cache.get(URL_FEED_Message);
if (entry != null) {
// fetch the data from cache
try {
String data = new String(entry.data, "UTF-8");
try {
parseJsonFeed(new JSONArray(data));
} catch (JSONException e) {
e.printStackTrace();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
} else {
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(URL_FEED_Message, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray jsonArray) {
Log.e("JsonArray", String.valueOf(jsonArray));
if (jsonArray != null) {
parseJsonFeed(jsonArray);
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
Log.e("ErrorResponse", String.valueOf(volleyError));
}
}
);
// Adding request to volley request queue
AppController.getInstance().addToRequestQueue(jsonArrayRequest);
}
edMessage = (EmojiconEditText) findViewById(R.id.edtMessage);
//Listening on Events
mSocket.on(Socket.EVENT_CONNECT, onConnect);
mSocket.on(Socket.EVENT_CONNECT_ERROR, onConnectionError);
mSocket.on(Socket.EVENT_DISCONNECT, onDisconnect);
mSocket.on("send:notice", onReceive); // Listening event for receiving messages
mSocket.connect(); // Explicitly call connect method to establish connection here
mSocket.emit("subscribe", md5StringRoomID);
sendMessage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
message = edMessage.getText().toString().trim();
Log.e("Sending", "Sending data-----" + message);
if (!message.equals("")) {
edMessage.setText(" ");
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("room_id", md5StringRoomID);
jsonObject.put("user", loggedInUpper);
jsonObject.put("id", friendID);
jsonObject.put("message", message);
jsonObject.put("date", time);
jsonObject.put("status", "sent");
} catch (JSONException e) {
e.printStackTrace();
}
isSelf = true; // Boolean isSelf is set to be true as sender of the message is logged in user i.e. you
attemptToSend(loggedInUpper, message, isSelf);
mSocket.emit("send", jsonObject); // owner i.e LoggedIn user is sending the message
} else {
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), "Please enter some text", Toast.LENGTH_LONG).show();
}
});
}
}
});
setEmojiconFragment(false);
}
/* public Spannable getSmiledText(String text) {
SpannableStringBuilder builder = new SpannableStringBuilder(text);
if (emoticons.size() > 0) {
int index;
for (index = 0; index < builder.length(); index++) {
if (Character.toString(builder.charAt(index)).equals(":")) {
for (Map.Entry<String, Integer> entry : emoticons.entrySet()) {
int length = entry.getKey().length();
if (index + length > builder.length())
continue;
if (builder.subSequence(index, index + length).toString().equals(entry.getKey())) {
builder.setSpan(new ImageSpan(getApplicationContext(), entry.getValue()), index, index + length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
index += length - 1;
break;
}
}
}
}
}
return builder;
}*/
private void setEmojiconFragment(boolean useSystemDefault) {
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.emojicons, EmojiconsFragment.newInstance(useSystemDefault))
.commit();
}
//Adding message in the arrayList
public void attemptToSend(String senderName, String message, boolean isSelf) {
msg = new Bean_Message(senderName, message, isSelf);
listBeanMessages.add(msg);
adapter.notifyDataSetChanged();
playBeep();
}
// Playing sound when the message is sent by the owner
public void playBeep() {
try {
Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), notification);
r.play();
} catch (Exception e) {
e.printStackTrace();
}
}
// encrypting string into MD5
public static String convertPassMd5(String pass) {
String password = null;
MessageDigest mdEnc;
try {
mdEnc = MessageDigest.getInstance("MD5");
mdEnc.update(pass.getBytes(), 0, pass.length());
pass = new BigInteger(1, mdEnc.digest()).toString(16);
while (pass.length() < 32) {
pass = "0" + pass;
}
password = pass;
} catch (NoSuchAlgorithmException e1) {
e1.printStackTrace();
}
return password;
}
// Converting first lowercase letter of every word in Uppercase
String upperCase(String source) {
StringBuffer res = new StringBuffer();
String[] strArr = source.split(" ");
for (String str : strArr) {
char[] stringArray = str.trim().toCharArray();
stringArray[0] = Character.toUpperCase(stringArray[0]);
str = new String(stringArray);
res.append(str).append(" ");
}
return res.toString().trim();
}
// Event Listeners
private Emitter.Listener onConnect = new Emitter.Listener() {
#Override
public void call(Object... args) {
Log.e("Socket", "Connected");
}
};
private Emitter.Listener onConnectionError = new Emitter.Listener() {
#Override
public void call(Object... args) {
Log.e("Error", "Error in connecting server");
}
};
private Emitter.Listener onDisconnect = new Emitter.Listener() {
#Override
public void call(Object... args) {
Log.e("Disconnect", "Socket Disconnected");
}
};
// Event Listener for receiving messages
private Emitter.Listener onReceive = new Emitter.Listener() {
#Override
public void call(final Object... args) {
Log.e("Receive", "Bean_Message received");
runOnUiThread(new Runnable() {
#Override
public void run() {
JSONObject data = (JSONObject) args[0];
Log.e("DATA", String.valueOf(data));
try {
JSONArray ops = data.getJSONArray("ops");
for (int i = 0; i < ops.length(); i++) {
JSONObject object = ops.getJSONObject(i);
String roomID = object.getString("room_id");
Log.e("RoomID", roomID); // Getting room ID from JSON array
Log.e("Md5RoomID", md5StringRoomID); // Getting room id which we have created using logged in user ID and room id of the user through which chat has to be done
//Comparing the room IDs
if (md5StringRoomID.equals(roomID)) {
String senderName = object.getString("user");
Log.e("Sender Name", senderName);
String senderID = object.getString("id");
Log.e("SenderID", senderID);
// JSONObject message = object.getJSONObject("message");
String messageReceived = object.getString("message");
Log.e("Bean_Message Received", messageReceived);
String loggedInUSerNAme = preferences.getString(Prefs_Registration.get_user_name, null);
//String loggedInUSerNAme = almaChatDatabase.getUserName();
//If the message is sent by the owner to other from webapp ,then we need to check whether the sender is the loggedinUSer in the App or not and we will right align the messages .
if (loggedInUSerNAme.equalsIgnoreCase(senderName)) {
isSelf = true;
msg = new Bean_Message(senderName, messageReceived, isSelf);
listBeanMessages.add(msg);
// Log.e("List Elements", String.valueOf(listBeanMessages));
adapter.notifyDataSetChanged();
playBeep();
} else {
isSelf = false;
msg = new Bean_Message(senderName, messageReceived, isSelf);
listBeanMessages.add(msg);
Log.e("List Elements", String.valueOf(listBeanMessages));
adapter.notifyDataSetChanged();
playBeep();
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
// Playing sound when the message is sent by other
public void playBeep() {
try {
Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), notification);
r.play();
} catch (Exception e) {
e.printStackTrace();
}
}
};
// Parsing JSon Array which corresponds to the old chat messages
public void parseJsonFeed(JSONArray jsonArray) {
for (int i = 0; i < jsonArray.length(); i++) {
try {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String roomID = jsonObject.getString("room_id");
Log.e("RoomID", roomID);
Log.e("Md5RoomID", md5StringRoomID);
// If Room ID(created using id of logged in user and id of friend) matches with the room id obtained from JSON String
if (md5StringRoomID.equals(roomID)) {
String userName = jsonObject.getString("user");
Log.e("Name", userName);
String loggedInUSerNAme = preferences.getString(Prefs_Registration.get_user_name, null);
//String loggedInUSerNAme = almaChatDatabase.getUserName();
Log.e("LoggedInUSer", loggedInUSerNAme);
//If the message is sent by the owner to other from webapp ,then we need to check whether the sender is the loggedinUSer in the App or not and we will right align the messages .
if (loggedInUSerNAme.equalsIgnoreCase(userName)) {
String message = jsonObject.getString("message");
Log.e("message", message);
isSelf = true;
msg = new Bean_Message(userName, message, isSelf);
listBeanMessages.add(msg);
adapter.notifyDataSetChanged();
//playBeep();
} else {
JSONObject jsonMessage = jsonObject.getJSONObject("message");
String message = jsonMessage.getString("text");
isSelf = false;
msg = new Bean_Message(userName, message, isSelf);
listBeanMessages.add(msg);
adapter.notifyDataSetChanged();
// playBeep();
}
}
} catch (JSONException e) {
e.printStackTrace();
}
// notify data changes to list adapter
//adapter.notifyDataSetChanged();
}
}
#Override
public void onEmojiconBackspaceClicked(View view) {
EmojiconsFragment.backspace(edMessage);
}
#Override
public void onEmojiconClicked(Emojicon emojicon) {
EmojiconsFragment.input(edMessage, emojicon);
}
}
3.Bean_Message.java
public class Bean_Message {
private String fromName, message;
private boolean isSelf; // isSelf is used to check whether the message is owned by you or not
public Bean_Message() {
}
public Bean_Message(String fromName, String message, boolean isSelf) {
this.fromName = fromName;
this.message = message;
this.isSelf = isSelf;
}
public String getFromName() {
return fromName;
}
public void setFromName(String fromName) {
this.fromName = fromName;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public boolean isSelf() {
return isSelf;
}
public void setSelf(boolean isSelf) {
this.isSelf = isSelf;
}
}
On clicking "Send Message" button ,message is sent to he server and the following code is used:
public void attemptToSend(String senderName, String message, boolean isSelf) {
msg = new Bean_Message(senderName, message, isSelf);
listBeanMessages.add(msg);
adapter.notifyDataSetChanged();
playBeep();
}
Message is stored in the Bean and Bean is added in the ArrayList .Now i am notifying my adapter that the ArrayList is updated using adapter.notifyDataSetChanged() method.But the problem is List view is displaying my sent message two times.Please help me to solve the issue .

Endless Adapter does not show any values in the listview

I am trying to use Endless listview adapter in application code but some how i am just not able to see any values in the listview. My code is running perfectly fine when using normal listview adapter. I an trying to use CWAC- endless adpater. I can get how to run it with my asynctask as it gives me blank screen after loding.
Below is my code for the some.
public class EndlessAdapterExample extends ListActivity {
public JSONArray jsonarray,jsondatearray;
public String url;
public String selectedvalue;
public String TAG = "TAG Event Display";
public String SuggestCity;
public String SuggestState;
public String suggestCountry;
public String event_id,address;
String lat;
String lng;
public String event_name;
public String dateKey;
public String datetime,timenew;
Calendar cal;
public SharedPreferences prefs;
public Editor editor;
public String access_token,id,username;
public static ArrayList<EventsBean> arrayEventsBeans = new ArrayList<EventsBean>();
ArrayList<DateBean> sortArray = new ArrayList<DateBean>();
public SAmpleAdapter adapter;
public ImageView img_menu,img_calender;
public ListView listview;
static int LIST_SIZE;
private int mLastOffset = 0;
static final int BATCH_SIZE = 10;
ArrayList<EventsBean> countriesSub = new ArrayList<EventsBean>();
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setTheme(android.R.style.Theme);
setContentView(R.layout.sample_endless);
listview = (ListView)findViewById(android.R.id.list);
try {
// Preferences values fetched from the preference of FBConnection class.
prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
access_token = prefs.getString("access_token", null);
id = prefs.getString("uid", null);
username = prefs.getString("username", null);
if(access_token == null && id == null && username == null)
{
Toast.makeText(getApplicationContext(), "FaceBook Login was not successful" +
"/nPlease Relogin.", Toast.LENGTH_SHORT).show();
}
else
{
Log.i(TAG, "VALUES::" + access_token+ " " + id + " " +username);
url = "mu Url"
}
} catch (NullPointerException e) {
Log.i(TAG, "User Not Logged IN " + e.getMessage());
// TODO Auto-generated catch block
e.printStackTrace();
}
init();
listview.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,long arg3) {
// TODO Auto-generated method stub
// Fetching the position from the listview which has been selected.
}
});
}
private void init() {
new FetchEventValues().execute();
}
private void setLastOffset(int i) {
mLastOffset = i;
}
private int getLastOffset(){
return mLastOffset;
}
private void displayList(ArrayList<EventsBean> countriesSub) {
setListAdapter(new DemoAdapter());
}
// AsyncTask Class called in the OnCreate() when the activity is first started.
public class FetchEventValues extends AsyncTask<Void, ArrayList<EventsBean>, ArrayList<EventsBean>>
{
ProgressDialog progressdialog = new ProgressDialog(EndlessAdapterExample.this);
ArrayList<EventsBean> merge = new ArrayList<EventsBean>();
ArrayList<EventsBean> localList;
public EventsBean eventsbean;
#SuppressLint("SimpleDateFormat")
#SuppressWarnings("unchecked")
#Override
protected ArrayList<EventsBean> doInBackground(Void... params) {
// Creating JSON Parser instance
JsonParser jParser = new JsonParser();
// getting JSON string from URL
JSONObject jsonobj = jParser.getJSONFromUrl(url);
Log.i(TAG, "URL VALUES:" + url);
try{
// Code to get the auto complete values Autocomplete Values
JSONArray jsonAarray = jsonobj.getJSONArray(Constants.LOCATIONS);
eventsbean = new EventsBean();
Log.e(TAG, "Location Array Size:" + jsonAarray.length());
for(int j = 0 ; j < jsonAarray.length() ; j++)
{
if(!jsonAarray.getJSONObject(j).isNull(Constants.LOCATION_CITY) && !jsonAarray.getJSONObject(j).isNull(Constants.LOCATION_STATE) && !jsonAarray.getJSONObject(j).isNull(Constants.LOCATION_COUNTRY))
{
JSONObject job = jsonAarray.getJSONObject(j);
if(job.has(Constants.LOCATION_STATE))
{
SuggestCity = job.getString(Constants.LOCATION_CITY);
eventsbean.setLocation_city(job.getString(Constants.LOCATION_CITY));
SuggestState = job.getString(Constants.LOCATION_STATE);
eventsbean.setLocation_state(job.getString(Constants.LOCATION_STATE));
suggestCountry = job.getString(Constants.LOCATION_COUNTRY);
eventsbean.setLocation_country(job.getString(Constants.LOCATION_COUNTRY));
}
}
}
// JSON object to fetch the events in datewise format
JSONObject eventobject = jsonobj.getJSONObject("events");
// #SuppressWarnings("unchecked")
Iterator<Object> keys = eventobject.keys();
while (keys.hasNext()) {
String datestring = String.valueOf(keys.next());
if (datestring.trim().length() > 0) {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
Date date = formatter.parse(datestring);
DateBean dateBean = new DateBean(date);
sortArray.add(dateBean);
}
// JSONArray jsonArray = eventobject.getJSONArray(datestring);
//System.out.println(" --"+jsonArray);
}
System.out.println("size:"+sortArray.size());
System.out.println("==========sorting array======");
Collections.sort(sortArray,new CompareDate());
//reverse order
//Collections.reverse(sortArray);
for(DateBean d : sortArray){
dateKey = new SimpleDateFormat("yyyy-MM-dd").format(d.getDate());
System.out.println(dateKey);
Date today = new Date();
Date alldates = d.getDate();
cal = Calendar.getInstance();
/// Calendar alldates1 = Calendar.getInstance();
JSONArray jsonArray = eventobject.getJSONArray(dateKey);
System.out.println(" --"+jsonArray);
for (int i = 0 ; i < jsonArray.length() ; i++)
{
if (alldates.compareTo(today) > 0)
// if (alldates1 > cal) alldates.getTime() >= today.getTime()
{
JSONObject jsonobjname = jsonArray.getJSONObject(i);
eventsbean = new EventsBean();
JSONObject jobjectpicture = jsonobjname.getJSONObject(Constants.PICTURE);
JSONObject jobjeventpicture = jobjectpicture.getJSONObject(Constants.DATA);
eventsbean.setUrl(jobjeventpicture.getString(Constants.URL));
if(jsonobjname.has(Constants.OWNER))
{
JSONObject owner_obj = jsonobjname.getJSONObject(Constants.OWNER);
eventsbean.setOwner_id(owner_obj.getString(Constants.OWNER_ID));
eventsbean.setOwner_name(owner_obj.getString(Constants.OWNER_NAME));
String owner_name = owner_obj.getString(Constants.OWNER_NAME);
Log.i(TAG, "Owner:" + owner_name);
}
if(!jsonobjname.isNull(Constants.COVER))
{
JSONObject objectcover = jsonobjname.getJSONObject(Constants.COVER);
eventsbean.setCover_id(objectcover.getString(Constants.COVER_ID));
eventsbean.setSource(objectcover.getString(Constants.SOURCE));
String cover_url = objectcover.getString(Constants.SOURCE);
Log.i(TAG, "Cover Url:" + cover_url);
eventsbean.setOffset_y(objectcover.getString(Constants.OFFSET_Y));
eventsbean.setOffset_x(objectcover.getString(Constants.OFFSET_X));
}
eventsbean.setName(jsonobjname.getString(Constants.NAME));
eventsbean.setEvent_id(jsonobjname.getString(Constants.EVENT_ID));
eventsbean.setStart_time(jsonobjname.getString(Constants.START_TIME));
eventsbean.setDescription(jsonobjname.getString(Constants.DESCRIPTION));
eventsbean.setLocation(jsonobjname.getString(Constants.LOCATION));
if(!jsonobjname.isNull(Constants.IS_SILHOUETTE))
{
eventsbean.setIs_silhouette(jsonobjname.getString(Constants.IS_SILHOUETTE));
}
eventsbean.setPrivacy(jsonobjname.getString(Constants.PRIVACY));
datetime = jsonobjname.getString(Constants.START_TIME);
if(!jsonobjname.isNull(Constants.VENUE))
{
JSONObject objectvenue = jsonobjname.getJSONObject(Constants.VENUE);
if(objectvenue.has(Constants.VENUE_NAME))
{
eventsbean.setVenue_name(objectvenue.getString(Constants.VENUE_NAME));
event_name = objectvenue.getString(Constants.VENUE_NAME);
Log.i(TAG, "Event Venue Name:" + event_name);
}
else
{
eventsbean.setLatitude(objectvenue.getString(Constants.LATITUDE));
eventsbean.setLongitude(objectvenue.getString(Constants.LONGITUDE));
eventsbean.setCity(objectvenue.getString(Constants.CITY));
eventsbean.setState(objectvenue.getString(Constants.STATE));
eventsbean.setCountry(objectvenue.getString(Constants.COUNTRY));
eventsbean.setVenue_id(objectvenue.getString(Constants.VENUE_ID));
eventsbean.setStreet(objectvenue.getString(Constants.STREET));
address = objectvenue.getString(Constants.STREET);
eventsbean.setZip(objectvenue.getString(Constants.ZIP));
}
}
arrayEventsBeans.add(eventsbean);
Log.i(TAG, "arry list values:" + arrayEventsBeans.size());
}
}
}
}catch(Exception e){
localList=null;
Log.e(TAG , "Exception Occured:" + e.getMessage());
}
return arrayEventsBeans;
}
class CompareDate implements Comparator<DateBean>{
#Override
public int compare(DateBean d1, DateBean d2) {
return d1.getDate().compareTo(d2.getDate());
}
}
#Override
protected void onPostExecute(ArrayList<EventsBean> result) {
super.onPostExecute(result);
if(this.progressdialog.isShowing())
{
this.progressdialog.dismiss();
}
// adapter = new SAmpleAdapter(EndlessAdapterExample.this,0, arrayEventsBeans);
//listview.setAdapter(adapter);
//displayList(arrayEventsBeans);
LIST_SIZE = arrayEventsBeans.size();
for (int i = 0; i <= BATCH_SIZE; i++) {
countriesSub.add(arrayEventsBeans.get(i));
}
setLastOffset(BATCH_SIZE);
displayList(countriesSub);
Log.i(TAG, "country list:" + countriesSub.size());
}
#Override
protected void onPreExecute() {
super.onPreExecute();
this.progressdialog.setMessage("Loading....");
this.progressdialog.setCanceledOnTouchOutside(false);
this.progressdialog.show();
}
}
public class SAmpleAdapter extends ArrayAdapter<EventsBean> {
Context context;
public ArrayList<EventsBean> mOriginalvalues;
private ArrayList<EventsBean> mDisplayvalues;
ImageLoader imageloader;
public String datenew,datetime,date_text_value,timenew;
public int date_text,year;
public String time,month,description;
public LayoutInflater inflator = null;
public SAmpleAdapter(Context context, int resource, ArrayList<EventsBean> mEventarraylist) {
super(context, resource , mEventarraylist);
// TODO Auto-generated constructor stub
this.mOriginalvalues = mEventarraylist;
this.mDisplayvalues = mEventarraylist;
inflator = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
imageloader=new ImageLoader(context.getApplicationContext());
getFilter();
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return mOriginalvalues.size();
}
#Override
public EventsBean getItem(int position) {
// TODO Auto-generated method stub
return mOriginalvalues.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
Holder viewHolder;
if(convertView == null)
{
viewHolder=new Holder();
convertView = inflator.inflate(R.layout.activity_list_items, parent, false);
viewHolder.txt_name = (TextView)convertView.findViewById(R.id.textname);
viewHolder.txt_owner_name = (TextView)convertView.findViewById(R.id.ownername);
viewHolder.txt_time = (TextView)convertView.findViewById(R.id.date);
viewHolder.txt_date = (TextView)convertView.findViewById(R.id.txt_date_value);
viewHolder.txt_month = (TextView)convertView.findViewById(R.id.txt_month_value);
viewHolder.txt_year = (TextView)convertView.findViewById(R.id.txt_year_value);
viewHolder.userimg = (ImageView)convertView.findViewById(R.id.imageView1);
convertView.setTag(viewHolder);
}
else
{
viewHolder=(Holder)convertView.getTag();
}
viewHolder.txt_name.setText(mOriginalvalues.get(position).getName());
viewHolder.txt_owner_name.setText(mOriginalvalues.get(position).getOwner_name());
String url = mOriginalvalues.get(position).getSource();
date_text_value = mOriginalvalues.get(position).getStart_time();
try {
parseDateFromString(date_text_value);
} catch (Exception e) {
Log.i("Adapter TAG", "Date Exception" + e.getMessage());
}
viewHolder.txt_date.setText(String.valueOf(date_text));
viewHolder.txt_month.setText(month);
viewHolder.txt_year.setText(String.valueOf(year));
Log.i("TEST", "Date:" + date_text_value);
imageloader.DisplayImage(url, viewHolder.userimg);
viewHolder.txt_time.setText(timenew);
return convertView;
}
public void resetData() {
mOriginalvalues = mDisplayvalues;
}
#SuppressLint("SimpleDateFormat")
public Date parseDateFromString(String aDateString){
SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
Calendar c = Calendar.getInstance();
Date date= new Date();
try {
date= inputFormat.parse(aDateString);
System.out.println(date);
SimpleDateFormat day = new SimpleDateFormat("dd-MMM-yyyy");
SimpleDateFormat time = new SimpleDateFormat("hh:mm a", Locale.getDefault());
SimpleDateFormat month_date = new SimpleDateFormat("MMM");
c.setTime(inputFormat.parse(aDateString));
System.out.println(day.format(date));
datenew = day.format(date).toString();
date_text = c.get(Calendar.DAY_OF_MONTH);
month = month_date.format(c.getTime());
year = c.get(Calendar.YEAR);
System.out.println("Year = " + c.get(Calendar.YEAR));
System.out.println("Month = " + month);
System.out.println("Day = " + date_text);
System.out.println(time.format(date));
timenew = time.format(date).toString();
} catch (ParseException e) {
Log.i("TAG", "DateFormat Pasring Error:" + e.getMessage());
}
return date;
}
private class Holder{
TextView txt_name;
TextView txt_owner_name ;
TextView txt_time;
TextView txt_date;
TextView txt_month;
TextView txt_year;
ImageView userimg;
}
}
class DemoAdapter extends EndlessAdapter {
private RotateAnimation rotate=null;
ArrayList<EventsBean> tempList = new ArrayList<EventsBean>();
LayoutInflater inflator = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
DemoAdapter() {
super(new SAmpleAdapter(EndlessAdapterExample.this,R.layout.sample_endless,countriesSub));
inflator = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
rotate=new RotateAnimation(0f, 360f, Animation.RELATIVE_TO_SELF,
0.5f, Animation.RELATIVE_TO_SELF,
0.5f);
rotate.setDuration(600);
rotate.setRepeatMode(Animation.RESTART);
rotate.setRepeatCount(Animation.INFINITE);
}
#Override
protected View getPendingView(ViewGroup parent) {
View row=getLayoutInflater().inflate(R.layout.row, null);
View child=row.findViewById(R.id.textview1);
child.setVisibility(View.GONE);
child=row.findViewById(R.id.throbber);
child.setVisibility(View.VISIBLE);
child.startAnimation(rotate);
return(row);
}
#Override
protected boolean cacheInBackground() {
tempList.clear();
int lastOffset = getLastOffset();
if(lastOffset < LIST_SIZE){
int limit = lastOffset + BATCH_SIZE;
for(int i=(lastOffset+1); (i<=limit && i<LIST_SIZE); i++){
tempList.add(arrayEventsBeans.get(i));
}
setLastOffset(limit);
if(limit<LIST_SIZE){
return true;
} else {
return false;
}
} else {
return false;
}
}
#SuppressLint("NewApi")
#Override
protected void appendCachedData() {
#SuppressWarnings("unchecked")
ArrayAdapter<EventsBean> arrAdapterNew = (ArrayAdapter<EventsBean>)getWrappedAdapter();
int listLen = tempList.size();
for(int i=0; i<listLen; i++){
arrAdapterNew.addAll(tempList.get(i));
}
}
}
}
I have updated my code. I guess my problem now is with the custom adapter as it gives me multiple values after it reaches the end of the listview. Initially i do get 10 values but after the update it gets same 10 values again but the count reaches to 121.
Replace your init() as below,
private void init() {
new FetchEventValues().execute();
}
and replace onPostExecute() with below,
#Override
protected void onPostExecute(ArrayList<EventsBean> result) {
super.onPostExecute(result);
if (this.progressdialog.isShowing()) {
this.progressdialog.dismiss();
}
// adapter = new SAmpleAdapter(EndlessAdapterExample.this,0,
// arrayEventsBeans);
// listview.setAdapter(adapter);
LIST_SIZE = arrayEventsBeans.size();
for (int i = 0; i <= BATCH_SIZE; i++) {
countriesSub.add(arrayEventsBeans.get(i));
}
setLastOffset(BATCH_SIZE);
displayList(countriesSub);
}

AsynTask with Endless Listview Scroll in android

I am creating an application where in i need to have endless scrolling listview. I dnt want to use any library in my application. I have seen some examples on line that help in achieving such listview,but my doubt is how can i have an endless listview when my data are coming from server and are getting parsed in the Asynctask. How can i load 10 items at a time from my asynctask on scroll? I want to know to implement a endless listview on asyntask.
Do i call my asynctask in the onScroll() or not???
public class EndlessScrollExample extends ListActivity {
public JSONArray jsonarray,jsondatearray;
public String url;
public String selectedvalue;
public String TAG = "TAG Event Display";
public String SuggestCity;
public String SuggestState;
public String suggestCountry;
public String event_id,address;
String lat;
String lng;
public String event_name;
public String dateKey;
public String datetime,timenew;
Calendar cal;
public SharedPreferences prefs;
public Editor editor;
public String access_token,id,username;
public static ArrayList<EventsBean> arrayEventsBeans = new ArrayList<EventsBean>();
ArrayList<DateBean> sortArray = new ArrayList<DateBean>();
public SAmpleAdapter adapter;
public ImageView img_menu,img_calender;
public ListView listview;
public EventsBean eventsbean;
int counter = 0;
int currentPage = 0;
FetchEventValues fetchValues;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setTheme(android.R.style.Theme);
setContentView(R.layout.sample_endless);
listview = (ListView)findViewById(android.R.id.list);
try {
// Preferences values fetched from the preference of FBConnection class.
prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
access_token = prefs.getString("access_token", null);
id = prefs.getString("uid", null);
username = prefs.getString("username", null);
if(access_token == null && id == null && username == null)
{
Toast.makeText(getApplicationContext(), "FaceBook Login was not successful" +
"/nPlease Relogin.", Toast.LENGTH_SHORT).show();
}
else
{
Log.i(TAG, "VALUES::" + access_token+ " " + id + " " +username);
url = "my Url";
}
} catch (NullPointerException e) {
Log.i(TAG, "User Not Logged IN " + e.getMessage());
// TODO Auto-generated catch block
e.printStackTrace();
}
fetchValues = new FetchEventValues();
fetchValues.execute();
listview = getListView();
listview.setOnScrollListener(new EndlessScrollListener());
}
// AsyncTask Class called in the OnCreate() when the activity is first started.
public class FetchEventValues extends AsyncTask<Integer, Integer, Integer>
{
ProgressDialog progressdialog = new ProgressDialog(EndlessScrollExample.this);
#SuppressLint("SimpleDateFormat")
#SuppressWarnings("unchecked")
#Override
protected Integer doInBackground(Integer... params) {
currentPage++;
// Creating JSON Parser instance
JsonParser jParser = new JsonParser();
// getting JSON string from URL
//arrayEventsBeans.clear();
JSONObject jsonobj = jParser.getJSONFromUrl(url);
Log.i(TAG, "URL VALUES:" + url);
try{
// Code to get the auto complete values Autocomplete Values
JSONArray jsonAarray = jsonobj.getJSONArray(Constants.LOCATIONS);
eventsbean = new EventsBean();
Log.e(TAG, "Location Array Size:" + jsonAarray.length());
for(int j = 0 ; j < jsonAarray.length() ; j++)
{
if(!jsonAarray.getJSONObject(j).isNull(Constants.LOCATION_CITY) && !jsonAarray.getJSONObject(j).isNull(Constants.LOCATION_STATE) && !jsonAarray.getJSONObject(j).isNull(Constants.LOCATION_COUNTRY))
{
JSONObject job = jsonAarray.getJSONObject(j);
if(job.has(Constants.LOCATION_STATE))
{
SuggestCity = job.getString(Constants.LOCATION_CITY);
eventsbean.setLocation_city(job.getString(Constants.LOCATION_CITY));
SuggestState = job.getString(Constants.LOCATION_STATE);
eventsbean.setLocation_state(job.getString(Constants.LOCATION_STATE));
suggestCountry = job.getString(Constants.LOCATION_COUNTRY);
eventsbean.setLocation_country(job.getString(Constants.LOCATION_COUNTRY));
}
}
}
// JSON object to fetch the events in datewise format
JSONObject eventobject = jsonobj.getJSONObject("events");
arrayEventsBeans = new ArrayList<EventsBean>();
// #SuppressWarnings("unchecked")
Iterator<Object> keys = eventobject.keys();
while (keys.hasNext()) {
String datestring = String.valueOf(keys.next());
if (datestring.trim().length() > 0) {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
Date date = formatter.parse(datestring);
DateBean dateBean = new DateBean(date);
sortArray.add(dateBean);
}
// JSONArray jsonArray = eventobject.getJSONArray(datestring);
//System.out.println(" --"+jsonArray);
}
System.out.println("size:"+sortArray.size());
System.out.println("==========sorting array======");
Collections.sort(sortArray,new CompareDate());
//reverse order
//Collections.reverse(sortArray);
for(DateBean d : sortArray){
dateKey = new SimpleDateFormat("yyyy-MM-dd").format(d.getDate());
System.out.println(dateKey);
Date today = new Date();
Date alldates = d.getDate();
/// Calendar alldates1 = Calendar.getInstance();
JSONArray jsonArray = eventobject.getJSONArray(dateKey);
System.out.println(" --"+jsonArray);
for (int i = 0 ; i < jsonArray.length() ; i++)
{
if ((today.compareTo(alldates) < 0 || (today.compareTo(alldates)== 0)))
// if (alldates1 > cal) alldates.getTime() >= today.getTime()
{
String currentTimeStr = "7:04 PM";
Date userDate = new Date();
String userDateWithoutTime = new SimpleDateFormat("yyyyMMdd").format(userDate);
String currentDateStr = userDateWithoutTime + " " + currentTimeStr;
Date currentDate = new SimpleDateFormat("yyyyMMdd h:mm a").parse(currentDateStr);
if (userDate.compareTo(currentDate) >= 0) {
System.out.println(userDate + " is greater than or equal to " + currentDate);
} else {
System.out.println(userDate + " is less than " + currentDate);
}
JSONObject jsonobjname = jsonArray.getJSONObject(i);
EventsBean eventsbean = new EventsBean();
JSONObject jobjectpicture = jsonobjname.getJSONObject(Constants.PICTURE);
JSONObject jobjeventpicture = jobjectpicture.getJSONObject(Constants.DATA);
eventsbean.setUrl(jobjeventpicture.getString(Constants.URL));
if(jsonobjname.has(Constants.OWNER))
{
JSONObject owner_obj = jsonobjname.getJSONObject(Constants.OWNER);
eventsbean.setOwner_id(owner_obj.getString(Constants.OWNER_ID));
eventsbean.setOwner_name(owner_obj.getString(Constants.OWNER_NAME));
String owner_name = owner_obj.getString(Constants.OWNER_NAME);
Log.i(TAG, "Owner:" + owner_name);
}
if(!jsonobjname.isNull(Constants.COVER))
{
JSONObject objectcover = jsonobjname.getJSONObject(Constants.COVER);
eventsbean.setCover_id(objectcover.getString(Constants.COVER_ID));
eventsbean.setSource(objectcover.getString(Constants.SOURCE));
String cover_url = objectcover.getString(Constants.SOURCE);
Log.i(TAG, "Cover Url:" + cover_url);
eventsbean.setOffset_y(objectcover.getString(Constants.OFFSET_Y));
eventsbean.setOffset_x(objectcover.getString(Constants.OFFSET_X));
}
eventsbean.setName(jsonobjname.getString(Constants.NAME));
eventsbean.setEvent_id(jsonobjname.getString(Constants.EVENT_ID));
eventsbean.setStart_time(jsonobjname.getString(Constants.START_TIME));
eventsbean.setDescription(jsonobjname.getString(Constants.DESCRIPTION));
eventsbean.setLocation(jsonobjname.getString(Constants.LOCATION));
if(!jsonobjname.isNull(Constants.IS_SILHOUETTE))
{
eventsbean.setIs_silhouette(jsonobjname.getString(Constants.IS_SILHOUETTE));
}
eventsbean.setPrivacy(jsonobjname.getString(Constants.PRIVACY));
datetime = jsonobjname.getString(Constants.START_TIME);
if(!jsonobjname.isNull(Constants.VENUE))
{
JSONObject objectvenue = jsonobjname.getJSONObject(Constants.VENUE);
if(objectvenue.has(Constants.VENUE_NAME))
{
eventsbean.setVenue_name(objectvenue.getString(Constants.VENUE_NAME));
event_name = objectvenue.getString(Constants.VENUE_NAME);
Log.i(TAG, "Event Venue Name:" + event_name);
}
else
{
eventsbean.setLatitude(objectvenue.getString(Constants.LATITUDE));
eventsbean.setLongitude(objectvenue.getString(Constants.LONGITUDE));
eventsbean.setCity(objectvenue.getString(Constants.CITY));
eventsbean.setState(objectvenue.getString(Constants.STATE));
eventsbean.setCountry(objectvenue.getString(Constants.COUNTRY));
eventsbean.setVenue_id(objectvenue.getString(Constants.VENUE_ID));
eventsbean.setStreet(objectvenue.getString(Constants.STREET));
address = objectvenue.getString(Constants.STREET);
eventsbean.setZip(objectvenue.getString(Constants.ZIP));
}
}
arrayEventsBeans.add(eventsbean);
Log.i(TAG, "arry list values:" + arrayEventsBeans.size());
}
}
}
}catch(Exception e){
Log.e(TAG , "Exception Occured:" + e.getMessage());
}
return null;
}
class CompareDate implements Comparator<DateBean>{
#Override
public int compare(DateBean d1, DateBean d2) {
return d1.getDate().compareTo(d2.getDate());
}
}
#Override
protected void onProgressUpdate(Integer... values) {
// TODO Auto-generated method stub
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(Integer result)
{
// TODO Auto-generated method stub
super.onPostExecute(result);
if(this.progressdialog.isShowing())
{
this.progressdialog.dismiss();
}
if(adapter == null)
{
adapter = new SAmpleAdapter(EndlessScrollExample.this, 0, arrayEventsBeans);
listview.setAdapter(adapter);
}
else
{
adapter.notifyDataSetChanged();
}
//currentPage++;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
this.progressdialog.setMessage("Loading....");
this.progressdialog.setCanceledOnTouchOutside(false);
this.progressdialog.show();
}
public int setPage(int currentPage) {
return currentPage;
// TODO Auto-generated method stub
}
}
public class EndlessScrollListener implements OnScrollListener {
private int visibleThreshold = 0;
private int currentPage = 0;
public EndlessScrollListener() {
}
public EndlessScrollListener(int visibleThreshold) {
this.visibleThreshold = visibleThreshold;
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
}
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
if (scrollState == SCROLL_STATE_IDLE) {
if (listview.getLastVisiblePosition() >= listview.getCount() - visibleThreshold) {
currentPage++;
fetchValues.setPage(currentPage);
fetchValues.execute();
}
}
}
}
}
Thanks in advance.
ListView already supports OnScrollListener, so you have to override it and check the condition(in onScroll()), whether it is reached to the end of the list or not.If yes, then add a footer(optional) and fire the async task. After reciving the result notify the adapter. You could check solution on this link, it works on the same concept.
here are few examples of what you are looking for:
http://mobile.dzone.com/news/android-tutorial-dynamicaly
https://github.com/johannilsson/android-pulltorefresh

my app working fine on online but not working on offline help me

I want to make my application offline .When I am inserting data from url to database it works fine when internet available but my app not show any thing in gridview when no internet available what is wrong in my app please help me why gridview not loading data from database help me
public class MainActivity extends Activity {
CategoryListAdapter3 cla;
static ArrayList<String> Category_ID = new ArrayList<String>();
static ArrayList<String> Category_name = new ArrayList<String>();
static ArrayList<String> Category_image = new ArrayList<String>();
String URL, URL2;
String SelectMenuAPI;
String _response;
String status;
GridView gridview;
private DbHelper mHelper;
private SQLiteDatabase dataBase;
private boolean isUpdate;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mHelper=new DbHelper(this);
dataBase=mHelper.getWritableDatabase();
gridview = (GridView) findViewById(R.id.gridview);
cla = new CategoryListAdapter3(MainActivity.this);
new TheTask().execute();
gridview.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1,
int position, long arg3) {
// TODO Auto-generated method stub
Intent iMenuList = new Intent(MainActivity.this,
Subcategory.class);
iMenuList.putExtra("Category_ID", Category_ID.get(position));
iMenuList.putExtra("Category_name", Category_name.get(position));
startActivity(iMenuList);
}
});
}
void clearData() {
Category_ID.clear();
Category_name.clear();
Category_image.clear();
}
public class TheTask extends AsyncTask<Void, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(Void... arg0) {
SelectMenuAPI = "http://www.fff/mobile_api.php?response=getmaincategories";
clearData();
URL = SelectMenuAPI;
URL2 = URL.replace(" ", "%20");
try {
Log.i("url", "" + URL2);
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(URL2);
HttpResponse response = client.execute(request);
HttpEntity resEntity = response.getEntity();
_response = EntityUtils.toString(resEntity);
} catch (Exception e) {
e.printStackTrace();
}
return _response;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
try {
JSONObject json2 = new JSONObject(result);
status = json2.getString("Status");
if (status.equals("1")) {
JSONArray school2 = json2.getJSONArray("data");
//
for (int i = 0; i < school2.length(); i++) {
JSONObject object = school2.getJSONObject(i);
String id = object.getString("category_id");
String name =object.getString("name");
String image_path = object.getString("image_path");
dataBase=mHelper.getWritableDatabase();
ContentValues values=new ContentValues();
values.put(DbHelper.KEY_MYID,id);
values.put(DbHelper.KEY_FNAME,name);
values.put(DbHelper.KEY_LNAME,image_path );
System.out.println("");
if(isUpdate)
{
//update database with new data
dataBase.update(DbHelper.TABLE_NAME, values, DbHelper.KEY_ID+"="+id, null);
}
else
{
//insert data into database
dataBase.insert(DbHelper.TABLE_NAME, null, values);
}
//close database
dataBase.close();
}
}
else {
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
displayData();
}
}
private void displayData() {
dataBase = mHelper.getWritableDatabase();
Cursor mCursor = dataBase.rawQuery("SELECT * FROM "
+ DbHelper.TABLE_NAME, null);
//
// Category_ID.clear();
// Category_name.clear();
// Category_image.clear();
if (mCursor.moveToFirst()) {
do {
Category_ID.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_ID)));
Category_name.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_FNAME)));
Category_image.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_LNAME)));
} while (mCursor.moveToNext());
}
gridview.setAdapter(cla);
mCursor.close();
}
public class DbHelper extends SQLiteOpenHelper {
static String DATABASE_NAME="userdata";
public static final String TABLE_NAME="user";
public static final String KEY_FNAME="fname";
public static final String KEY_LNAME="lname";
public static final String KEY_ID="id";
public static final String KEY_MYID="myid";
public DbHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_TABLE="CREATE TABLE "+TABLE_NAME+" ("+KEY_ID+" INTEGER PRIMARY
KEY,"+KEY_MYID+" TEXT, "+KEY_FNAME+" TEXT, "+KEY_LNAME+" BLOB)";
db.execSQL(CREATE_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME);
onCreate(db);
}
}
public class CategoryListAdapter3 extends BaseAdapter {
private Activity activity;
private AQuery androidAQuery;
public CategoryListAdapter3(Activity act) {
this.activity = act;
// imageLoader = new ImageLoader(act);
}
public int getCount() {
// TODO Auto-generated method stub
return MainActivity.Category_ID.size();
}
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ViewHolder holder;
androidAQuery = new AQuery(getcontext());
if(convertView == null){
LayoutInflater inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.viewitem2, null);
holder = new ViewHolder();
convertView.setTag(holder);
}else{
holder = (ViewHolder) convertView.getTag();
}
holder.txtText = (TextView) convertView.findViewById(R.id.title2);
holder.imgThumb = (ImageView) convertView.findViewById(R.id.image2);
holder.txtText.setText(MainActivity.Category_name.get(position));
a
ndroidAQuery.id(holder.imgThumb).image(MainActivity.Category_image.get(position), true,
true);
return convertView;
}
private Activity getcontext() {
// TODO Auto-generated method stub
return null;
}
static class ViewHolder {
TextView txtText;
ImageView imgThumb;
}
}
check internet Availability before web service call:
public static boolean isInternetAvailable(Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
return true;
}
return false;
}
You have called displayData() only in onPostExecute, so the data is displayed in grid only when you receive data from that URL.
Solution: Call the displayData() once in onCreate function before new TheTask().execute(). So now data will be displayed from the DB if available and then fetch from that URL using HTTPClient. If no internet then the data will still be displayed.
Note: Make sure the cursor size greater than 0 inside displayData(), else display no data text instead of grid view.
happy coding :)
This is quite obvious, You are actually calling you displayData() in postExecute, but in case of no internet, exception will occur you doInBackgroud and null will be passed to postExecute...Exception again in postExecute and your displayData() will not be called.
So first, implement checks for null values to avoid exceptions, and then close try closing you db in catch block.

Async Task Loader, Google Cloud Messaging , Sync Adapter not connected properly, Array Adapter

I am working on an application that requires data to be displayed on a listview. The data to be displayed on the listview needs to be updated frequently so i created a sync-adapter which will be triggered my a broadcast message from gcm. When this occurs my AsyncTask loader.onContentChanged is called which call the loadinbackground method and all this works properly. The issues i am having is displaying the new data on the listview without restarting the activity. i am trying to get it to work like facebook news feed listview.
Please help me
My codes are as follows
SyncAdapter
#Override
public void onPerformSync(Account account, Bundle extras, String authority,
ContentProviderClient provider, SyncResult syncResult) {
// TODO Auto-generated method stub
Log.d(TAG, "onPerformSync for account[" + account.name + "]");
String theValue = mAccountManager.getUserData(account, "User_ID");
mContentResolver = mContext.getContentResolver();
final RoomListLoader mLoader = new RoomListLoader(mContext, theValue);
mLoader.onContentChanged();
}
Loader
public class RoomListLoader extends AsyncTaskLoader<List<RoomList>> {
private static String url = "********************";
int success;
private static final String TAG_SUCCESS = "success";
private static final String TAG_ROOMS = "room";
String room_id = null, roomTitle, created_at, user_id, room_ids,
clickedOnRoomId, retrievedRoomId, username;
String room_title, reward, numOfComments, filePath;
JSONParser jsonParser = new JSONParser();
JSONObject json;
JSONArray rooms = null;
JSONArray ids = null;
int i = 0, c = 0, tryme = 0, tryme2 = 0;
int co = 0, counterOnGetRooms = 0;
RoomList details;
public static List<RoomList> mRoomList = new ArrayList<RoomList>();
Context mContext;
//private final Handler observerHandler;
public RoomListLoader(Context context,String nuser_id) {
super(context);
// TODO Auto-generated constructor stub
//mRoomList = nRoomList;
this.user_id = nuser_id;
this.mContext = context;
//observerHandler = new Handler();
}
#Override
public List<RoomList> loadInBackground() {
// TODO Auto-generated method stub
mRoomList.clear();
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("user_id", user_id));
json = jsonParser.makeHttpRequest(url, "POST", params);
// final Context context = getContext();
try {
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
rooms = json.getJSONArray(TAG_ROOMS);
// counter = json.getInt("counter");
counterOnGetRooms = json.getInt("count");
Log.d("counterOnGetRooms", "" + counterOnGetRooms);
// Log.v("counter", "" + counter);
for (int i = 0; i < rooms.length(); i++) {
tryme2++;
JSONObject c = rooms.getJSONObject(i);
// get room titles
roomTitle = c.getString("room_title");
retrievedRoomId = c.getString("room_id");
created_at = c.getString("created_at");
username = c.getString("username");
numOfComments = c.getString("counters");
filePath = c.getString("filePath");
Log.i("filePath", filePath);
details = new RoomList(retrievedRoomId, roomTitle,
created_at, username, numOfComments, filePath);
mRoomList.add(details);
}
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//MostRecentRooms Room;
//deliverResult(mRoomList);
return mRoomList;
}
#Override
public void onContentChanged() {
// TODO Auto-generated method stub
super.onContentChanged();
loadInBackground();
//deliverResult(mRoomList);
}
#Override
public void onCanceled(List<RoomList> data) {
// TODO Auto-generated method stub
super.onCanceled(data);
}
#Override
public void deliverResult(List<RoomList> data) {
// TODO Auto-generated method stub
Log.d("Deliver Result",""+data.size());
super.deliverResult(data);
}
#Override
protected void onReset() {
// TODO Auto-generated method stub
super.onReset();
onStopLoading();
}
#Override
protected void onStartLoading() {
// TODO Auto-generated method stub
if (mRoomList != null) {
//deliverResult(mRoomList);
}
super.onStartLoading();
}
#Override
protected void onStopLoading() {
// TODO Auto-generated method stub
cancelLoad();
}
}
Activity
public class MostRecentRooms extends ListActivity implements LoaderManager.LoaderCallbacks<List<RoomList>> {
// progress dialog
ProgressDialog pDialog;
// json parser object
JSONParser jsonParser = new JSONParser();
int decrement = 0;
int success;
int s = 0;
Activity mActivity;
// url to view most recent rooms
private static String url = "************8";
// url to load more rooms
private static String url3 = "***************";
// url to check status of user
private static String url2 = "*****************";
// url to get profile images
private static String url4 = "****************88";
private static final String TAG_SUCCESS = "success";
private static final String TAG_ROOMS = "room";
int Loader_ID =0x3;
int counter = 0;
HashMap<String, String> map;
public static List<RoomList> mRoomList = new ArrayList<RoomList>();
RoomList details;
ListAdapter adapter;
public static RoomListAdapter mAdapter;
public static LoaderManager mLoadManager;
// json arrays
JSONArray rooms = null;
JSONArray ids = null;
int i = 0, c = 0, tryme = 0, tryme2 = 0;
int co = 0, counterOnGetRooms = 0;
// Array list to hold room titles
ArrayList<HashMap<String, String>> allRooms;
// ArrayList<String> allRooms;
// List view to show room titles of an arraylist
public ListView lv;
// json Object
JSONObject json;
int limit = 20;
// strings
String room_id = null, roomTitle, created_at, user_id, room_ids,
clickedOnRoomId, retrievedRoomId, username;
String room_title, reward, numOfComments, filePath;
// buttons
Button back, loadMore, refresh;
Bitmap img_bitmap;
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_most_recent_rooms);
mLoadManager = getLoaderManager();
mAdapter = new RoomListAdapter(this, getApplicationContext());
lv= getListView();
lv.setAdapter(mAdapter);
// back button
back = (Button) findViewById(R.id.backToMainMenu);
back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
finish();
}
});
// end back button
// get user id from View rooms class
if (getIntent().getExtras().getString("user_id_value") != null)
user_id = getIntent().getExtras().getString("user_id_value");
else
Log.e("Error", "Missing user_id");
mLoadManager.initLoader(Loader_ID,null,MostRecentRooms.this);
//allRooms = new ArrayList<HashMap<String, String>>();
// allRooms = new ArrayList<String>();
// call class GetAllRooms
//new GetAllRooms().execute();
// get room_id
if (getIntent().getExtras().getString("room_id_to_send") != null)
room_id = getIntent().getExtras().getString("room_id_to_send");
else
Log.e("Error", "Missing room id");
loadMore = (Button) findViewById(R.id.loadMore);
loadMore.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//new LoadMoreRooms().execute();
// counter -= 5;
}
});
refresh = (Button) findViewById(R.id.refresh);
refresh.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
mRoomList.clear();
allRooms.clear();
limit = 20;
tryme = 0;
img_bitmap.recycle();
//new GetAllRooms().execute();
}
});
}
/**
* This class get users status whether deleted or not
*/
class GetUserStatus extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... args) {
// TODO Auto-generated method stub
backGroundProcess(user_id);
return null;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
Log.e("i is", "" + i);
if (i == 2) {
// decativatedPage();
Toast.makeText(getApplicationContext(), "noooo",
Toast.LENGTH_SHORT).show();
} else {
Intent i = new Intent(getApplicationContext(), RoomPage.class);
i.putExtra("room_id_to_send", clickedOnRoomId);
i.putExtra("user_id_value", user_id);
startActivity(i);
}
}
}// end class
private void backGroundProcess(String string) {
// build parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("user_id", string));
json = jsonParser.makeHttpRequest(url2, "POST", params);
int success;
try {
success = json.getInt("success");
if (success == 1) {
i = 1;
Log.i("status", json.getString("message").toString());
} else if (success == 2) {
i = 2;
} else {
Log.d("Error", "Something went wrong");
}
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public Loader<List<RoomList>> onCreateLoader(int id, Bundle args) {
// TODO Auto-generated method stub
Log.d("Tsg", "here");
RoomListLoader mRoomloader = new RoomListLoader(getApplicationContext(), user_id);
mRoomloader.forceLoad();
return mRoomloader ;
}
#Override
public void onLoadFinished(Loader<List<RoomList>> arg0, List<RoomList> data) {
// TODO Auto-generated method stub
Log.i("tag","list loaded");
if(data != null){
mAdapter.SetData(data);
mAdapter.notifyDataSetChanged();
}
//mAdapter.SetData(data);
Log.i("Tag",""+data.size());
//lv.setAdapter(mAdapter);
}
#Override
public void onLoaderReset(Loader<List<RoomList>> arg0) {
// TODO Auto-generated method stub
Log.d("Loader", "Loader Reset");
mAdapter.SetData(null);
}
}
Adapter
public class RoomListAdapter extends ArrayAdapter<RoomList> {
ImageLoader imageLoader = null;
private Activity activity;
String TAG = "RoomListAdapter";
private final LayoutInflater mInflator;
List<RoomList> nRoomList;
public RoomListAdapter(Activity a, Context context) {
// TODO Auto-generated constructor stub
super(context, R.layout.viewroom_layout);
activity = a;
mInflator = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
imageLoader = new ImageLoader(a.getApplicationContext());
//nRoomList = mRoomList;
//SetData(nRoomList);
}
public void SetData(List<RoomList> data) {
clear();
if (data != null) {
addAll(data);
}
}
#Override
public void notifyDataSetChanged() {
// TODO Auto-generated method stub
super.notifyDataSetChanged();
}
#Override
public void setNotifyOnChange(boolean notifyOnChange) {
// TODO Auto-generated method stub
super.setNotifyOnChange(notifyOnChange);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View vi;
if (convertView == null) {
vi = mInflator.inflate(R.layout.viewroom_layout, null);
} else {
vi = convertView;
}
TextView room_id = (TextView) vi.findViewById(R.id.roomsIDHidden);
TextView room_title = (TextView) vi.findViewById(R.id.roomsName);
TextView created_at = (TextView) vi.findViewById(R.id.createdTime);
TextView username = (TextView) vi.findViewById(R.id.creatorName);
TextView numOfComments = (TextView) vi.findViewById(R.id.numComments);
ImageView image = (ImageView) vi.findViewById(R.id.userPic);
//Log.d(TAG, "Within the room list adapter");
RoomList info = getItem(position);
room_id.setText(info.getmRoom_id());
room_title.setText(info.getmRoomTitle());
created_at.setText(info.getmCreated_at());
username.setText(info.getmUsername());
numOfComments.setText(info.getmNumberOfComments());
imageLoader.DisplayImage(info.getmFilePath(), image);
return vi;
}
}
with the help of venkat and monica i solved it didn't need the Syncadpter all i needed was a broadcast receiver this i did by
1) creating a broad cast intent when GCM receives the message
Intent intent1 = new Intent();
intent1.setAction("com.gcm.updatecame");
this.sendBroadcast(intent1);
2) in my Activity i register the receiver and create the class
filter1= new IntentFilter("com.gcm.updatecame");
registerReceiver(myReceiver, filter1);
Broadcast Receiver
private BroadcastReceiver myReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// write your code here to update the listview.
if(mLoadManager != null){
Reload.setVisibility(View.VISIBLE);
Reload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
mLoadManager.destroyLoader(Loader_ID);
mAdapter.notifyDataSetChanged();
mAdapter.SetData(null);
mRoomList.clear();
mLoadManager.initLoader(Loader_ID, null, MostRecentRooms.this);
Reload.setVisibility(View.INVISIBLE);
}
});
}
}
};
Replace you onLoadFinished method with this one:
#Override
public void onLoadFinished(Loader<List<RoomList>> arg0, List<RoomList> data) {
if(data != null){
mAdapter = new RoomListAdapter(this, getApplicationContext());
mAdapter.SetData(data);
lv.setAdapter(mAdapter);
}
}

Categories

Resources