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
Related
public class Constant {
public static final String FIREBASE_CHAT_URL="https://roadcaremap.firebaseio.com/";
public static final String CHILD_USERS="users";
public static final String CHILD_CHAT="chat";
public static final String KEY_SEND_USER="key_send_user";
public static final String CHILD_CONNECTION="connecttion";
public static final String CHILD_LATITUDE="latitude";
public static final String CHILD_LONGITUDE="longitude";
public static final String KEY_EMAIL="email";
public static final String KEY_ONLINE="online";
public static final String KEY_OFFLINE="offline";
public static final String KEY_CLOSE="key_close";
}
I'm new to android. Recently, I encountered a problem when running the application on my device. The app crashes and shows me an error on this line which I do not know how to solve. I've added the code and picture of the logcat. Any help would be much appreciated. The error is shown in this line.
rootUrl = new Firebase(Constant.FIREBASE_CHAT_URL);
package com.snapsofts.demogmap.activity;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import com.firebase.client.AuthData;
import com.firebase.client.ChildEventListener;
import com.firebase.client.DataSnapshot;
import com.firebase.client.Firebase;
import com.firebase.client.FirebaseError;
import com.firebase.client.ValueEventListener;
import com.firebase.ui.auth.AuthUI;
import com.google.firebase.auth.FirebaseAuth;
import com.google.gson.Gson;
import com.snapsofts.demogmap.R;
import com.snapsofts.demogmap.Services.LocationService;
import com.snapsofts.demogmap.common.Constant;
import com.snapsofts.demogmap.object.User;
import java.util.ArrayList;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
public class MainActivity extends AppCompatActivity {
private Firebase rootUrl;
private Firebase urlCurrenUser;
private Firebase urlAllUser;
private FirebaseAuth mAuth;
private Firebase.AuthStateListener mAuthStateListener;
private String currenUserId;
private String currenUserEmail;
private ArrayList<User> arrUser;
private AllUserAdapter allUserAdapter;
private ArrayList<String> arrStringEmail;
private ValueEventListener valueEventListenerUserConnected;
private User currenUser;
#BindView(R.id.btnLogout)
Button btnLogout;
#BindView(R.id.lvUser)
ListView lvUser;
#BindView(R.id.tvUsserName)
TextView tvUsserName;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
MainActivity.this.startService(new Intent(MainActivity.this, LocationService.class));
arrStringEmail = new ArrayList<>();
arrUser = new ArrayList<User>();
allUserAdapter = new AllUserAdapter(MainActivity.this, 0, arrUser);
lvUser.setAdapter(allUserAdapter);
lvUser.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent=new Intent(MainActivity.this,MapsActivity.class);
User user=arrUser.get(position);
Gson gson=new Gson();
intent.putExtra(Constant.KEY_SEND_USER,gson.toJson(user).toString()+"---"+gson.toJson(currenUser).toString());
startActivity(intent);
mAuth = FirebaseAuth.getInstance();
}
});
rootUrl = new Firebase(Constant.FIREBASE_CHAT_URL);
mAuthStateListener = new Firebase.AuthStateListener() {
#Override
public void onAuthStateChanged(AuthData authData) {
setAuthenticatedUser();
}
};
rootUrl.addAuthStateListener(mAuthStateListener);
}
private void setAuthenticatedUser () {
if (FirebaseAuth.getInstance().getCurrentUser() != null) {
currenUserId = FirebaseAuth.getInstance().getCurrentUser().getUid();
currenUserEmail = FirebaseAuth.getInstance().getCurrentUser().getEmail();
getCurrenUser();
getAllUser();
} else {
startActivity(new Intent(MainActivity.this, LoginActivity.class));
finish();
}
}
public void getCurrenUser() {
urlCurrenUser = new Firebase(Constant.FIREBASE_CHAT_URL).child(Constant.CHILD_USERS).child(FirebaseAuth.getInstance().getCurrentUser().getUid());
urlCurrenUser.addValueEventListener(valueEventListenerCurrenUser);
valueEventListenerUserConnected=rootUrl.getRoot().child(".info/connected").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
boolean connected = (Boolean) dataSnapshot.getValue();
if (connected) {
urlCurrenUser.child(Constant.CHILD_CONNECTION).setValue(Constant.KEY_ONLINE);
urlCurrenUser.child(Constant.CHILD_CONNECTION).onDisconnect().setValue(Constant.KEY_OFFLINE);
}
}
#Override
public void onCancelled(FirebaseError firebaseError) {
}
});
}
private ValueEventListener valueEventListenerCurrenUser = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
User user = dataSnapshot.getValue(User.class);
tvUsserName.setText("Hello "+user.name);
}
#Override
public void onCancelled(FirebaseError firebaseError) {
}
};
public void getAllUser() {
urlAllUser = new Firebase(Constant.FIREBASE_CHAT_URL).child(Constant.CHILD_USERS);
urlAllUser.addChildEventListener(childEventListenerAllUser);
}
private ChildEventListener childEventListenerAllUser = new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
User user = dataSnapshot.getValue(User.class);
if (!dataSnapshot.getKey().equals(currenUserId)){
arrStringEmail.add(user.email);
arrUser.add(user);
allUserAdapter.notifyDataSetChanged();
}else {
currenUser=user;
}
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
if (!dataSnapshot.getKey().equals(currenUserId)){
User user = dataSnapshot.getValue(User.class);
int index = arrStringEmail.indexOf(user.email);
arrUser.set(index, user);
allUserAdapter.notifyDataSetChanged();
}
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(FirebaseError firebaseError) {
}
};
#Override
protected void onDestroy() {
super.onDestroy();
try {
rootUrl.removeAuthStateListener(mAuthStateListener);
} catch (Exception e) {
}
try {
urlCurrenUser.removeEventListener(valueEventListenerCurrenUser);
} catch (Exception e) {
}
try {
urlAllUser.removeEventListener(childEventListenerAllUser);
} catch (Exception e) {
}
try {
rootUrl.getRoot().child(".info/connected").removeEventListener(valueEventListenerUserConnected);
}catch (Exception e){}
}
#OnClick(R.id.btnLogout)
public void btnLogout() {
if (FirebaseAuth.getInstance().getCurrentUser() != null) {
stopService(new Intent(this, LocationService.class));
AuthUI.getInstance().signOut(this);
Intent intent = new Intent(getApplicationContext(), LoginActivity.class);
startActivity(intent);
finish();
}
}
public class AllUserAdapter extends ArrayAdapter<User> {
private Activity mActivity;
private ArrayList<User> mArrUser;
#BindView(R.id.tvNameUser)
TextView tvNameUser;
#BindView(R.id.tvStatus)
TextView tvStatus;
public AllUserAdapter(Activity mActivity, int resource, ArrayList<User> mArrUser) {
super(mActivity, resource, mArrUser);
this.mActivity = mActivity;
this.mArrUser = mArrUser;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater layoutInflater = mActivity.getLayoutInflater();
convertView = layoutInflater.inflate(R.layout.item_list_user, null);
}
ButterKnife.bind(this, convertView);
tvNameUser.setText(mArrUser.get(position).name);
tvStatus.setText(mArrUser.get(position).connecttion);
if (mArrUser.get(position).connecttion.equals(Constant.KEY_ONLINE)){
tvStatus.setTextColor(Color.parseColor("#00FF00"));
}else {
tvStatus.setTextColor(Color.parseColor("#FF0000"));
}
return convertView;
}
}
}
logcat
I run my App on my phone. Everything works perfectly.. But after i check in my logcat for the debug.
It's show me this error.
E/HAL: hw_get_module_by_class: module name gralloc
E/HAL: hw_get_module_by_class: module name gralloc
It's show when user run the app for the first time. It's show just in time the app show splash screen. I'm not sure which code that make this thing happen.
So i'll show you my splash code and my fragment home code.
so this is my splasactivity code :
package com.apps.mathar;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Build;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.TypedValue;
import android.view.Window;
import android.view.WindowManager;
import com.apps.utils.Constant;
import com.apps.utils.JsonUtils;
public class SplashActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
// hideStatusBar();
setStatusColor();
try {
Constant.isFromPush = getIntent().getExtras().getBoolean("ispushnoti", false);
Constant.pushID = getIntent().getExtras().getString("noti_nid");
} catch (Exception e) {
Constant.isFromPush = false;
}
try {
Constant.isFromNoti = getIntent().getExtras().getBoolean("isnoti", false);
} catch (Exception e) {
Constant.isFromNoti = false;
}
JsonUtils jsonUtils = new JsonUtils(SplashActivity.this);
Resources r = getResources();
float padding = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, Constant.GRID_PADDING, r.getDisplayMetrics());
Constant.columnWidth = (int) ((jsonUtils.getScreenWidth() - ((Constant.NUM_OF_COLUMNS + 1) * padding)) / Constant.NUM_OF_COLUMNS);
if(!Constant.isFromNoti) {
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
openMainActivity();
}
}, 2000);
} else {
openMainActivity();
}
}
private void openMainActivity() {
Intent intent = new Intent(SplashActivity.this,MainActivity.class);
startActivity(intent);
finish();
}
public void setStatusColor()
{
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
{
Window window = getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.setStatusBarColor(getResources().getColor(R.color.statusBar));
}
}
}
And this is my fragmenthome code
package com.apps.mathar;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.apps.adapter.AdapterRecent;
import com.apps.item.ItemSong;
import com.apps.utils.Constant;
import com.apps.utils.DBHelper;
import com.apps.utils.JsonUtils;
import com.apps.utils.RecyclerItemClickListener;
import com.apps.utils.ZProgressHUD;
import com.google.android.gms.ads.AdListener;
import com.squareup.picasso.Callback;
import com.squareup.picasso.Picasso;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
public class FragmentHome extends Fragment {
DBHelper dbHelper;
RecyclerView recyclerView;
ArrayList<ItemSong> arrayList;
ArrayList<ItemSong> arrayList_recent;
AdapterRecent adapterRecent;
ZProgressHUD progressHUD;
LinearLayoutManager linearLayoutManager;
public ViewPager viewpager;
ImagePagerAdapter adapter;
TextView textView_empty;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
View rootView = inflater.inflate(R.layout.fragment_home, container, false);
setHasOptionsMenu(true);
dbHelper = new DBHelper(getActivity());
progressHUD = ZProgressHUD.getInstance(getActivity());
progressHUD.setMessage(getActivity().getResources().getString(R.string.loading));
progressHUD.setSpinnerType(ZProgressHUD.FADED_ROUND_SPINNER);
textView_empty = (TextView)rootView.findViewById(R.id.textView_recent_empty);
adapter = new ImagePagerAdapter();
viewpager = (ViewPager)rootView.findViewById(R.id.viewPager_home);
viewpager.setPadding(80,20,80,20);
viewpager.setClipToPadding(false);
viewpager.setPageMargin(40);
viewpager.setClipChildren(false);
// viewpager.setPageTransformer(true,new BackgroundToForegroundTransformer());
arrayList = new ArrayList<ItemSong>();
arrayList_recent = new ArrayList<ItemSong>();
recyclerView = (RecyclerView)rootView.findViewById(R.id.recyclerView_home_recent);
linearLayoutManager = new LinearLayoutManager(getActivity(),LinearLayoutManager.HORIZONTAL,false);
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setHasFixedSize(true);
if (JsonUtils.isNetworkAvailable(getActivity())) {
new LoadLatestNews().execute(Constant.URL_LATEST);
} else {
Toast.makeText(getActivity(), getResources().getString(R.string.internet_not_conn), Toast.LENGTH_SHORT).show();
}
recyclerView.addOnItemTouchListener(new RecyclerItemClickListener(getActivity(), new RecyclerItemClickListener.OnItemClickListener() {
#Override
public void onItemClick(View view, int position) {
if(JsonUtils.isNetworkAvailable(getActivity())) {
Constant.isOnline = true;
Constant.arrayList_play.clear();
Constant.arrayList_play.addAll(arrayList_recent);
Constant.playPos = position;
((MainActivity)getActivity()).changeText(arrayList_recent.get(position).getMp3Name(),arrayList_recent.get(position).getCategoryName(),position+1,arrayList_recent.size(),arrayList_recent.get(position).getDuration(),arrayList_recent.get(position).getImageBig(),"home");
Constant.context = getActivity();
if(position == 0) {
Intent intent = new Intent(getActivity(), PlayerService.class);
intent.setAction(PlayerService.ACTION_FIRST_PLAY);
getActivity().startService(intent);
}
} else {
Toast.makeText(getActivity(), getResources().getString(R.string.internet_not_conn), Toast.LENGTH_SHORT).show();
}
}
}));
return rootView;
}
private class LoadLatestNews extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
progressHUD.show();
arrayList.clear();
super.onPreExecute();
}
#Override
protected String doInBackground(String... strings) {
try {
String json = JsonUtils.getJSONString(strings[0]);
JSONObject mainJson = new JSONObject(json);
JSONArray jsonArray = mainJson.getJSONArray(Constant.TAG_ROOT);
JSONObject objJson = null;
for (int i = 0; i < jsonArray.length(); i++) {
objJson = jsonArray.getJSONObject(i);
String id = objJson.getString(Constant.TAG_ID);
String cid = objJson.getString(Constant.TAG_CAT_ID);
String cname = objJson.getString(Constant.TAG_CAT_NAME);
String artist = objJson.getString(Constant.TAG_ARTIST);
String name = objJson.getString(Constant.TAG_SONG_NAME);
String url = objJson.getString(Constant.TAG_MP3_URL);
String desc = objJson.getString(Constant.TAG_DESC);
String duration = objJson.getString(Constant.TAG_DURATION);
String image = objJson.getString(Constant.TAG_THUMB_B).replace(" ","%20");
String image_small = objJson.getString(Constant.TAG_THUMB_S).replace(" ","%20");
ItemSong objItem = new ItemSong(id,cid,cname,artist,url,image,image_small,name,duration,desc);
arrayList.add(objItem);
}
return "1";
} catch (JSONException e) {
e.printStackTrace();
return "0";
} catch (Exception ee) {
ee.printStackTrace();
return "0";
}
}
#Override
protected void onPostExecute(String s) {
recyclerView.setAdapter(adapterRecent);
if(s.equals("1")) {
progressHUD.dismissWithSuccess(getResources().getString(R.string.success));
// setLatestVariables(0);
if(Constant.isAppFirst) {
if(arrayList.size()>0) {
Constant.isAppFirst = false;
Constant.arrayList_play.addAll(arrayList);
((MainActivity)getActivity()).changeText(arrayList.get(0).getMp3Name(),arrayList.get(0).getCategoryName(),1,arrayList.size(),arrayList.get(0).getDuration(),arrayList.get(0).getImageBig(),"home");
Constant.context = getActivity();
}
}
viewpager.setAdapter(adapter);
loadRecent();
// adapterPagerTrending = new AdapterPagerTrending(getActivity(),Constant.arrayList_trending);
// viewPager_trending.setAdapter(adapterPagerTrending);
// adapterTopStories = new AdapterTopStories(getActivity(),Constant.arrayList_topstories);
// listView_topstories.setAdapter(adapterTopStories);
// setListViewHeightBasedOnChildren(listView_topstories);
adapterRecent.notifyDataSetChanged();
} else {
progressHUD.dismissWithFailure(getResources().getString(R.string.error));
Toast.makeText(getActivity(), getResources().getString(R.string.server_no_conn), Toast.LENGTH_SHORT).show();
}
super.onPostExecute(s);
recyclerView.setAdapter(adapterRecent);
}
}
private void loadRecent() {
arrayList_recent = dbHelper.loadDataRecent();
adapterRecent = new AdapterRecent(getActivity(),arrayList_recent);
recyclerView.setAdapter(adapterRecent);
if(arrayList_recent.size() == 0) {
recyclerView.setVisibility(View.GONE);
textView_empty.setVisibility(View.VISIBLE);
} else {
recyclerView.setVisibility(View.VISIBLE);
textView_empty.setVisibility(View.GONE);
}
}
private class ImagePagerAdapter extends PagerAdapter {
private LayoutInflater inflater;
public ImagePagerAdapter() {
// TODO Auto-generated constructor stub
inflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return arrayList.size();
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view.equals(object);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
View imageLayout = inflater.inflate(R.layout.viewpager_home, container, false);
assert imageLayout != null;
ImageView imageView = (ImageView) imageLayout.findViewById(R.id.imageView_pager_home);
final ProgressBar spinner = (ProgressBar) imageLayout.findViewById(R.id.loading_home);
TextView title = (TextView) imageLayout.findViewById(R.id.textView_pager_home_title);
TextView cat = (TextView) imageLayout.findViewById(R.id.textView_pager_home_cat);
RelativeLayout rl = (RelativeLayout)imageLayout.findViewById(R.id.rl_homepager);
title.setText(arrayList.get(position).getMp3Name());
cat.setText(arrayList.get(position).getCategoryName());
Picasso.with(getActivity())
.load(arrayList.get(position).getImageBig())
.placeholder(R.mipmap.app_icon)
.into(imageView, new Callback() {
#Override
public void onSuccess() {
spinner.setVisibility(View.GONE);
}
#Override
public void onError() {
spinner.setVisibility(View.GONE);
}
});
rl.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(JsonUtils.isNetworkAvailable(getActivity())) {
//showInter();
playIntent();
} else {
Toast.makeText(getActivity(), getResources().getString(R.string.internet_not_conn), Toast.LENGTH_SHORT).show();
}
}
});
container.addView(imageLayout, 0);
return imageLayout;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
}
}
/* private void showInter() {
Constant.adCount = Constant.adCount + 1;
if(Constant.adCount % Constant.adDisplay == 0) {
((MainActivity)getActivity()).mInterstitial.setAdListener(new AdListener() {
#Override
public void onAdClosed() {
playIntent();
super.onAdClosed();
}
});
if(((MainActivity)getActivity()).mInterstitial.isLoaded()) {
((MainActivity)getActivity()).mInterstitial.show();
((MainActivity)getActivity()).loadInter();
} else {
playIntent();
}
} else {
playIntent();
}
}
*/
private void playIntent() {
Constant.isOnline = true;
int pos = viewpager.getCurrentItem();
Constant.arrayList_play.clear();
Constant.arrayList_play.addAll(arrayList);
Constant.playPos = pos;
((MainActivity)getActivity()).changeText(arrayList.get(pos).getMp3Name(),arrayList.get(pos).getCategoryName(),pos+1,arrayList.size(),arrayList.get(pos).getDuration(),arrayList.get(pos).getImageBig(),"home");
Constant.context = getActivity();
if(pos == 0) {
Intent intent = new Intent(getActivity(), PlayerService.class);
intent.setAction(PlayerService.ACTION_FIRST_PLAY);
getActivity().startService(intent);
}
}
}
Once more, i'm sure what's going on here.
I'm looking this error since 3 days ago but i have checked my code, i dont know what is wrong with this code.
This kind of error occurs when you have a loop that doesn't terminate.I also faced the similar kind of situation and It took me literally two days to find out the root cause of problem.
My problem was:
When I run the above code, I used to get this kind of error
hw_get module_by class _gralloc... .
I was really frustrated because I was not able to find out the root cause and luckily I found out that the above section of the code was the main cause because the loop never goes to terminate in the above section and when I found about the problem main cause I replaced it by:
Then, the problem was solved..
So maybe your problem lies within the loop or similar kind of situations..
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);
}
}
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);
}
}
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