How to get facebook profile pic android studio - android

im unable to retrieve the facebook profile pic:
package com.androidtutorialpoint.flogin.Adapter;
import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Build;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.androidtutorialpoint.flogin.ImageHelper;
import com.androidtutorialpoint.flogin.Model.Post_Song;
import com.androidtutorialpoint.flogin.R;
import com.squareup.picasso.Callback;
import com.squareup.picasso.Picasso;
import com.squareup.picasso.Target;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
/**
* Created by sravya on 19-02-2017.
*/
public class SongPostListAdapter extends BaseAdapter {
private Context context;
private int layout;
private ArrayList<Post_Song> songlist;
public SongPostListAdapter(ArrayList<Post_Song> songlist, int layout, Context context) {
this.songlist = songlist;
this.layout = layout;
this.context = context;
}
#Override
public int getCount() {
return songlist.size();
}
#Override
public Object getItem(int position) {
return songlist.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
private class ViewHolder{
TextView name,time,title,artist;
LinearLayout song_pic;
}
ImageView profilePicImageView;
#Override
public View getView(int position, View view, ViewGroup parent) {
View row = view;
ViewHolder holder = new ViewHolder();
if(row ==null){
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(layout,null);
holder.artist = (TextView)row.findViewById(R.id.artist);
holder.name = (TextView)row.findViewById(R.id.user_name);
holder.time = (TextView)row.findViewById(R.id.time);
holder.title = (TextView)row.findViewById(R.id.song_title);
holder.song_pic = (LinearLayout)row.findViewById(R.id.track_pic);
//holder.userImage =(ImageView) row.findViewById(R.id.user_pic);
profilePicImageView = (ImageView) row.findViewById(R.id.profilePicture);
row.setTag(holder);
}else{
holder = (ViewHolder)row.getTag();
}
Post_Song posts = songlist.get(position);
holder.artist.setText(posts.getArtist());
holder.name.setText(posts.getUname());
holder.time.setText(posts.getTime());
holder.title.setText(posts.getTitle());
new LoadProfileImage(profilePicImageView).execute(posts.getUser_pic());
final ViewHolder finalHolder = holder;
Picasso.with(context).load(posts.getArtwork()).placeholder(R.drawable.music_placeholder).into(new Target(){
#TargetApi(Build.VERSION_CODES.JELLY_BEAN)
#Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
finalHolder.song_pic.setBackground(new BitmapDrawable(context.getResources(), bitmap));
}
#Override
public void onBitmapFailed(final Drawable errorDrawable) {
Log.d("TAG", "FAILED");
}
#Override
public void onPrepareLoad(final Drawable placeHolderDrawable) {
Log.d("TAG", "Prepare Load");
}
});
return row;
}
private class LoadProfileImage extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
public LoadProfileImage(ImageView bmImage) {
this.bmImage = bmImage;
}
protected Bitmap doInBackground(String... uri) {
String url = uri[0];
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(url).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return mIcon11;
}
protected void onPostExecute(Bitmap result) {
if (result != null) {
Bitmap resized = Bitmap.createScaledBitmap(result,90,90, true);
bmImage.setImageBitmap(ImageHelper.getRoundedCornerBitmap(context,resized,100,90,90, false, false, false, false));
}
}
}
}
This is my adaptor. Iam not able to get the profile pic here.
This is my Facebook fragment, here there is no problem with getting the profile pic
package com.androidtutorialpoint.flogin;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.content.Context;
import android.content.SharedPreferences;
import com.facebook.AccessToken;
import com.facebook.CallbackManager;
import com.facebook.FacebookAuthorizationException;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.FacebookSdk;
import com.facebook.GraphRequest;
import com.facebook.GraphResponse;
import com.facebook.Profile;
import com.facebook.ProfileTracker;
import com.facebook.appevents.AppEventsLogger;
import com.facebook.login.LoginManager;
import com.facebook.login.LoginResult;
import com.facebook.login.widget.LoginButton;
import com.facebook.share.ShareApi;
import com.facebook.share.Sharer;
import com.facebook.share.model.ShareLinkContent;
import com.facebook.share.model.SharePhoto;
import com.facebook.share.model.SharePhotoContent;
import com.facebook.share.widget.ShareDialog;
import org.json.JSONObject;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
public class FacebookFragment extends Fragment{
DatabaseHelper myDb;
private LoginButton loginButton;
private Button getLibrary;
private Button getShared;
private boolean postingEnabled = false;
private static final String PERMISSION = "publish_actions";
private final String PENDING_ACTION_BUNDLE_KEY =
"com.example.hellofacebook:PendingAction";
//private Button postStatusUpdateButton;
// private Button postPhotoButton;
private ImageView profilePicImageView;
private TextView greeting;
private PendingAction pendingAction = PendingAction.NONE;
private boolean canPresentShareDialog;
private boolean canPresentShareDialogWithPhotos;
private CallbackManager callbackManager;
private ProfileTracker profileTracker;
private ShareDialog shareDialog;
private FacebookCallback<Sharer.Result> shareCallback = new FacebookCallback<Sharer.Result>() {
#Override
public void onCancel() {
Log.d("FacebookFragment", "Canceled");
}
#Override
public void onError(FacebookException error) {
Log.d("FacebookFragment", String.format("Error: %s", error.toString()));
String title = getString(R.string.error);
String alertMessage = error.getMessage();
showResult(title, alertMessage);
}
#Override
public void onSuccess(Sharer.Result result) {
Log.d("FacebookFragment", "Success!");
if (result.getPostId() != null) {
String title = getString(R.string.success);
String id = result.getPostId();
String alertMessage = getString(R.string.successfully_posted_post, id);
showResult(title, alertMessage);
}
}
private void showResult(String title, String alertMessage) {
new AlertDialog.Builder(getActivity())
.setTitle(title)
.setMessage(alertMessage)
.setPositiveButton(R.string.ok, null)
.show();
}
};
private enum PendingAction {
NONE,
POST_PHOTO,
POST_STATUS_UPDATE
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
myDb = new DatabaseHelper(getActivity());
FacebookSdk.sdkInitialize(getActivity());
// Other app specific specialization
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_facebook, parent, false);
loginButton = (LoginButton) v.findViewById(R.id.loginButton);
// If using in a fragment
loginButton.setFragment(this);
callbackManager = CallbackManager.Factory.create();
// Callback registration
loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
Toast toast = Toast.makeText(getActivity(), "Logged In", Toast.LENGTH_SHORT);
postingEnabled = true;
// postPhotoButton.setVisibility(View.VISIBLE);
// postStatusUpdateButton.setVisibility(View.VISIBLE);
getLibrary.setVisibility(View.VISIBLE);
getShared.setVisibility(View.VISIBLE);
toast.show();
handlePendingAction();
updateUI();
}
#Override
public void onCancel() {
// App code
if (pendingAction != PendingAction.NONE) {
showAlert();
pendingAction = PendingAction.NONE;
}
updateUI();
}
#Override
public void onError(FacebookException exception) {
if (pendingAction != PendingAction.NONE
&& exception instanceof FacebookAuthorizationException) {
showAlert();
pendingAction = PendingAction.NONE;
}
updateUI();
}
private void showAlert() {
new AlertDialog.Builder(getActivity())
.setTitle(R.string.cancelled)
.setMessage(R.string.permission_not_granted)
.setPositiveButton(R.string.ok, null)
.show();
}
});
shareDialog = new ShareDialog(this);
shareDialog.registerCallback(
callbackManager,
shareCallback);
if (savedInstanceState != null) {
String name = savedInstanceState.getString(PENDING_ACTION_BUNDLE_KEY);
pendingAction = PendingAction.valueOf(name);
}
profileTracker = new ProfileTracker() {
#Override
protected void onCurrentProfileChanged(Profile oldProfile, Profile currentProfile) {
updateUI();
handlePendingAction();
}
};
profilePicImageView = (ImageView) v.findViewById(R.id.profilePicture);
greeting = (TextView) v.findViewById(R.id.greeting);
//postStatusUpdateButton = (Button) v.findViewById(R.id.postStatusUpdateButton);
/*postStatusUpdateButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
onClickPostStatusUpdate();
}
});*/
/*postPhotoButton = (Button) v.findViewById(R.id.postPhotoButton);
postPhotoButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
onClickPostPhoto();
}
});*/
getLibrary = (Button) v.findViewById(R.id.getLibraryButton);
getShared = (Button)v.findViewById(R.id.getSharedButton);
getShared.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(getActivity(), SongPostList.class));
}
});
getLibrary.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(getActivity(), MainActivity.class));
}
});
// Can we present the share dialog for regular links?
canPresentShareDialog = ShareDialog.canShow(
ShareLinkContent.class);
// Can we present the share dialog for photos?
canPresentShareDialogWithPhotos = ShareDialog.canShow(
SharePhotoContent.class);
loginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
LoginManager.getInstance().logInWithReadPermissions(getActivity(), Arrays.asList("public_profile"));
if(!postingEnabled) {
postingEnabled = true;
// postPhotoButton.setVisibility(View.VISIBLE);
// postStatusUpdateButton.setVisibility(View.VISIBLE);
getLibrary.setVisibility(View.VISIBLE);
getShared.setVisibility(View.VISIBLE);
}else{
postingEnabled = false;
// postPhotoButton.setVisibility(View.GONE);
//postStatusUpdateButton.setVisibility(View.GONE);
getLibrary.setVisibility(View.GONE);
getShared.setVisibility(View.GONE);
}
// GraphRequest request = GraphRequest.newMeRequest(AccessToken.getCurrentAccessToken(),
// new GraphRequest.GraphJSONObjectCallback() {
// #Override
// public void onCompleted(
// JSONObject object,
// GraphResponse response) {
// if (object != null) {
// Log.d("Me Request",object.toString());
// Toast t = Toast.makeText(getActivity(), object.toString(), Toast.LENGTH_SHORT);
// t.show();
// }
//
// }
// });
// Bundle parameters = new Bundle();
// parameters.putString("fields", "id,name,link,email");
// request.setParameters(parameters);
// request.executeAsync();
}
});
// loginButton.setOnClickListener(new View.OnClickListener() {
// #Override
// public void onClick(View v) {
//
// LoginManager.getInstance().logInWithReadPermissions(getActivity(), Arrays.asList("public_profile", "user_friends"));
//
//
//
// }
// });
return v;
}
#Override
public void onResume() {
super.onResume();
// Call the 'activateApp' method to log an app event for use in analytics and advertising
// reporting. Do so in the onResume methods of the primary Activities that an app may be
// launched into.
AppEventsLogger.activateApp(getActivity());
updateUI();
}
#Override
public void onPause() {
super.onPause();
// Call the 'deactivateApp' method to log an app event for use in analytics and advertising
// reporting. Do so in the onPause methods of the primary Activities that an app may be
// launched into.
AppEventsLogger.deactivateApp(getActivity());
}
#Override
public void onDestroy() {
super.onDestroy();
profileTracker.stopTracking();
}
private void updateUI() {
boolean enableButtons = AccessToken.getCurrentAccessToken() != null;
//postStatusUpdateButton.setEnabled(enableButtons || canPresentShareDialog);
//postPhotoButton.setEnabled(enableButtons || canPresentShareDialogWithPhotos);
Profile profile = Profile.getCurrentProfile();
if (enableButtons && profile != null) {
new LoadProfileImage(profilePicImageView).execute(profile.getProfilePictureUri(200, 200).toString());
greeting.setText(getString(R.string.hello_user, profile.getName()));
boolean isInserted =myDb.insertData(profile.getId(),profile.getName(),profile.getProfilePictureUri(200,200).toString());
if(isInserted == true){
Toast.makeText(getActivity(),"Data Inserted",Toast.LENGTH_LONG).show();
SharedPreferences settings = getActivity().getSharedPreferences("mysettings",
Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.putString("uid", profile.getId());
editor.putString("name",profile.getName());
editor.putString("pic",profile.getProfilePictureUri(200,200).toString());
editor.commit();
}else{
Toast.makeText(getActivity(),"Not Inserted",Toast.LENGTH_LONG).show();
}
postingEnabled = true;
//postPhotoButton.setVisibility(View.VISIBLE);
//postStatusUpdateButton.setVisibility(View.VISIBLE);
getLibrary.setVisibility(View.VISIBLE);
getShared.setVisibility(View.VISIBLE);
} else {
Bitmap icon = BitmapFactory.decodeResource(getContext().getResources(),R.drawable.user_default);
profilePicImageView.setImageBitmap(ImageHelper.getRoundedCornerBitmap(getContext(), icon, 200, 200, 200, false, false, false, false));
greeting.setText(null);
postingEnabled = false;
// postPhotoButton.setVisibility(View.GONE);
//postStatusUpdateButton.setVisibility(View.GONE);
getLibrary.setVisibility(View.GONE);
getShared.setVisibility(View.GONE);
}
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putString(PENDING_ACTION_BUNDLE_KEY, pendingAction.name());
}
private void handlePendingAction() {
PendingAction previouslyPendingAction = pendingAction;
// These actions may re-set pendingAction if they are still pending, but we assume they
// will succeed.
pendingAction = PendingAction.NONE;
switch (previouslyPendingAction) {
case NONE:
break;
case POST_PHOTO:
postPhoto();
break;
case POST_STATUS_UPDATE:
postStatusUpdate();
break;
}
}
private void onClickPostStatusUpdate() {
performPublish(PendingAction.POST_STATUS_UPDATE, canPresentShareDialog);
}
private void postStatusUpdate() {
Profile profile = Profile.getCurrentProfile();
ShareLinkContent linkContent = new ShareLinkContent.Builder()
.setContentTitle("Integrate Facebook Login to your Android App")
.setContentDescription(
"This app shows how to integrate Facebook Login to your Android App")
.setContentUrl(Uri.parse("http://www.androidtutorialpoint.com/material-design/adding-facebook-login-to-android-app/"))
.build();
if (canPresentShareDialog) {
shareDialog.show(linkContent);
} else if (profile != null && hasPublishPermission()) {
ShareApi.share(linkContent, shareCallback);
} else {
pendingAction = PendingAction.POST_STATUS_UPDATE;
}
}
private void onClickPostPhoto() {
performPublish(PendingAction.POST_PHOTO, canPresentShareDialogWithPhotos);
}
private void postPhoto() {
Bitmap image = BitmapFactory.decodeResource(this.getResources(), R.drawable.androidlogo);
SharePhoto sharePhoto = new SharePhoto.Builder().setBitmap(image).build();
ArrayList<SharePhoto> photos = new ArrayList<>();
photos.add(sharePhoto);
SharePhotoContent sharePhotoContent =
new SharePhotoContent.Builder().setPhotos(photos).build();
if (canPresentShareDialogWithPhotos) {
shareDialog.show(sharePhotoContent);
} else if (hasPublishPermission()) {
ShareApi.share(sharePhotoContent, shareCallback);
} else {
pendingAction = PendingAction.POST_PHOTO;
// We need to get new permissions, then complete the action when we get called back.
LoginManager.getInstance().logInWithPublishPermissions(
this,
Arrays.asList(PERMISSION));
}
}
private boolean hasPublishPermission() {
AccessToken accessToken = AccessToken.getCurrentAccessToken();
return accessToken != null && accessToken.getPermissions().contains("publish_actions");
}
private void performPublish(PendingAction action, boolean allowNoToken) {
AccessToken accessToken = AccessToken.getCurrentAccessToken();
if (accessToken != null || allowNoToken) {
pendingAction = action;
handlePendingAction();
}
}
/**
* Background Async task to load user profile picture from url
* */
private class LoadProfileImage extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
public LoadProfileImage(ImageView bmImage) {
this.bmImage = bmImage;
}
protected Bitmap doInBackground(String... uri) {
String url = uri[0];
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(url).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return mIcon11;
}
protected void onPostExecute(Bitmap result) {
if (result != null) {
Bitmap resized = Bitmap.createScaledBitmap(result,200,200, true);
bmImage.setImageBitmap(ImageHelper.getRoundedCornerBitmap(getContext(),resized,250,200,200, false, false, false, false));
}
}
}
}
Please help, iam unable to figure out whats wrong

