First message is duplicated - android

I've been working on a messaging app and within the group and private chat, the first message duplicates and then when another message is sent, it's hidden behind the duplicated text until another one is sent and then so on. Can anybody help me with this problem? I'm using Quickblox as a database
ChatMessage Class
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.app.AlertDialog;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.Toast;
import com.liftersheaven.messaging.Adapter.ChatMessageAdapter;
import com.liftersheaven.messaging.Common.Common;
import com.liftersheaven.messaging.Holder.QBChatMessagesHolder;
import com.quickblox.chat.QBChatService;
import com.quickblox.chat.QBIncomingMessagesManager;
import com.quickblox.chat.QBRestChatService;
import com.quickblox.chat.exception.QBChatException;
import com.quickblox.chat.listeners.QBChatDialogMessageListener;
import com.quickblox.chat.model.QBChatDialog;
import com.quickblox.chat.model.QBChatMessage;
import com.quickblox.chat.model.QBDialogType;
import com.quickblox.chat.request.QBDialogRequestBuilder;
import com.quickblox.chat.request.QBMessageGetBuilder;
import com.quickblox.chat.request.QBMessageUpdateBuilder;
import com.quickblox.core.QBEntityCallback;
import com.quickblox.core.exception.QBResponseException;
import org.jivesoftware.smack.SmackException;
import org.jivesoftware.smackx.muc.DiscussionHistory;
import java.util.ArrayList;
public class ChatMessage extends AppCompatActivity implements
QBChatDialogMessageListener{
QBChatDialog qbChatDialog;
ListView lstChatMessages;
ImageButton submitButton;
EditText edtContent;
ChatMessageAdapter adapter;
int contextMenuIndexClicked = -1;
boolean isEditMode = false;
QBChatMessage editMessage;
Toolbar toolbar;
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId()){
case R.id.chat_group_edit_name:
editNameGroup();
break;
case R.id.chat_group_add_user:
addUser();
break;
case R.id.chat_group_remove_user:
removeUser();
break;
}
return true;
}
private void removeUser() {
Intent intent = new Intent(this,ListUsers.class);
intent.putExtra(Common.UPDATE_DIALOG_EXTRA, qbChatDialog);
intent.putExtra(Common.UPDATE_MODE, Common.UPDATE_REMOVE_MODE);
startActivity(intent);
}
private void addUser() {
Intent intent = new Intent(this,ListUsers.class);
intent.putExtra(Common.UPDATE_DIALOG_EXTRA, qbChatDialog);
intent.putExtra(Common.UPDATE_MODE,Common.UPDATE_ADD_MODE);
startActivity(intent);
}
private void editNameGroup() {
LayoutInflater inflater = LayoutInflater.from(this);
View view = inflater.inflate(R.layout.dialog_edit_group_layout, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setView(view);
final EditText newName = (EditText) view.findViewById(R.id.edt_group_name);
alertDialogBuilder.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
qbChatDialog.setName(newName.getText().toString());
QBDialogRequestBuilder requestBuilder = new QBDialogRequestBuilder();
QBRestChatService.updateGroupChatDialog(qbChatDialog, requestBuilder)
.performAsync(new QBEntityCallback<QBChatDialog>() {
#Override
public void onSuccess(QBChatDialog qbChatDialog, Bundle bundle) {
Toast.makeText(ChatMessage.this, "Group name edited", Toast.LENGTH_SHORT);
toolbar.setTitle(qbChatDialog.getName());
}
#Override
public void onError(QBResponseException e) {
Toast.makeText(getBaseContext(), ""+e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
if (qbChatDialog.getType() == QBDialogType.GROUP || qbChatDialog.getType() == QBDialogType.PUBLIC_GROUP)
getMenuInflater().inflate(R.menu.chat_message_group_menu, menu);
return true;
}
#Override
public boolean onContextItemSelected(MenuItem item){
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)item.getMenuInfo();
contextMenuIndexClicked = info.position;
switch (item.getItemId()){
case R.id.chat_message_update:
updateMessage();
break;
case R.id.chat_message_delete:
deleteMessage();
break;
}
return true;
}
private void deleteMessage() {
final ProgressDialog deleteDialog = new ProgressDialog(ChatMessage.this);
deleteDialog.setMessage("Please wait...");
deleteDialog.show();
editMessage = QBChatMessagesHolder.getInstance().getChatMessagesByDialogId(qbChatDialog.getDialogId())
.get(contextMenuIndexClicked);
QBRestChatService.deleteMessage(editMessage.getId(),false).performAsync(new QBEntityCallback<Void>() {
#Override
public void onSuccess(Void aVoid, Bundle bundle) {
retrieveAllMessage();
deleteDialog.dismiss();
}
#Override
public void onError(QBResponseException e) {
}
});
}
private void updateMessage() {
editMessage = QBChatMessagesHolder.getInstance().getChatMessagesByDialogId(qbChatDialog.getDialogId())
.get(contextMenuIndexClicked);
edtContent.setText(editMessage.getBody());
isEditMode = true;
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo){
getMenuInflater().inflate(R.menu.chat_message_content_menu, menu);
}
#Override
protected void onDestroy(){
super.onDestroy();
qbChatDialog.removeMessageListrener(this);
}
#Override
protected void onStop(){
super.onStop();
qbChatDialog.removeMessageListrener(this);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat_message);
initViews();
initChatDialogs();
retrieveAllMessage();
submitButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!edtContent.getText().toString().isEmpty()){
if (!isEditMode) {
QBChatMessage chatMessage = new QBChatMessage();
chatMessage.setBody(edtContent.getText().toString());
chatMessage.setSenderId(QBChatService.getInstance().getUser().getId());
chatMessage.setSaveToHistory(true);
try {
qbChatDialog.sendMessage(chatMessage);
} catch (SmackException.NotConnectedException e) {
e.printStackTrace();
}
if (qbChatDialog.getType() == QBDialogType.PRIVATE){
QBChatMessagesHolder.getInstance().putMessage(qbChatDialog.getDialogId(),chatMessage);
ArrayList<QBChatMessage> messages = QBChatMessagesHolder.getInstance().getChatMessagesByDialogId(chatMessage.getDialogId());
adapter = new ChatMessageAdapter(getBaseContext(),messages);
lstChatMessages.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
edtContent.setText("");
edtContent.setFocusable(true);
}else
{
final ProgressDialog updateDialog = new ProgressDialog(ChatMessage.this);
updateDialog.setMessage("Please wait...");
updateDialog.show();
QBMessageUpdateBuilder messageUpdateBuilder = new QBMessageUpdateBuilder();
messageUpdateBuilder.updateText(edtContent.getText().toString()).markDelivered().markRead();
QBRestChatService.updateMessage(editMessage.getId(),qbChatDialog.getDialogId(),messageUpdateBuilder)
.performAsync(new QBEntityCallback<Void>() {
#Override
public void onSuccess(Void aVoid, Bundle bundle) {
retrieveAllMessage();
isEditMode = false;
updateDialog.dismiss();
edtContent.setText("");
edtContent.setFocusable(true);
}
#Override
public void onError(QBResponseException e) {
Toast.makeText(getBaseContext(),""+e.getMessage(),Toast.LENGTH_SHORT).show();
}
});
}
}
}
});
}
private void retrieveAllMessage() {
QBMessageGetBuilder messageGetBuilder = new QBMessageGetBuilder();
messageGetBuilder.setLimit(500);
if(qbChatDialog != null){
QBRestChatService.getDialogMessages(qbChatDialog,messageGetBuilder).performAsync(new QBEntityCallback<ArrayList<QBChatMessage>>() {
#Override
public void onSuccess(ArrayList<QBChatMessage> qbChatMessages, Bundle bundle) {
QBChatMessagesHolder.getInstance().putMessages(qbChatDialog.getDialogId(),qbChatMessages);
adapter = new ChatMessageAdapter(getBaseContext(),qbChatMessages);
lstChatMessages.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
#Override
public void onError(QBResponseException e) {
}
});
}
}
private void initChatDialogs() {
qbChatDialog = (QBChatDialog)getIntent().getSerializableExtra(Common.DIALOG_EXTRA);
qbChatDialog.initForChat(QBChatService.getInstance());
QBIncomingMessagesManager incomingMessage = QBChatService.getInstance().getIncomingMessagesManager();
incomingMessage.addDialogMessageListener(new QBChatDialogMessageListener() {
#Override
public void processMessage(String s, QBChatMessage qbChatMessage, Integer integer) {
}
#Override
public void processError(String s, QBChatException e, QBChatMessage qbChatMessage, Integer integer) {
}
});
if (qbChatDialog.getType() == QBDialogType.PUBLIC_GROUP || qbChatDialog.getType() == QBDialogType.GROUP){
DiscussionHistory discussionHistory = new DiscussionHistory();
discussionHistory.setMaxStanzas(0);
qbChatDialog.join(discussionHistory, new QBEntityCallback() {
#Override
public void onSuccess(Object o, Bundle bundle) {
}
#Override
public void onError(QBResponseException e) {
Log.d("ERROR", ""+e.getMessage());
}
});
}
qbChatDialog.addMessageListener(this);
toolbar.setTitle(qbChatDialog.getName());
setSupportActionBar(toolbar);
}
private void initViews() {
lstChatMessages = (ListView)findViewById(R.id.messages_list);
submitButton = (ImageButton)findViewById(R.id.send);
edtContent = (EditText)findViewById(R.id.edt_content);
registerForContextMenu(lstChatMessages);
toolbar = (Toolbar)findViewById(R.id.chatmessage_toolbar);
}
#Override
public void processMessage(String s, QBChatMessage qbChatMessage, Integer integer) {
QBChatMessagesHolder.getInstance().putMessage(qbChatMessage.getDialogId(),qbChatMessage);
ArrayList<QBChatMessage> messages = QBChatMessagesHolder.getInstance().getChatMessagesByDialogId(qbChatMessage.getDialogId());
adapter = new ChatMessageAdapter(getBaseContext(),messages);
lstChatMessages.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
#Override
public void processError(String s, QBChatException e, QBChatMessage qbChatMessage, Integer integer) {
Log.e("ERROR",""+e.getMessage());
}
}
ChatMessageAdapter Class
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.github.library.bubbleview.BubbleTextView;
import com.liftersheaven.messaging.Holder.QBUsersHolder;
import com.liftersheaven.messaging.R;
import com.quickblox.chat.QBChatService;
import com.quickblox.chat.model.QBChatMessage;
import java.util.ArrayList;
public class ChatMessageAdapter extends BaseAdapter {
private Context context;
private ArrayList<QBChatMessage> qbChatMessages;
public ChatMessageAdapter(Context context, ArrayList<QBChatMessage> qbChatMessages){
this.context = context;
this.qbChatMessages = qbChatMessages;
}
#Override
public int getCount() {
return qbChatMessages.size();
}
#Override
public Object getItem(int position) {
return qbChatMessages.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if (convertView == null){
LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (qbChatMessages.get(position).getSenderId().equals(QBChatService.getInstance().getUser().getId())){
view = inflater.inflate(R.layout.list_message_send, null);
BubbleTextView bubbleTextView = (BubbleTextView)view.findViewById(R.id.message_content);
bubbleTextView.setText(qbChatMessages.get(position).getBody());
}
else{
view = inflater.inflate(R.layout.list_recieve_message, null);
BubbleTextView bubbleTextView = (BubbleTextView)view.findViewById(R.id.message_recieve);
bubbleTextView.setText(qbChatMessages.get(position).getBody());
TextView txtName = (TextView)view.findViewById(R.id.message_user);
txtName.setText(QBUsersHolder.getInstance().getUserById(qbChatMessages.get(position).getSenderId()).getFullName());
}
}
return view;
}
}
QBChatMessagesHolder Class
import com.quickblox.chat.model.QBChatMessage;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class QBChatMessagesHolder {
private static QBChatMessagesHolder instance;
private HashMap<String,ArrayList<QBChatMessage>> qbChatMessageArray;
public static synchronized QBChatMessagesHolder getInstance(){
QBChatMessagesHolder qbChatMessagesHolder;
synchronized (QBChatMessagesHolder.class){
if (instance == null)
instance = new QBChatMessagesHolder();
qbChatMessagesHolder = instance;
}
return qbChatMessagesHolder;
}
private QBChatMessagesHolder(){
this.qbChatMessageArray = new HashMap<>();
}
public void putMessages(String dialogId,ArrayList<QBChatMessage> qbChatMessages){
this.qbChatMessageArray.put(dialogId,qbChatMessages);
}
public void putMessage(String dialogId,QBChatMessage qbChatMessage){
List<QBChatMessage> lstResult = (List)this.qbChatMessageArray.get(dialogId);
lstResult.add(qbChatMessage);
ArrayList<QBChatMessage> lstAdded = new ArrayList(lstResult.size());
lstAdded.addAll(lstResult);
putMessages(dialogId, lstAdded);
}
public ArrayList<QBChatMessage> getChatMessagesByDialogId(String dialogId){
return (ArrayList<QBChatMessage>)this.qbChatMessageArray.get(dialogId);
}
}

Related

ListView displays data twice

I am working on a small application to save the data of the book (such as the name of the book, the type of the book, the author of the book and the year of publication) in a database, but when the data is returned from the databases using CursorLoader It's shown twice in ListView
This is a code of AddBook activity.
package training.android.com.librarycard;
import android.app.AlertDialog;
import android.app.LoaderManager;
import android.content.ContentValues;
import android.content.CursorLoader;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.Loader;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
import training.android.com.librarycard.Database.Database;
import training.android.com.librarycard.Database.LibraryCardContract;
public class AddBook extends AppCompatActivity
implements LoaderManager.LoaderCallbacks<Cursor> {
private static final int EXISTING_BOOK_LOADER = 0;
Spinner mBookType;
EditText mBookTitle, mBookAuthor, mBookPublishYear;
String bookType;
int position;
private boolean bookHasChanged = false;
private Uri currentBookUri;
private View.OnTouchListener touchListener = new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
bookHasChanged = true;
return false;
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_book);
Intent intent = getIntent();
if (intent != null) {
currentBookUri = intent.getData();
if (currentBookUri == null) {
setTitle("Add a book");
invalidateOptionsMenu();
} else {
setTitle("Edit a book");
getLoaderManager().initLoader(EXISTING_BOOK_LOADER, null, this);
}
}
mBookType = findViewById(R.id.spinner);
mBookTitle = findViewById(R.id.book_title);
mBookAuthor = findViewById(R.id.book_author);
mBookPublishYear = findViewById(R.id.publish_year);
mBookType.setOnTouchListener(touchListener);
mBookAuthor.setOnTouchListener(touchListener);
mBookTitle.setOnTouchListener(touchListener);
mBookPublishYear.setOnTouchListener(touchListener);
setupBookTypeSpinner();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.home, menu);
return true;
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
if (currentBookUri == null) {
MenuItem menuItem = menu.findItem(R.id.action_delete);
menuItem.setVisible(false);
}
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch (id) {
case R.id.action_save:
setBook();
finish();
return true;
case R.id.action_delete:
showDeleteConfirmationDialog();
return true;
case android.R.id.home:
if (!bookHasChanged) {
NavUtils.navigateUpFromSameTask(AddBook.this);
return true;
}
DialogInterface.OnClickListener discardButtonClickListener
= new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
NavUtils.navigateUpFromSameTask(AddBook.this);
}
};
showUnsavedChangeDialog(discardButtonClickListener);
return true;
}
return super.onOptionsItemSelected(item);
}
private void showUnsavedChangeDialog(DialogInterface.OnClickListener discardButtonClickListener) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Discard your changes and quit editing?");
builder.setPositiveButton("Discard", discardButtonClickListener);
builder.setNegativeButton("Keep editing", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (dialog != null)
dialog.dismiss();
}
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
private void showDeleteConfirmationDialog() {
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Delete this book ?");
builder.setPositiveButton("Delete", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
deleteBook();
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (dialog != null)
dialog.dismiss();
}
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
private void deleteBook() {
if (currentBookUri != null) {
int rowDeleted = getContentResolver().delete(currentBookUri, null, null);
if (rowDeleted == 0)
Toast.makeText(this, "Delete book failed", Toast.LENGTH_SHORT).show();
else
Toast.makeText(this, "Delete book successful", Toast.LENGTH_SHORT).show();
}
finish();
}
public void setupBookTypeSpinner() {
final ArrayAdapter<CharSequence> bookTypeAdapter = ArrayAdapter.createFromResource(
this, R.array.books_type, R.layout.support_simple_spinner_dropdown_item);
bookTypeAdapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
mBookType.setAdapter(bookTypeAdapter);
mBookType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
bookType = parent.getSelectedItem().toString();
position = parent.getSelectedItemPosition();
Log.i("BookTypeSelection", bookType+"");
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
public void setBook() {
String bookTitle = mBookTitle.getText().toString().trim();
String bookAuthor = mBookAuthor.getText().toString().trim();
String publishYear = mBookPublishYear.getText().toString().trim();
if (currentBookUri == null && TextUtils.isEmpty(bookTitle) && TextUtils.isEmpty(bookAuthor)
&& TextUtils.isEmpty(publishYear))
return;
Database database = new Database(this);
SQLiteDatabase db = database.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(LibraryCardContract.LibraryCard.COLUMN_BOOK_TITLE, bookTitle);
values.put(LibraryCardContract.LibraryCard.COLUMN_BOOK_AUTHOR, bookAuthor);
values.put(LibraryCardContract.LibraryCard.COLUMN_BOOK_PUBLISH_YEAR, publishYear);
values.put(LibraryCardContract.LibraryCard.COLUMN_BOOK_TYPE, bookType);
if (currentBookUri == null) {
Uri uri = getContentResolver().insert(LibraryCardContract.LibraryCard.CONTENT_URI, values);
if (uri == null) {
Toast.makeText(this, "Error with saving book", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Book saved", Toast.LENGTH_SHORT).show();
}
} else {
int rowAffected = getContentResolver().update(currentBookUri, values, null, null);
if (rowAffected == 0) {
Toast.makeText(this, "Error with saving book", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Book saved", Toast.LENGTH_SHORT).show();
}
}
db.insert(LibraryCardContract.LibraryCard.TABLE_NAME, null, values);
Toast.makeText(this, "Insert new book", Toast.LENGTH_SHORT).show();
}
#Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
String [] projection = {
LibraryCardContract.LibraryCard.COLUMN_BOOK_TITLE,
LibraryCardContract.LibraryCard.COLUMN_BOOK_TYPE,
LibraryCardContract.LibraryCard.COLUMN_BOOK_AUTHOR,
LibraryCardContract.LibraryCard.COLUMN_BOOK_PUBLISH_YEAR };
return new CursorLoader(this,currentBookUri,projection,
null,null,null);
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
if(data.moveToFirst()){
String title = data.getString(
data.getColumnIndexOrThrow(LibraryCardContract.LibraryCard.COLUMN_BOOK_TITLE));
String type = data.getString(
data.getColumnIndexOrThrow(LibraryCardContract.LibraryCard.COLUMN_BOOK_TYPE));
String publishYear = data.getString(
data.getColumnIndexOrThrow(LibraryCardContract.LibraryCard.COLUMN_BOOK_PUBLISH_YEAR));
String author = data.getString(
data.getColumnIndexOrThrow(LibraryCardContract.LibraryCard.COLUMN_BOOK_AUTHOR));
mBookTitle.setText(title);
mBookAuthor.setText(author);
mBookType.setSelection(position);
mBookPublishYear.setText(publishYear);
}
}
#Override
public void onLoaderReset(Loader<Cursor> loader) {
mBookTitle.setText("");
mBookType.setSelection(position);
mBookAuthor.setText("");
mBookPublishYear.setText("");
}
#Override
public void onBackPressed() {
if(!bookHasChanged){
super.onBackPressed();
return;
}
DialogInterface.OnClickListener discardButtonClickListener =
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
};
showUnsavedChangeDialog(discardButtonClickListener);
}
}
And this is a code of Home activity that contains a listView to
display the data.
package training.android.com.librarycard;
import android.app.LoaderManager;
import android.content.ContentUris;
import android.content.CursorLoader;
import android.content.Intent;
import android.content.Loader;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.List;
import training.android.com.librarycard.Database.Database;
import training.android.com.librarycard.Database.LibraryCardContract;
import training.android.com.librarycard.Models.BookCursorAdapter;
import training.android.com.librarycard.Models.BookDetail;
public class Home extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener, LoaderManager.LoaderCallbacks<Cursor> {
private static final int BOOK_LOADER = 0;
private ListView mBookList;
private BookCursorAdapter cursorAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mBookList = findViewById(R.id.books_rv);
cursorAdapter = new BookCursorAdapter(this, null);
mBookList.setAdapter(cursorAdapter);
mBookList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(Home.this, AddBook.class);
Uri currentPetUri = ContentUris.withAppendedId(LibraryCardContract.LibraryCard.CONTENT_URI, id);
intent.setData(currentPetUri);
startActivity(intent);
}
});
getLoaderManager().initLoader(BOOK_LOADER, null, this);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(getBaseContext(), AddBook.class);
startActivity(intent);
}
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
switch (id) {
case R.id.delete_all_books:
deleteAllBooks();
return true;
}
//noinspection SimplifiableIfStatement
return super.onOptionsItemSelected(item);
}
private void deleteAllBooks() {
int rowDeleted = getContentResolver().delete(LibraryCardContract.LibraryCard.CONTENT_URI,
null, null);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
#Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
String[] projection = {
LibraryCardContract.LibraryCard._ID,
LibraryCardContract.LibraryCard.COLUMN_BOOK_TITLE,
LibraryCardContract.LibraryCard.COLUMN_BOOK_AUTHOR,
LibraryCardContract.LibraryCard.COLUMN_BOOK_TYPE,
LibraryCardContract.LibraryCard.COLUMN_BOOK_PUBLISH_YEAR};
return new CursorLoader(this, LibraryCardContract.LibraryCard.CONTENT_URI,
projection,
null,
null,
null);
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
cursorAdapter.swapCursor(data);
}
#Override
public void onLoaderReset(Loader<Cursor> loader) {
cursorAdapter.swapCursor(null);
}
}
> This is a code of **BookCursorAdapter** class.
package training.android.com.librarycard.Models;
import android.content.Context;
import android.database.Cursor;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CursorAdapter;
import android.widget.TextView;
import training.android.com.librarycard.Database.LibraryCardContract;
import training.android.com.librarycard.R;
/**
* Created by Hassan on 4/9/2018.
*/
public class BookCursorAdapter extends CursorAdapter {
public BookCursorAdapter(Context context, Cursor c) {
super(context, c, 0);
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return LayoutInflater.from(context)
.inflate(R.layout.book_list,parent,false);
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
TextView bookTitle = view.findViewById(R.id.book_name_tv);
TextView bookAuthor = view.findViewById(R.id.author_tv);
TextView bookType = view.findViewById(R.id.book_type_tv);
TextView publishYear = view.findViewById(R.id.publish_year_tv);
String title = cursor.getString(
cursor.getColumnIndexOrThrow(LibraryCardContract.LibraryCard.COLUMN_BOOK_TITLE));
String type = cursor.getString(
cursor.getColumnIndexOrThrow(LibraryCardContract.LibraryCard.COLUMN_BOOK_TYPE));
String year = cursor.getString(
cursor.getColumnIndexOrThrow(LibraryCardContract.LibraryCard.COLUMN_BOOK_PUBLISH_YEAR));
String author = cursor.getString(
cursor.getColumnIndexOrThrow(LibraryCardContract.LibraryCard.COLUMN_BOOK_AUTHOR));
bookAuthor.setText(author);
bookTitle.setText(title);
bookType.setText(type);
publishYear.setText(year);
}
#Override
public int getCount() {
return super.getCount();
}
}
Screenshot of the application
enter image description here