Instead of downloading the image using a custom class extended from AsyncTask you can load it with Picasso.
Uri image = Profile.getCurrentProfile().getProfilePictureUri(200, 200);
Picasso.with(context).load(image).placeholder(R.drawable.placeholder).into(imageView);

Related

I found this error in logcat hw_get_module_by_class: module name gralloc

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..

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

First message is duplicated

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);
}
}

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

my fragment showing blank screen after i am having this code

package com.example.mindwareuae;
import java.util.Arrays;
import java.util.List;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.InputFilter.LengthFilter;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.facebook.Request;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.SessionState;
import com.facebook.UiLifecycleHelper;
import com.facebook.model.GraphUser;
import com.facebook.widget.LoginButton;
import com.facebook.widget.LoginButton.UserInfoChangedCallback;
public class FacebokkFragment extends Fragment{
private LoginButton loginBtn;
private Button postImageBtn;
private Button updateStatusBtn;
private TextView userName;
private UiLifecycleHelper uiHelper;
private static final List<String> PERMISSIONS = Arrays.asList("publish_actions");
View rootView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
if (rootView != null) {
ViewGroup parent = (ViewGroup) rootView.getParent();
if (parent != null) {
parent.removeView(rootView);
}
}
try
{
View rootView = inflater.inflate(R.layout.fragment_facebook,container,false);
userName = (TextView)rootView.findViewById(R.id.user_name);
loginBtn = (LoginButton) rootView.findViewById(R.id.fb_login_button);
loginBtn.setUserInfoChangedCallback(new UserInfoChangedCallback() {
#Override
public void onUserInfoFetched(GraphUser user) {
if (user != null) {
userName.setText("Hello, " + user.getName());
} else {
userName.setText("You are not logged");
}
}
});
postImageBtn = (Button)rootView.findViewById(R.id.fbpost_image);
postImageBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
postImage();
}
});
updateStatusBtn = (Button)rootView.findViewById(R.id.fbupdate_status);
updateStatusBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
}
});
buttonsEnabled(false);
}catch(Exception e)
{
e.printStackTrace();
}
return rootView;
}
public void buttonsEnabled(boolean isEnabled) {
postImageBtn.setEnabled(isEnabled);
updateStatusBtn.setEnabled(isEnabled);
}
public void postImage() {
if (checkPermissions()) {
Bitmap img = BitmapFactory.decodeResource(getResources(),
R.drawable.ic_launcher);
Request uploadRequest = Request.newUploadPhotoRequest(
Session.getActiveSession(), img, new Request.Callback() {
#Override
public void onCompleted(Response response) {
Toast.makeText(getActivity(),
"Photo uploaded successfully",
Toast.LENGTH_LONG).show();
}
});
uploadRequest.executeAsync();
} else {
requestPermissions();
}
}
// public void postStatusMessage() {
// if (checkPermissions()) {
// Request request = Request.newStatusUpdateRequest(
// Session.getActiveSession(), message,
// new Request.Callback() {
// #Override
// public void onCompleted(Response response) {
// if (response.getError() == null)
// Toast.makeText(getActivity(),
// "Status updated successfully",
// Toast.LENGTH_LONG).show();
// }
// });
// request.executeAsync();
// } else {
// requestPermissions();
// }
// }
public boolean checkPermissions() {
Session s = Session.getActiveSession();
if (s != null) {
return s.getPermissions().contains("publish_actions");
} else
return false;
}
public void requestPermissions() {
Session s = Session.getActiveSession();
if (s != null)
s.requestNewPublishPermissions(new Session.NewPermissionsRequest(
this, PERMISSIONS));
}
// #Override
// public void onResume() {
// super.onResume();
// uiHelper.onResume();
// buttonsEnabled(Session.getActiveSession().isOpened());
// }
//
// #Override
// public void onPause() {
// super.onPause();
// uiHelper.onPause();
// }
//
// #Override
// public void onDestroy() {
// super.onDestroy();
// if (rootView != null) {
// ViewGroup parentViewGroup = (ViewGroup) rootView.getParent();
// if (parentViewGroup != null) {
// parentViewGroup.removeAllViews();
// }
// }
// uiHelper.onDestroy();
// }
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
uiHelper.onActivityResult(requestCode, resultCode, data);
}
#Override
public void onSaveInstanceState(Bundle savedState) {
super.onSaveInstanceState(savedState);
uiHelper.onSaveInstanceState(savedState);
}
}
i want login the facbook from this fragment..but i am not getiing any thing my xml file is
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:facebook="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_horizontal"
android:orientation="vertical"
android:padding="20dp"
android:background="#EEEEEE">
<com.facebook.widget.LoginButton
android:id="#+id/fb_login_button"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
facebook:confirm_logout="false"
facebook:fetch_user_info="true" />
<TextView
android:id="#+id/fb_user"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_margin="10dp"
android:textSize="18sp" />
<Button
android:id="#+id/fbupdate_status"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="update_status" />
<Button
android:id="#+id/fbpost_image"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="post_image" />
</LinearLayout>
it is my xml file why i am not able to get the fragment with my facebook login button.
please any one can explain me.
Create a FragmentActivity and add your fragment to that FragmentActivity
public class MainActivity extends FragmentActivity{
FacebokkFragment fbFragment;
ArrayList<Fragment> fragemetnList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
fbFragment = new FacebokkFragment();
fragemetnList = getFragmnetsList();
setContentView(R.layout.activity_main);
}
ArrayList<Fragment> getFragmnetsList() {
ArrayList<Fragment> fragments = new ArrayList<Fragment>();
fragments.add(fbFragment);
// you can also add more fragments here
return fragments;
}
}
Now create an activity_main.xml file into your res/layout directory
Don't forget to make the entry of your MainActivity into AndroidManifest.xml file
May this code will solve your problem
if (rootView != null) {
ViewGroup parent = (ViewGroup) rootView.getParent();
if (parent != null) {
parent.removeView(rootView);
}
}
Is this part of code really required? Try removing this.
Try this
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_facebook, container, false);
...
return rootView;

Categories

Resources