Only 10 Users Show Up In List Of Users

I'm developing a messaging app using quickblox, the activity where all the users in the database show, only 10 users show up when there's more users than just 10. Any help would be much appreciated!! Got to add more details, but this should explain the problem enough
ListUsers Class
import android.app.ProgressDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.util.SparseBooleanArray;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import com.liftersheaven.messaging.Adapter.ListUsersAdapter;
import com.liftersheaven.messaging.Common.Common;
import com.liftersheaven.messaging.Holder.QBUsersHolder;
import com.quickblox.chat.QBChatService;
import com.quickblox.chat.QBRestChatService;
import com.quickblox.chat.QBSystemMessagesManager;
import com.quickblox.chat.model.QBChatDialog;
import com.quickblox.chat.model.QBChatMessage;
import com.quickblox.chat.model.QBDialogType;
import com.quickblox.chat.request.QBDialogRequestBuilder;
import com.quickblox.chat.utils.DialogUtils;
import com.quickblox.core.QBEntityCallback;
import com.quickblox.core.exception.QBResponseException;
import com.quickblox.users.QBUsers;
import com.quickblox.users.model.QBUser;
import org.jivesoftware.smack.SmackException;
import java.util.ArrayList;
import java.util.List;
public class ListUsers extends AppCompatActivity {
ListView lstUsers;
Button btnCreate;
String mode="";
QBChatDialog qbChatDialog;
List<QBUser> userAdd=new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_users);
Toolbar toolbar = (Toolbar)findViewById(R.id.chatusers_toolbar);
toolbar.setTitle("Users");
setSupportActionBar(toolbar);
mode = getIntent().getStringExtra(Common.UPDATE_MODE);
qbChatDialog=(QBChatDialog)getIntent().getSerializableExtra(Common.UPDATE_DIALOG_EXTRA);
lstUsers = (ListView)findViewById(R.id.lstUsers);
lstUsers.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
btnCreate = (Button)findViewById(R.id.btn_create_chat);
btnCreate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mode == null) {
int countChoice = lstUsers.getCount();
if (lstUsers.getCheckedItemPositions().size() == 1)
createPrivateChat(lstUsers.getCheckedItemPositions());
else if (lstUsers.getCheckedItemPositions().size() > 1)
createGroupChat(lstUsers.getCheckedItemPositions());
else
Toast.makeText(ListUsers.this, "Select a friend to chat with", Toast.LENGTH_SHORT).show();
} else if (mode.equals(Common.UPDATE_ADD_MODE) && qbChatDialog != null) {
if (userAdd.size() > 0) {
QBDialogRequestBuilder requestBuilder = new QBDialogRequestBuilder();
int cntChoice = lstUsers.getCount();
SparseBooleanArray checkItemPositions = lstUsers.getCheckedItemPositions();
for (int i = 0; i < cntChoice; i++) {
if (checkItemPositions.get(i)) {
QBUser user = (QBUser) lstUsers.getItemAtPosition(i);
requestBuilder.addUsers(user);
}
}
QBRestChatService.updateGroupChatDialog(qbChatDialog, requestBuilder)
.performAsync(new QBEntityCallback<QBChatDialog>() {
#Override
public void onSuccess(QBChatDialog qbChatDialog, Bundle bundle) {
Toast.makeText(getBaseContext(), "Add user success", Toast.LENGTH_SHORT).show();
finish();
}
#Override
public void onError(QBResponseException e) {
}
});
}
} else if (mode.equals(Common.UPDATE_REMOVE_MODE) && qbChatDialog != null) {
if (userAdd.size() > 0) {
QBDialogRequestBuilder requestBuilder = new QBDialogRequestBuilder();
int cntChoice = lstUsers.getCount();
SparseBooleanArray checkItemPositions = lstUsers.getCheckedItemPositions();
for (int i = 0; i < cntChoice; i++) {
if (checkItemPositions.get(i)) {
QBUser user = (QBUser) lstUsers.getItemAtPosition(i);
requestBuilder.removeUsers(user);
}
}
QBRestChatService.updateGroupChatDialog(qbChatDialog, requestBuilder)
.performAsync(new QBEntityCallback<QBChatDialog>() {
#Override
public void onSuccess(QBChatDialog qbChatDialog, Bundle bundle) {
Toast.makeText(getBaseContext(), "Remove user success", Toast.LENGTH_SHORT).show();
finish();
}
#Override
public void onError(QBResponseException e) {
}
});
}
}
}
});
if (mode == null && qbChatDialog == null)
retrieveAllUser();
else{
if (mode.equals(Common.UPDATE_ADD_MODE))
loadListAvailableUser();
else if (mode.equals(Common.UPDATE_REMOVE_MODE))
loadListUserInGroup();
}
}
private void loadListUserInGroup() {
btnCreate.setText("Remove User");
QBRestChatService.getChatDialogById(qbChatDialog.getDialogId())
.performAsync(new QBEntityCallback<QBChatDialog>() {
#Override
public void onSuccess(QBChatDialog qbChatDialog, Bundle bundle) {
List<Integer> occupantsId = qbChatDialog.getOccupants();
List<QBUser> listUserAlreadyInGroup = QBUsersHolder.getInstance().getUsersByIds(occupantsId);
ArrayList<QBUser> users = new ArrayList<QBUser>();
users.addAll(listUserAlreadyInGroup);
ListUsersAdapter adapter = new ListUsersAdapter(getBaseContext(),users);
lstUsers.setAdapter(adapter);
adapter.notifyDataSetChanged();
userAdd = users;
}
#Override
public void onError(QBResponseException e) {
Toast.makeText(ListUsers.this, ""+e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
private void loadListAvailableUser() {
btnCreate.setText("Add User");
QBRestChatService.getChatDialogById(qbChatDialog.getDialogId())
.performAsync(new QBEntityCallback<QBChatDialog>() {
#Override
public void onSuccess(QBChatDialog qbChatDialog, Bundle bundle) {
ArrayList<QBUser> listUsers = QBUsersHolder.getInstance().getAllUsers();
List<Integer> occupantsId = qbChatDialog.getOccupants();
List<QBUser>listUserAlreadyInChatGroup = QBUsersHolder.getInstance().getUsersByIds(occupantsId);
for (QBUser user:listUserAlreadyInChatGroup)
listUsers.remove(user);
if (listUsers.size() > 0){
ListUsersAdapter adapter = new ListUsersAdapter(getBaseContext(),listUsers);
lstUsers.setAdapter(adapter);
adapter.notifyDataSetChanged();
userAdd = listUsers;
}
}
#Override
public void onError(QBResponseException e) {
Toast.makeText(ListUsers.this, ""+e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
private void createGroupChat(SparseBooleanArray checkedItemPositions) {
final ProgressDialog mDialog = new ProgressDialog(ListUsers.this);
mDialog.setMessage("Waiting...");
mDialog.setCanceledOnTouchOutside(false);
mDialog.show();
int countChoice = lstUsers.getCount();
ArrayList<Integer> occupantIdsList = new ArrayList<>();
for (int i =0;i<countChoice;i++){
if (checkedItemPositions.get(i)){
QBUser user = (QBUser)lstUsers.getItemAtPosition(i);
occupantIdsList.add(user.getId());
}
}
QBChatDialog dialog = new QBChatDialog();
dialog.setName(Common.createChatDialogName(occupantIdsList));
dialog.setType(QBDialogType.GROUP);
dialog.setOccupantsIds(occupantIdsList);
QBRestChatService.createChatDialog(dialog).performAsync(new QBEntityCallback<QBChatDialog>() {
#Override
public void onSuccess(QBChatDialog qbChatDialog, Bundle bundle) {
mDialog.dismiss();
Toast.makeText(getBaseContext(), "Chat dialog successfully created", Toast.LENGTH_SHORT).show();
finish();
QBSystemMessagesManager qbSystemMessagesManager = QBChatService.getInstance().getSystemMessagesManager();
QBChatMessage qbChatMessage = new QBChatMessage();
qbChatMessage.setBody(qbChatDialog.getDialogId());
for (int i=0;i<qbChatDialog.getOccupants().size();i++) {
qbChatMessage.setRecipientId(qbChatDialog.getOccupants().get(i));
try {
qbSystemMessagesManager.sendSystemMessage(qbChatMessage);
} catch (SmackException.NotConnectedException e) {
e.printStackTrace();
}
}
finish();
}
#Override
public void onError(QBResponseException e) {
Log.e("ERROR",e.getMessage());
}
});
}
private void createPrivateChat(SparseBooleanArray checkedItemPositions) {
final ProgressDialog mDialog = new ProgressDialog(ListUsers.this);
mDialog.setMessage("Waiting...");
mDialog.setCanceledOnTouchOutside(false);
mDialog.show();
int countChoice = lstUsers.getCount();
for(int i=0;i<countChoice;i++){
if (checkedItemPositions.get(i)){
final QBUser user = (QBUser)lstUsers.getItemAtPosition(i);
QBChatDialog dialog = DialogUtils.buildPrivateDialog(user.getId());
QBRestChatService.createChatDialog(dialog).performAsync(new QBEntityCallback<QBChatDialog>() {
#Override
public void onSuccess(QBChatDialog qbChatDialog, Bundle bundle) {
mDialog.dismiss();
Toast.makeText(getBaseContext(), "Private chat dialog successfully created", Toast.LENGTH_SHORT).show();
finish();
QBSystemMessagesManager qbSystemMessagesManager = QBChatService.getInstance().getSystemMessagesManager();
QBChatMessage qbChatMessage = new QBChatMessage();
qbChatMessage.setRecipientId(user.getId());
qbChatMessage.setBody(qbChatDialog.getDialogId());
try {
qbSystemMessagesManager.sendSystemMessage(qbChatMessage);
} catch (SmackException.NotConnectedException e) {
e.printStackTrace();
}
finish();
}
#Override
public void onError(QBResponseException e) {
Log.e("ERROR",e.getMessage());
}
});
}
}
}
private void retrieveAllUser() {
QBUsers.getUsers(null).performAsync(new QBEntityCallback<ArrayList<QBUser>>() {
#Override
public void onSuccess(ArrayList<QBUser> qbUsers, Bundle bundle) {
QBUsersHolder.getInstance().putUsers(qbUsers);
ArrayList<QBUser> qbUserWithoutCurrent = new ArrayList<QBUser>();
for (QBUser user : qbUsers){
if (!user.getLogin().equals(QBChatService.getInstance().getUser().getLogin()))
qbUserWithoutCurrent.add(user);
}
ListUsersAdapter adapter = new ListUsersAdapter(getBaseContext(),qbUserWithoutCurrent);
lstUsers.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
#Override
public void onError(QBResponseException e) {
Log.e("ERROR", e.getMessage());
}
});
}
}
ListUsersAdapter Class
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.quickblox.users.model.QBUser;
import java.util.ArrayList;
public class ListUsersAdapter extends BaseAdapter {
private Context context;
private ArrayList<QBUser> qbUserArrayList;
public ListUsersAdapter(Context context, ArrayList<QBUser> qbUserArrayList){
this.context = context;
this.qbUserArrayList = qbUserArrayList;
}
#Override
public int getCount() {
return qbUserArrayList.size();
}
#Override
public Object getItem(int position) {
return qbUserArrayList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if(convertView == null){
LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(android.R.layout.simple_list_item_multiple_choice,null);
TextView textView = (TextView)view.findViewById(android.R.id.text1);
textView.setText(qbUserArrayList.get(position).getLogin());
}
return view;
}
}
QBUserHolder Class
import android.util.SparseArray;
import com.quickblox.users.model.QBUser;
import java.util.ArrayList;
import java.util.List;
public class QBUsersHolder {
private static QBUsersHolder instance;
private SparseArray<QBUser> qbUserSparseArray;
public static synchronized QBUsersHolder getInstance(){
if (instance == null)
instance = new QBUsersHolder();
return instance;
}
private QBUsersHolder(){
qbUserSparseArray = new SparseArray<>();
}
public void putUsers(List<QBUser> users){
for (QBUser user:users)
putUser(user);
}
public void putUser(QBUser user) {
qbUserSparseArray.put(user.getId(),user);
}
public QBUser getUserById(int id){
return qbUserSparseArray.get(id);}
public List<QBUser> getUsersByIds(List<Integer> ids){
List<QBUser> qbUser = new ArrayList<>();
for(Integer id:ids) {
QBUser user = getUserById(id);
if (user != null)
qbUser.add(user);
}
return qbUser;
}
public ArrayList<QBUser> getAllUsers() {
ArrayList<QBUser> result = new ArrayList<>();
for (int i=0;i<qbUserSparseArray.size();i++)
result.add(qbUserSparseArray.valueAt(i));
return result;
}
}
By default you could retrieve only 10 users per page. You should change JSON request which retrieve users

My listview is not showing any chats from parse database

I have three classes one user list holds the list of user when each user is clicked it directs you to chat class which holds the chats activity. I also have the conversation list which holds a single conversation. The problem is the list view does not show previous chats stored in parse data base how can I load the previous chats to my list view.
package com.example.user.mycareerchat;
import java.util.ArrayList;
import java.util.List;
import android.app.ActionBar;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.TextView;
import android.widget.Toast;
import com.example.user.mycareerchat.custom.CustomActivity;
import com.parse.FindCallback;
import com.parse.Parse;
import com.parse.ParseClassName;
import com.parse.ParseException;
import com.parse.ParseObject;
import com.parse.ParseQuery;
import com.parse.ParseUser;
public class UserList extends CustomActivity {
private static final String EXTRADATA = null;
// Declare Variables
// the chat list
private ArrayList<ParseUser> uList =new ArrayList<ParseUser>();
// the parseruser
public static ParseUser user=new ParseUser();
/////////////
public static ArrayList names = new ArrayList<String>();
private String currentUserId;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.user_list);
updateUserStatus(true);
}
#Override
protected void onDestroy() {
super.onDestroy();
updateUserStatus(false);
}
#Override
protected void onResume() {
super.onResume();
loadUserList();
}
private void loadUserList() {
currentUserId = ParseUser.getCurrentUser().getObjectId();
names = new ArrayList<String>();
ParseQuery<ParseUser> query = ParseUser.getQuery();
//don't include yourself
query.whereNotEqualTo("objectId", currentUserId);
query.findInBackground(new FindCallback<ParseUser>() {
public void done(List<ParseUser> userList, com.parse.ParseException e) {
if (e == null) {
for (int i=0; i<userList.size(); i++) {
names.add(userList.get(i).getUsername().toString());
uList = new ArrayList<ParseUser>(userList);
}
final ListView list = (ListView)findViewById(R.id.list);
ArrayAdapter namesArrayAdapter = new ArrayAdapter<String>(getApplicationContext(),
R.layout.chat_item, names);
list.setAdapter(namesArrayAdapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> a, View v, int i, long l) {
// openConversation(names, i);
String name= names.get(i).toString();
startActivity(new Intent(UserList.this, Chat.class).putExtra(EXTRADATA, name));
}
});
} else {
Toast.makeText(getApplicationContext(),
"Error loading user list",
Toast.LENGTH_LONG).show();
}
}
});
}
private void updateUserStatus(boolean online) {
user.put("online", online);
user.saveEventually();
}
private class UserAdapter extends BaseAdapter {
#Override
public int getCount() {
return uList.size();
}
#Override
public ParseUser getItem(int arg0) {
return uList.get(arg0);
}
#Override
public long getItemId(int arg0) {
return arg0;
}
#Override
public View getView(int pos, View v, ViewGroup arg2) {
if(v!=null)
v=getLayoutInflater().inflate(R.layout.chat_item,null);
ParseUser c= getItem(pos);
TextView lbl = (TextView) v;
lbl.setText(c.getUsername());
lbl.setCompoundDrawablesWithIntrinsicBounds(c.getBoolean("online")? R.drawable.ic_online:
R.drawable.ic_offline,0,
R.drawable.arrow,0);
return v;
}
}
}
//Conversation Class
package com.example.user.mycareerchat.model;
import com.example.user.mycareerchat.UserList;
import java.util.Date;
/**
* Created by user on 26/Aug/2015.
*/
public class Conversation {
public static final int STATUS_SENDING =0;
public static final int STATUS_SENT =1;
public static final int STATUS_FAILED =2;
private int status = STATUS_SENT;
private Date date;
private String sender;
private String msg;
//instatiates new conversation
public Conversation(String msg,Date date,String sender) {
this.msg =msg;
this.date = date;
this.sender = sender;
}
//instatiates new conversation
// public Conversation() {
//
// }
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public boolean isSent(){
return UserList.user.getUsername().equals(sender);
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public String getSender() {
return sender;
}
public void setSender(String sender) {
this.sender = sender;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
}
//Chat class
package com.example.user.mycareerchat;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Telephony;
import android.text.InputType;
import android.text.format.DateUtils;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AbsListView;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import com.example.user.mycareerchat.custom.CustomActivity;
import com.example.user.mycareerchat.model.Conversation;
import com.parse.FindCallback;
import com.parse.ParseException;
import com.parse.ParseObject;
import com.parse.ParseQuery;
import com.parse.ParseUser;
import com.parse.SaveCallback;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
* This class represents single chat class message
*/
public class Chat extends CustomActivity {
private ArrayList<Conversation> convList;
private ChatAdapter adp;
private EditText txt;
private String buddy;
private Date lastMsgDate;
private boolean isRunning;
private static Handler handler;
private static final String EXTRA_DATA = null ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.chat);
convList = new ArrayList<Conversation>();
ListView list = (ListView) findViewById(R.id.listchat);
adp = new ChatAdapter();
list.setAdapter(adp);
list.setTranscriptMode(AbsListView.TRANSCRIPT_MODE_ALWAYS_SCROLL);
list.setStackFromBottom(true);
txt = (EditText) findViewById(R.id.txt);
txt.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_MULTI_LINE);
setTouchNClick(R.id.btnSend);
buddy = getIntent().getStringExtra(EXTRA_DATA);
// getActionBar().setTitle(buddy);
loadConversationList();
handler = new Handler();
}
#Override
protected void onResume() {
super.onResume();
isRunning =true;
loadConversationList();
}
#Override
protected void onPause() {
super.onPause();
isRunning = false;
}
#Override
public void onClick(View v) {
super.onClick(v);
if(v.getId()== R.id.btnSend){
sendMessage();
}
}
private void sendMessage() {
if(txt.length()==0)
return;
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(txt.getWindowToken(),0);
String s =txt.getText().toString();
final Conversation c = new Conversation(s, new Date(),UserList.user.getUsername());
c.setStatus(Conversation.STATUS_SENDING);
convList.add(c);
adp.notifyDataSetChanged();
txt.setText(null);
ParseObject po = new ParseObject("Chat");
po.put("sender",UserList.user.getUsername());
po.put("receiver",buddy);
po.put("message",s);
po.saveEventually(new SaveCallback() {
#Override
public void done(ParseException e) {
if(e==null)
c.setStatus(Conversation.STATUS_SENT);
else
c.setStatus(Conversation.STATUS_FAILED);
adp.notifyDataSetChanged();
}
});
}
/*load the conversation list from parse server and save the data of the last message that will
* be used to load only new received messages*/
private void loadConversationList() {
//load all messsages
ParseQuery<ParseObject> q =ParseQuery.getQuery("Chat");
if(convList.size()==0){
ArrayList<String> al = new ArrayList<String>();
al.add(buddy);
al.add(ParseUser.getCurrentUser().getUsername());
q.whereContainedIn("sender", al);
q.whereContainedIn("receiver",al);
}
else{
//load only new received messages....
if(lastMsgDate!=null){
q.whereLessThan("createdAt",lastMsgDate);
q.whereEqualTo("sender", ParseUser.getCurrentUser().getUsername());
q.whereEqualTo("receiver",buddy);
adp.notifyDataSetChanged();
}
//load messages in the most recent order
q.orderByDescending("createdAt");
q.setLimit(30);
q.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> li, ParseException e) {
if(li != null && li.size() >0){
for (int i =li.size()-1;i>=0;i--){
ParseObject po = li.get(i);
Conversation c =new Conversation(po.getString("message"),po.getCreatedAt(),po.getString("sender"));
convList.add(c);
if(lastMsgDate == null || lastMsgDate.before(c.getDate()))
lastMsgDate = c.getDate();
adp.notifyDataSetChanged();
}
}
handler.postDelayed(new Runnable() {
#Override
public void run() {
if(isRunning)
loadConversationList();
}
},1000);
//
}
});
}
}
/*this class is the adapter class for chat listview. this adapter shows the sent and received messages
*in the list item*/
private class ChatAdapter extends BaseAdapter{
#Override
public int getCount() {
return convList.size();
}
#Override
public Conversation getItem(int arg0) {
return convList.get(arg0);
}
#Override
public long getItemId(int arg0) {
return arg0;
}
#Override
public View getView(int pos, View v, ViewGroup arg2) {
Conversation c = getItem(pos);
if(c.isSent())
v=getLayoutInflater().inflate(R.layout.chat_item_sent,null);
else
v=getLayoutInflater().inflate(R.layout.chat_item_rcv,null);
TextView lbl =(TextView) v.findViewById(R.id.lbl1);
lbl.setText(DateUtils.getRelativeDateTimeString(Chat.this,c.getDate().getTime (),DateUtils.SECOND_IN_MILLIS,DateUtils.DAY_IN_MILLIS,0));
lbl =(TextView) v.findViewById(R.id.lbl2);
lbl.setText(c.getMsg());
lbl =(TextView) v.findViewById(R.id.lbl3);
if (c.isSent()){
if (c.getStatus()==Conversation.STATUS_SENT)
lbl.setText("Delivered");
else if (c.getStatus()==Conversation.STATUS_SENDING)
lbl.setText("Sending...");
else
lbl.setText("Failed");
}
else
lbl.setText("");
return v;
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getItemId()==android.R.id.home){
finish();
}
return super.onOptionsItemSelected(item);
}
}

Loading data from sqlite and displaying on ViewPager

Been trying to load data from sqlite and display it on viewpager without much success.
I have a viewpager with two tabs which should hold data based on the tag_id passed as a parameter of newInstance. There is also an action bar navigation spinner with a list of counties that is used for filter data displayed based on the county_id.
Am able to fetch data from server and save it in the sqlite db but displaying it is the problem. Data is not dispalyed on the first page of the viewpager but it exists in the sqlite. Data for the second is the only one laoded.
Below is my implementation;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.app.ListFragment;
import android.support.v4.app.LoaderManager.LoaderCallbacks;
import android.support.v4.content.Loader;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBar.OnNavigationListener;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.ContextThemeWrapper;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.NetworkError;
import com.android.volley.NoConnectionError;
import com.android.volley.ParseError;
import com.android.volley.Response;
import com.android.volley.ServerError;
import com.android.volley.TimeoutError;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.app.adapter.CustomCountySpinnerAdapter;
import com.app.adapter.TendersAdapter;
import com.app.database.DBFunctions;
import com.app.externallib.AppController;
import com.app.model.CountyModel;
import com.app.model.PostsModel;
import com.app.utils.AppConstants;
import com.app.utils.PostsListLoader;
import com.nhaarman.listviewanimations.appearance.simple.SwingBottomInAnimationAdapter;
import com.viewpagerindicator.TabPageIndicator;
public class PublicTendersFragment extends Fragment{
private static List<PubliTenders> public_tenders;
public PublicTendersFragment newInstance(String text) {
PublicTendersFragment mFragment = new PublicTendersFragment();
Bundle mBundle = new Bundle();
mBundle.putString(AppConstants.TEXT_FRAGMENT, text);
mFragment.setArguments(mBundle);
return mFragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
public_tenders = new ArrayList<PubliTenders>();
public_tenders.add(new PubliTenders(14, "County"));
public_tenders.add(new PubliTenders(15, "National"));
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final Context contextThemeWrapper = new ContextThemeWrapper(
getActivity(), R.style.StyledIndicators);
LayoutInflater localInflater = inflater
.cloneInContext(contextThemeWrapper);
View v = localInflater.inflate(R.layout.fragment_tenders, container,
false);
FragmentPagerAdapter adapter = new TendersVPAdapter(
getFragmentManager());
ViewPager pager = (ViewPager) v.findViewById(R.id.pager);
pager.setAdapter(adapter);
TabPageIndicator indicator = (TabPageIndicator) v
.findViewById(R.id.indicator);
indicator.setViewPager(pager);
return v;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setHasOptionsMenu(true);
}
class TendersVPAdapter extends FragmentPagerAdapter{
public TendersVPAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Parcelable saveState() {
return null;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return Tenders.newInstance(public_tenders.get(position).tag_id);
case 1:
return Tenders.newInstance(public_tenders.get(position).tag_id);
default:
return null;
}
}
#Override
public CharSequence getPageTitle(int position) {
return public_tenders.get(position).tender_type.toUpperCase(Locale
.getDefault());
}
#Override
public int getCount() {
return public_tenders.size();
}
}
public class PubliTenders {
public int tag_id;
public String tender_type;
public PubliTenders(int tag_id, String tender_type) {
this.tag_id = tag_id;
this.tender_type = tender_type;
}
}
public static class Tenders extends ListFragment implements
OnNavigationListener, LoaderCallbacks<ArrayList<PostsModel>> {
boolean mDualPane;
int mCurCheckPosition = 0;
// private static View rootView;
private SwipeRefreshLayout swipeContainer;
private ListView lv;
private View rootView;
private DBFunctions mapper;
private CustomCountySpinnerAdapter spinadapter;
private TendersAdapter mTendersAdapter;
private static final String ARG_TAG_ID = "tag_id";
private int tag_id;
private int mycounty;
private static final int INITIAL_DELAY_MILLIS = 500;
private static final String DEBUG_TAG = "BlogsFragment";
private final String TAG_REQUEST = "BLOG_TAG";
private JsonArrayRequest jsonArrTendersRequest;
// private OnItemSelectedListener listener;
public static Tenders newInstance(int tag_id) {
Tenders fragment = new Tenders();
Bundle b = new Bundle();
b.putInt(ARG_TAG_ID, tag_id);
fragment.setArguments(b);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
tag_id = getArguments().getInt(ARG_TAG_ID);
}
#Override
public void onStart() {
super.onStart();
getLoaderManager().initLoader(0, null, this);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_headlines_blog,
container, false);
swipeContainer = (SwipeRefreshLayout) rootView
.findViewById(R.id.swipeProjectsContainer);
lv = (ListView) rootView.findViewById(android.R.id.list);
lv.setOnScrollListener(new AbsListView.OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView view,
int scrollState) {
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
int topRowVerticalPosition = (lv == null || lv
.getChildCount() == 0) ? 0 : lv.getChildAt(0)
.getTop();
swipeContainer.setEnabled(topRowVerticalPosition >= 0);
}
});
swipeContainer.setOnRefreshListener(new OnRefreshListener() {
#Override
public void onRefresh() {
fetchPublicTenders(mycounty);
}
});
swipeContainer.setColorSchemeResources(R.color.blue_dark,
R.color.irdac_green, R.color.red_light,
R.color.holo_red_light);
return rootView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setHasOptionsMenu(true);
mapper = new DBFunctions(getActivity());
mapper.open();
// initialize AB Spinner
populateSpinner();
fetchPublicTenders(mycounty);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("curChoice", mCurCheckPosition);
}
private void populateSpinner() {
try {
List<CountyModel> counties = new ArrayList<CountyModel>();
counties = mapper.getAllCounties();
ActionBar actBar = ((ActionBarActivity) getActivity())
.getSupportActionBar();
actBar.setDisplayShowTitleEnabled(true);
actBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
spinadapter = new CustomCountySpinnerAdapter(getActivity(),
android.R.layout.simple_spinner_dropdown_item, counties);
actBar.setListNavigationCallbacks(spinadapter, this);
} catch (NullPointerException exp) {
}
}
#Override
public Loader<ArrayList<PostsModel>> onCreateLoader(int arg0,
Bundle arg1) {
Log.v(DEBUG_TAG, "On Create Loader");
return new PostsListLoader(getActivity(), mycounty, tag_id);
}
#Override
public void onLoadFinished(Loader<ArrayList<PostsModel>> arg0,
ArrayList<PostsModel> data) {
// System.out.println("results " + data.size());
addToAdapter(data);
}
#Override
public void onLoaderReset(Loader<ArrayList<PostsModel>> arg0) {
lv.setAdapter(null);
}
#Override
public boolean onNavigationItemSelected(int pos, long arg1) {
CountyModel mo = spinadapter.getItem(pos);
this.mycounty = mo.getId();
refresh(mo.getId());
return false;
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
TextView txtTitle = (TextView) v.findViewById(R.id.tender_title);
TextView txtRefNo = (TextView) v.findViewById(R.id.ref_no);
TextView txtExpiryDate = (TextView) v
.findViewById(R.id.expiry_date);
TextView txtOrg = (TextView) v.findViewById(R.id.dept_or_org);
Intent intTenderFullDetails = new Intent(getActivity(),
TenderDetailsActivity.class);
intTenderFullDetails.putExtra(TenderDetailsActivity.TENDER_TITLE,
txtTitle.getText().toString().trim());
intTenderFullDetails.putExtra(TenderDetailsActivity.TENDER_REF_NO,
txtRefNo.getText().toString().trim());
intTenderFullDetails.putExtra(
TenderDetailsActivity.TENDER_EXPIRY_DATE, txtExpiryDate
.getText().toString().trim());
intTenderFullDetails.putExtra(TenderDetailsActivity.TENDER_ORG,
txtOrg.getText().toString().trim());
// intTenderFullDetails.putExtra(TenderDetailsActivity.TENDER_DESC,
// Lorem);
startActivity(intTenderFullDetails);
}
private void fetchPublicTenders(final int county_id) {
swipeContainer.setRefreshing(true);
Uri.Builder builder = Uri.parse(AppConstants.postsUrl).buildUpon();
builder.appendQueryParameter("tag_id", Integer.toString(tag_id));
System.out.println("fetchPublicTenders with tag_id " + tag_id
+ " and county_id " + county_id);
jsonArrTendersRequest = new JsonArrayRequest(builder.toString(),
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
if (response.length() > 0) {
for (int i = 0; i < response.length(); i++) {
try {
JSONObject tender_item = response
.getJSONObject(i);
mapper.createPost(
tender_item.getInt("id"),
tender_item.getInt("tag_id"),
tender_item.getInt("county_id"),
tender_item.getInt("sector_id"),
tender_item.getString("title"),
tender_item.getString("slug"),
tender_item.getString("content"),
tender_item
.getString("reference_no"),
tender_item
.getString("expiry_date"),
tender_item
.getString("organization"),
tender_item
.getString("image_url"),
tender_item
.getString("created_at"));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
swipeContainer.setRefreshing(false);
refresh(county_id);
}
} else {
if (swipeContainer.isShown()) {
swipeContainer.setRefreshing(false);
}
try {
Toast.makeText(getActivity(),
"Sorry! No results found",
Toast.LENGTH_LONG).show();
} catch (NullPointerException npe) {
System.out.println(npe);
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
if (error instanceof NetworkError) {
try {
Toast.makeText(
getActivity(),
"Network Error. Cannot refresh list",
Toast.LENGTH_SHORT).show();
} catch (NullPointerException npe) {
System.err.println(npe);
}
if (swipeContainer.isShown()) {
swipeContainer.setRefreshing(false);
}
refresh(county_id);
} else if (error instanceof ServerError) {
try {
Toast.makeText(
getActivity(),
"Problem Connecting to Server. Try Again Later",
Toast.LENGTH_SHORT).show();
} catch (NullPointerException npe) {
System.err.println(npe);
}
if (swipeContainer.isShown()) {
swipeContainer.setRefreshing(false);
}
} else if (error instanceof AuthFailureError) {
} else if (error instanceof ParseError) {
} else if (error instanceof NoConnectionError) {
try {
Toast.makeText(getActivity(),
"No Connection", Toast.LENGTH_SHORT)
.show();
} catch (NullPointerException npe) {
System.err.println(npe);
}
} else if (error instanceof TimeoutError) {
try {
Toast.makeText(
getActivity()
.getApplicationContext(),
"Timeout Error. Try Again Later",
Toast.LENGTH_SHORT).show();
} catch (NullPointerException npe) {
System.err.println(npe);
}
}
if (swipeContainer.isShown()) {
swipeContainer.setRefreshing(false);
}
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Accept", "application/json");
return headers;
}
};
// Set a retry policy in case of SocketTimeout & ConnectionTimeout
// Exceptions. Volley does retry for you if you have specified the
// policy.
jsonArrTendersRequest.setRetryPolicy(new DefaultRetryPolicy(
(int) TimeUnit.SECONDS.toMillis(20),
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
jsonArrTendersRequest.setTag(TAG_REQUEST);
AppController.getInstance().addToRequestQueue(jsonArrTendersRequest);
}
public void refresh(int county_id) {
Bundle b = new Bundle();
b.putInt("myconty", county_id);
if (isAdded()) {
getLoaderManager().restartLoader(0, b, this);
}
}
private void addToAdapter(ArrayList<PostsModel> plist) {
mTendersAdapter = new TendersAdapter(rootView.getContext(), plist);
SwingBottomInAnimationAdapter swingBottomInAnimationAdapter = new SwingBottomInAnimationAdapter(
mTendersAdapter);
swingBottomInAnimationAdapter.setAbsListView(lv);
assert swingBottomInAnimationAdapter.getViewAnimator() != null;
swingBottomInAnimationAdapter.getViewAnimator()
.setInitialDelayMillis(INITIAL_DELAY_MILLIS);
setListAdapter(swingBottomInAnimationAdapter);
mTendersAdapter.notifyDataSetChanged();
}
}
}
And this is the PostsListLoader class
import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import android.support.v4.content.AsyncTaskLoader;
import com.app.database.DBFunctions;
import com.app.model.PostsModel;
public class PostsListLoader extends AsyncTaskLoader<ArrayList<PostsModel>> {
private DBFunctions mapper;
private ArrayList<PostsModel> myPostsModel;
private int county_id;
private int tag_id;
public PostsListLoader(Context context, int county_id, int tag_id) {
super(context);
mapper = new DBFunctions(getContext());
mapper.open();
this.county_id = county_id;
this.tag_id = tag_id;
}
#Override
public ArrayList<PostsModel> loadInBackground() {
String query_string = AppConstants.KEY_COUNTY_ID + " = " + county_id
+ " AND " + AppConstants.KEY_TAG_ID + " = " + tag_id;
myPostsModel = mapper.getPosts(query_string);
return myPostsModel;
}
#Override
public void deliverResult(ArrayList<PostsModel> data) {
if (isReset()) {
// An async query came in while the loader is stopped. We
// don't need the result.
if (data != null) {
onReleaseResources(data);
}
}
List<PostsModel> oldNews = data;
myPostsModel = data;
if (isStarted()) {
// If the Loader is currently started, we can immediately
// deliver its results.
super.deliverResult(data);
}
// At this point we can release the resources associated with
// 'oldNews' if needed; now that the new result is delivered we
// know that it is no longer in use.
if (oldNews != null) {
onReleaseResources(oldNews);
}
}
/**
* Handles a request to start the Loader.
*/
#Override
protected void onStartLoading() {
if (myPostsModel != null) {
// If we currently have a result available, deliver it
// immediately.
deliverResult(myPostsModel);
}
if (takeContentChanged() || myPostsModel == null) {
// If the data has changed since the last time it was loaded
// or is not currently available, start a load.
forceLoad();
}
}
/**
* Handles a request to stop the Loader.
*/
#Override
protected void onStopLoading() {
// Attempt to cancel the current load task if possible.
cancelLoad();
}
/**
* Handles a request to cancel a load.
*/
#Override
public void onCanceled(ArrayList<PostsModel> news) {
super.onCanceled(news);
// At this point we can release the resources associated with 'news'
// if needed.
onReleaseResources(news);
}
/**
* Handles a request to completely reset the Loader.
*/
#Override
protected void onReset() {
super.onReset();
// Ensure the loader is stopped
onStopLoading();
// At this point we can release the resources associated with 'apps'
// if needed.
if (myPostsModel != null) {
onReleaseResources(myPostsModel);
myPostsModel = null;
}
}
/**
* Helper function to take care of releasing resources associated with an
* actively loaded data set.
*/
protected void onReleaseResources(List<PostsModel> news) {
}
}
What could I be doing wrong?
Any help will be appreciated.
Thanks

ListActivity onScroll never fired

I have a ListActivity that implements OnScrollListener. Unfortunality the methods onScroll and onScrollStateChanged are never fired.
I have absolutly no idear why. The data is shown correctly. I am able to scroll inside my view... Do you see the problem?
package bc.qz.client.android.activity;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import bc.qz.client.android.R;
import bc.qz.client.android.adapter.ScoreListAdapter;
import bc.qz.client.android.proxy.RemoteServletCaller;
import de.bc.qz.business.Score;
public class ScoreActivity extends ListActivity implements OnScrollListener{
private SharedPreferences mSharedPreferences;
private RemoteServletCaller mRemoteServletCaller;
private Runnable lViewScoreRunnable;
private String mUuid;
private String mUsername;
private ProgressDialog mProgressDialog = null;
private ScoreListAdapter mScoreListAdapter;
List<Score> mAllScore = new ArrayList<Score>();
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
mRemoteServletCaller = new RemoteServletCaller();
mSharedPreferences = this.getSharedPreferences(
"de.bc.qz.client.sharedpreferences", Context.MODE_PRIVATE);
mUuid = mSharedPreferences.getString("uuid", null);
mUsername = mSharedPreferences.getString("user", null);
mScoreListAdapter = new ScoreListAdapter(this, mAllScore);
setListAdapter(mScoreListAdapter);
lViewScoreRunnable = new Runnable() {
#Override
public void run() {
loadAllScore(mUsername, mUuid);
}
};
Thread thread = new Thread(null, lViewScoreRunnable,
"MagentoBackground");
thread.start();
mProgressDialog = ProgressDialog.show(ScoreActivity.this,
"Bitte warten...", "Lade Highscore...", true);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.activity_score_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.goToTop:
return true;
case R.id.goToBottom:
return true;
case R.id.goToMine:
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
System.out.println("onScroll");
}
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
System.out.println("onScrollStateChanged");
}
private void loadAllScore(String pUsername, String pUuid) {
try {
if (null == mUuid || mUsername == null) {
mUuid = UUID.randomUUID().toString();
mSharedPreferences.edit().putString("uuid", mUuid).commit();
mAllScore.addAll(mRemoteServletCaller.getAllScore(1, 50));
} else {
mAllScore.addAll(mRemoteServletCaller.getAllScore(mUsername,
mUuid));
}
} catch (Exception e) {
return;
}
runOnUiThread(returnRes);
}
private Runnable returnRes = new Runnable() {
#Override
public void run() {
if (mAllScore != null && mAllScore.size() > 0) {
mScoreListAdapter.notifyDataSetChanged();
for (int i = 0, N = mAllScore.size(); i < N; i++)
mScoreListAdapter.add(mAllScore.get(i));
}
mProgressDialog.dismiss();
}
};
}
getListView().setOnScrollListener(this);

Categories

Resources