Hello Everyone I am trying to start activity when I click on RecyclerView , it is started when I add the code in the Custom Adapter , but when I write it in Activity it Just give me the position on Log ..
so any help
here is the code OnClick in activity and that's what I tried to do
#Override
public void onItemClick(int position, View v) {
Log.e("TAG", "You clicked number " + mAdapter.getItemId(position) + ", which is at cell position " + position);
// this.startActivity(new Intent(FrameListActivity.this , FinalActivity.class));
// Bitmap frameSelected = results.get(position).getImage();
// Log.e("frameSelected" , frameSelected+"");
// createImageFromBitmap(frameSelected , "frameImage");
positionId = "" + position;
Context context = v.getContext();
Intent intent = new Intent(context.getApplicationContext() , FinalActivity.class);
intent.putExtra("resultpos", "" + positionId);
context.getApplicationContext().startActivity(intent);
finish();
}
here is the activity
package com.abed.montage.hijabapptest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import com.kbeanie.imagechooser.api.ImageChooserManager;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;
public class FrameListActivity extends AppCompatActivity implements PhotoRecyclerViewAdapter.MyClickListener {
private RecyclerView photoRecyclerView;
private RecyclerView.Adapter mAdapter;
private List<Integer> framePhotoList ;
List<PhotoClass> results ;
private static String LOG_TAG = "CardViewActivity";
String positionId ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_frame_list);
photoRecyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);
photoRecyclerView.setHasFixedSize(true);
int numberOfColumns = 2;
// mLayoutManager = new LinearLayoutManager();
photoRecyclerView.setLayoutManager(new GridLayoutManager(this , numberOfColumns));
mAdapter = new PhotoRecyclerViewAdapter(getDataSet() , this);
photoRecyclerView.setAdapter(mAdapter);
}
#Override
protected void onResume() {
super.onResume();
((PhotoRecyclerViewAdapter) mAdapter).setOnItemClickListener(new PhotoRecyclerViewAdapter
.MyClickListener() {
#Override
public void onItemClick(int position, View v) {
Log.i(LOG_TAG, " Clicked on Item " + position);
}
});
}
private List<PhotoClass> getDataSet() {
fillPhotoFrameList();
results = new ArrayList<>();
for (int index = 0; index < framePhotoList.size(); index++) {
PhotoClass obj = new PhotoClass();
obj.setImage(framePhotoList.get(index));
results.add(index, obj);
}
return results;
}
private void fillPhotoFrameList(){
framePhotoList = new ArrayList<>();
framePhotoList.add(R.drawable.frame_1);
framePhotoList.add(R.drawable.frame_2);
framePhotoList.add(R.drawable.frame_3);
framePhotoList.add(R.drawable.frame_4);
framePhotoList.add(R.drawable.frame_5);
framePhotoList.add(R.drawable.frame_6);
framePhotoList.add(R.drawable.frame_7);
framePhotoList.add(R.drawable.frame_8);
framePhotoList.add(R.drawable.frame_2);
framePhotoList.add(R.drawable.frame_10);
framePhotoList.add(R.drawable.frame_11);
framePhotoList.add(R.drawable.frame_12);
framePhotoList.add(R.drawable.frame_13);
framePhotoList.add(R.drawable.frame_14);
framePhotoList.add(R.drawable.frame_15);
framePhotoList.add(R.drawable.frame_16);
framePhotoList.add(R.drawable.frame_17);
framePhotoList.add(R.drawable.frame_18);
framePhotoList.add(R.drawable.frame_19);
framePhotoList.add(R.drawable.frame_20);
}
#Override
public void onItemClick(int position, View v) {
Log.e("TAG", "You clicked number " + mAdapter.getItemId(position) + ", which is at cell position " + position);
// this.startActivity(new Intent(FrameListActivity.this , FinalActivity.class));
// Bitmap frameSelected = results.get(position).getImage();
// Log.e("frameSelected" , frameSelected+"");
// createImageFromBitmap(frameSelected , "frameImage");
positionId = "" + position;
Context context = v.getContext();
Intent intent = new Intent( context , FinalActivity.class);
intent.putExtra("resultpos", "" + positionId);
context.startActivity(intent);
finish();;
}
public String createImageFromBitmap(Bitmap bitmap , String fileNameForSave) {
String fileName = fileNameForSave;//no .png or .jpg needed
try {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, bytes);
FileOutputStream fo = openFileOutput(fileName, Context.MODE_PRIVATE);
fo.write(bytes.toByteArray());
// remember close file output
fo.close();
} catch (Exception e) {
e.printStackTrace();
fileName = null;
}
return fileName;
}
}
and here is the Adapter ....
package com.abed.montage.hijabapptest;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.BitmapFactory;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import java.util.List;
/**
* Created by hp15-AY on 02/27/2017.
*/
public class PhotoRecyclerViewAdapter extends RecyclerView.Adapter<PhotoRecyclerViewAdapter.DataObjectHolder> {
private static String LOG_TAG = "MyRecyclerViewAdapter";
private List<PhotoClass> mDataset;
private static MyClickListener myClickListener;
Context context;
public static class DataObjectHolder extends RecyclerView.ViewHolder
implements View.OnClickListener {
ImageView photo;
public DataObjectHolder(View itemView) {
super(itemView);
photo = (ImageView) itemView.findViewById(R.id.photo);
Log.i(LOG_TAG, "Adding Listener");
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
myClickListener.onItemClick(getAdapterPosition(), v);
// Context context = v.getContext();
// Intent intent = new Intent(context, FinalActivity.class);
// context.startActivity(intent);
}
}
public void setOnItemClickListener(MyClickListener myClickListener) {
this.myClickListener = myClickListener;
}
public PhotoRecyclerViewAdapter(List<PhotoClass> myDataset , Context context) {
this.context = context ;
mDataset = myDataset;
}
#Override
public DataObjectHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.cardview_photo, parent, false);
view.setBackgroundResource(R.drawable.rounded_frame);
DataObjectHolder dataObjectHolder = new DataObjectHolder(view);
return dataObjectHolder;
}
#Override
public void onBindViewHolder(DataObjectHolder holder, int position) {
holder.photo.setImageBitmap(BitmapFactory.decodeResource(context.getResources() ,mDataset.get(position).getImage()));
}
public void addItem(PhotoClass dataObj, int index) {
mDataset.add(index, dataObj);
notifyItemInserted(index);
}
public void deleteItem(int index) {
mDataset.remove(index);
notifyItemRemoved(index);
}
#Override
public int getItemCount() {
return mDataset.size();
}
public interface MyClickListener {
public void onItemClick(int position, View v);
}
}
and here is the class ...
public class PhotoClass {
int id;
int image ;
public PhotoClass() {
}
public void setId(int id) {
this.id = id;
}
public void setImage(int image) {
this.image = image;
}
public int getId() {
return id;
}
public int getImage() {
return image;
}
}
FinalActivity OnCreate
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.i(TAG, "Activity Created");
setContentView(R.layout.activity_final);
mGlobal = (Global) getApplicationContext();
imageViewThumbnail = (ImageView) findViewById(R.id.selectedimage);
saveIcon = (ImageView) findViewById(R.id.imageSave);
filterIcon = (ImageView) findViewById(R.id.editImage);
mImageViewFrame = (ImageView) findViewById(R.id.frameimage);
// mInterstitialAd = new InterstitialAd(this);
// mInterstitialAd.setAdUnitId(getApplicationContext().getString(R.string.admob_intersitials));
// mAdRequest= new AdRequest.Builder().build();
// mInterstitialAd.loadAd(mAdRequest);
imageViewThumbnail.setOnTouchListener(new MultiTouchListener());
mDialog = Utils.SetProgressBar(mDialog, FinalActivity.this);
mDialog.dismiss();
loadImage(imageViewThumbnail, mGlobal.getPath());
String result = getIntent().getStringExtra("resultpos");
pos = Integer.parseInt(result);
Log.w("Position===", "" + pos);
String imagevalue = frames[pos];
Log.w("imagename=====++++", "" + imagevalue);
int resID = getResources().getIdentifier(imagevalue, "drawable", getPackageName());
mImageViewFrame.setImageResource(resID);
saveIcon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// if (mInterstitialAd.isLoaded()) {
// mInterstitialAd.show();
// }
RelativeLayout view = (RelativeLayout) findViewById(R.id.layout);
view.setDrawingCacheEnabled(true);
view.buildDrawingCache();
Bitmap bm = view.getDrawingCache();
SaveImage(bm);
}
});
filterIcon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
RelativeLayout view = (RelativeLayout) findViewById(R.id.layout);
view.setDrawingCacheEnabled(true);
view.buildDrawingCache();
Bitmap bm = view.getDrawingCache();
EditImage(bm);
}
});}
loadImage Function :
private void loadImage(ImageView iv, final String path) {
if(!isAirplaneModeOn(this.getApplicationContext())) {
Picasso.with(FinalActivity.this)
.load(Uri.fromFile(new File(path)))
.fit()
.centerInside()
.into(iv, new Callback() {
#Override
public void onSuccess() {
Log.i(TAG, "Picasso Success Loading Thumbnail - " + path);
}
#Override
public void onError() {
Log.i(TAG, "Picasso Error Loading Thumbnail Small - " + path);
}
});
}
else{
//do something else?
}
File image = new File(path);
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
Bitmap bitmap = BitmapFactory.decodeFile(image.getAbsolutePath(), bmOptions);
engrave(bitmap);
// bitmap = Bitmap.createScaledBitmap(bitmap,parent.getWidth(),parent.getHeight(),true);
}
#SuppressWarnings("deprecation")
#TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
public static boolean isAirplaneModeOn(Context context) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) {
return Settings.System.getInt(context.getContentResolver(),
Settings.System.AIRPLANE_MODE_ON, 0) != 0;
} else {
return Settings.Global.getInt(context.getContentResolver(),
Settings.Global.AIRPLANE_MODE_ON, 0) != 0;
}
}
}
I used setOnClickListener in itemView in the onBindViewHolder.
the itemView is like the container of all things that has the item...
public class MyClassAdapter extends RecyclerView.Adapter<MyClassAdapter.MyClassViewHolder> {
....
....
....
#Override
public void onBindViewHolder(#NonNull final MyClassViewHolder holder, int position) {
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Context context = v.getContext();
Intent intent = new Intent(context , NewActivity.class);
context.startActivity(intent);
}
});
}
....
....
}
This is another example that I find
I created the setOnClickListener on view in onCreateViewHolder
public class MyClassAdapter extends RecyclerView.Adapter<MyClassAdapter.MyClassViewHolder> {
....
....
....
#NonNull
#Override
public MyClassViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
View view = layoutInflater.inflate(R.layout.row_item_example, parent, false);
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
System.out.println("Click in oncReateViewHolder");
}
});
return new SolicitudViewHolder(view);
}
....
....
}
Try this:
in your onResume(): you are already attaching setOnItemClickListener into the PhotoRecyclerViewAdapter
#Override
protected void onResume() {
super.onResume();
((PhotoRecyclerViewAdapter) mAdapter).setOnItemClickListener(new PhotoRecyclerViewAdapter
.MyClickListener() {
#Override
public void onItemClick(int position, View v) {
Log.i(LOG_TAG, " Clicked on Item " + position);
Intent intent = new Intent(FrameListActivity.this , FinalActivity.class);
intent.putExtra("resultpos", "" + position);
startActivity(intent);
}
});
}
Use this:
#Override
public void onItemClick(int position, View v) {
Log.e("TAG", "You clicked number " + mAdapter.getItemId(position) + ", which is at cell position " + position);
// this.startActivity(new Intent(FrameListActivity.this , FinalActivity.class));
// Bitmap frameSelected = results.get(position).getImage();
// Log.e("frameSelected" , frameSelected+"");
// createImageFromBitmap(frameSelected , "frameImage");
positionId = "" + position;
Context context = FrameListActivity.this;
Intent intent = new Intent(context , FinalActivity.class);
intent.putExtra("resultpos", "" + positionId);
context.startActivity(intent);
finish();
}
Hope this helps.
As far as I know, the proper way to attach an onClickListener to a recyclerView, is to do so in the onBindViewHolder method as mentioned as the first option in the answer below. This method binds the properties to each of the recyclerview item, therefore the onClickListener could also be attached similarly.
Related
I have a RecylcerView filled with a Custom Adapter recylerView.setAdapter(myAdapter), and the adaper is filled with different elements by an ArrayList. In the ViewHolder i overrided the
public void onBindViewHolder(#NonNull ViewHolder viewHolder, int position) method. In the custom ViewHolder i put a button. The button has a click listener on it. When i click the button i read the variable position and i am facing that the variable changes every time i click the same button.
Why this happens?
My Adapter is like this:
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.amplifyframework.core.Amplify;
import com.amplifyframework.core.model.query.Where;
import com.amplifyframework.datastore.generated.model.Comments;
import com.amplifyframework.datastore.generated.model.Likes;
import com.amplifyframework.datastore.generated.model.Posts;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.google.firebase.auth.FirebaseAuth;
import java.net.URL;
import java.util.LinkedList;
import de.hdodenhof.circleimageview.CircleImageView;
import static com.amazonaws.mobile.auth.core.internal.util.ThreadUtils.runOnUiThread;
public class PostsAdapter extends RecyclerView.Adapter<PostsAdapter.PostViewHolder>
{
private LinkedList<Posts> usersPostsList;
private FirebaseAuth mAuth;
private Context context;
//private Boolean likeChecker;
private String currentUserId;
private MainActivity mainActivity;
private int currentPosition;
public PostsAdapter(Context context, String currentUserId, MainActivity mainActivity)
{
this.context = context;
this.currentUserId = currentUserId;
this.mainActivity = mainActivity;
}
public PostsAdapter(LinkedList<Posts> usersPostsList, Context context)
{
this.usersPostsList = usersPostsList;
this.context = context;
}
public void setMessages(LinkedList<Posts> usersPostsList) {
this.usersPostsList = usersPostsList;
}
public static class PostViewHolder extends RecyclerView.ViewHolder
{
View mView;
public static ImageButton LikePostButton, CommentPostButton;
public TextView DisplayNoOfLikes, modifyPost;
private TextView DisplayNoOfComments;
String currentUserID;
ExpandableTextView PostDescription;
private Context context;
public PostViewHolder(#NonNull View itemView, Context context)
{
super(itemView);
mView = itemView;
this.context = context;
LikePostButton = (ImageButton) mView.findViewById(R.id.like_button);
CommentPostButton = (ImageButton) mView.findViewById(R.id.comment_button);
DisplayNoOfLikes = (TextView) mView.findViewById(R.id.display_no_of_likes);
DisplayNoOfComments = (TextView) mView.findViewById(R.id.display_no_of_comments);
currentUserID = FirebaseAuth.getInstance().getCurrentUser().getUid();
modifyPost = mView.findViewById(R.id.modify_post);
}
public void setLikeButtonStatus(final String PostKey) {
Amplify.DataStore.query(
Likes.class, Where.matches(Likes.POST_ID.eq(PostKey.trim()).and(Likes.SENDER.eq(currentUserID.trim()))),
items -> {
int countLikes = 0;
if (!items.hasNext()) {
LikePostButton.setImageResource(R.drawable.ic_star_border);
}
while (items.hasNext()) {
Likes item = items.next();
countLikes++;
LikePostButton.setImageResource(R.drawable.ic_star_fill);
Log.i("Amplify", "Id " + item.getId());
}
int finalCountLikes = countLikes;
DisplayNoOfLikes.setText(finalCountLikes + (" Likes"));
},
failure -> Log.e("Amplify", "Could not query DataStore", failure)
);
}
public void setFullname(String fullname)
{
TextView username = (TextView) mView.findViewById(R.id.post_user_name);
username.setText(fullname);
}
public void setProfileimage(Context ctx, String profileimage)
{
CircleImageView image = (CircleImageView) mView.findViewById(R.id.post_profile_image);
Amplify.Storage.getUrl(profileimage,
result -> {
URL url = result.getUrl();
runOnUiThread(() -> Glide.with(ctx)
.load(url)
.apply(new RequestOptions()
.diskCacheStrategy(DiskCacheStrategy.NONE)
.skipMemoryCache(true))
.into(image));
},
error -> Log.i("Amplify", "error while retrieving url"));
}
public void setTime(String time)
{
TextView PostTime = (TextView) mView.findViewById(R.id.post_time);
PostTime.setText(" " + time);
}
public void setDate(String date)
{
TextView PostDate = (TextView) mView.findViewById(R.id.post_date);
PostDate.setText(" " + date);
}
public void setDescription(String description)
{
PostDescription = mView.findViewById(R.id.post_description);
PostDescription.setText(description);
}
public void setPostimage(Context ctx, String postimage, String id)
{
ImageView postImageInner = mView.findViewById(R.id.post_image);
Amplify.Storage.getUrl(postimage,
result -> {
URL url = result.getUrl();
runOnUiThread(() -> Glide.with(ctx)
.load(url)
.apply(new RequestOptions()
.diskCacheStrategy(DiskCacheStrategy.NONE)
.skipMemoryCache(true))
.into(postImageInner));
Log.i("Amplify---------", "url ok----");
},
error -> Log.e("Amplify---------", "error while retrieving url: " + error.getCause().toString()));
postImageInner.setOnClickListener(v -> {
Intent clickPostIntent = new Intent(context, ClickPostActivity.class);
clickPostIntent.putExtra("PostKey", id);
clickPostIntent.putExtra("postImagePath", postimage);
context.startActivity (clickPostIntent);
});
}
public void setCountry(String country)
{
TextView CountryName = (TextView) mView.findViewById(R.id.post_country_name);
CountryName.setText(country);
}
public void setCity(String city)
{
TextView City = (TextView) mView.findViewById(R.id.post_city_name);
City.setText("- " + city);
}
public void setCommentStatus(final String PostKey) {
Amplify.DataStore.query(
Comments.class, Where.matches(Comments.POST_ID.eq(PostKey.trim())),
items -> {
int i = 0;
while (items.hasNext()) {
Comments comments = items.next();
i++;
int finalI = i;
runOnUiThread(() -> DisplayNoOfComments.setText(finalI + " comments"));
Log.i("amplify?", "comment id: " + comments.getId());
}
},
failure -> Log.e("Amplify", "Could not query DataStore", failure)
);
}
}
#NonNull
#Override
public PostViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType)
{
View V = LayoutInflater.from(parent.getContext())
.inflate(R.layout.all_posts_layout, parent,false);
mAuth = FirebaseAuth.getInstance();
return new PostViewHolder(V, context);
}
#Override
public int getItemViewType(int position) {
currentPosition = position;
return position;
}
#Override
public void onBindViewHolder(#NonNull PostViewHolder viewHolder, int position) {
viewHolder.setFullname(usersPostsList.get(position).getFullname());
viewHolder.setTime(usersPostsList.get(position).getTime());
viewHolder.setDate(usersPostsList.get(position).getDate());
viewHolder.setDescription(usersPostsList.get(position).getDescription());
viewHolder.setProfileimage(context, usersPostsList.get(position).getProfileimage());
viewHolder.setPostimage(context, usersPostsList.get(position).getPostimage(), usersPostsList.get(position).getId());
viewHolder.setCountry(usersPostsList.get(position).getCountry());
viewHolder.setCity(usersPostsList.get(position).getCity());
if( viewHolder.PostDescription.originalText.length() > 100 ) {
viewHolder.PostDescription.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!((ExpandableTextView)v).read) {
((ExpandableTextView)v).expandText();
((ExpandableTextView)v).read = true;
} else {
((ExpandableTextView)v).truncateText();
((ExpandableTextView)v).read = false;
}
}
});
}
viewHolder.CommentPostButton.setOnClickListener(v -> {
Intent commentsIntent = new Intent(context, CommentActivity.class);
commentsIntent.putExtra("PostKey",usersPostsList.get(currentPosition).getId());
context.startActivity(commentsIntent);
});
viewHolder.LikePostButton.setOnClickListener(v -> {
Amplify.DataStore.query(
Likes.class, Where.matches(Likes.POST_ID.eq(usersPostsList.get(currentPosition).getId().trim())
.and(Likes.SENDER.eq(currentUserId.trim()))
.and((Likes.RECEIVER.eq(usersPostsList.get(currentPosition).getUid())))
),
items -> {
if (items.hasNext()) {
Likes item = items.next();
Amplify.DataStore.delete(item,
deleted -> Log.i("Amplify", "Deleted item."),
failure -> Log.e("Amplify", "Delete failed.", failure)
);
Log.i("Amplify", "Id " + item.getId());
} else {
Likes likes = Likes.builder()
.receiver(usersPostsList.get(currentPosition).getUid().trim())
.sender(currentUserId.trim())
.postId(usersPostsList.get(currentPosition).getId().trim())
.value("true")
.build();
Amplify.DataStore.save(
likes,
success -> Log.i("Amplify", "Item updated: " + success.item().getId()),
error -> Log.e("Amplify", "Could not save item to DataStore", error)
);
}
},
failure -> {
Log.e("Amplify", "Could not query DataStore", failure);
}
);
notifyDataSetChanged();
});
viewHolder.modifyPost.setOnClickListener(v -> {
Intent intent = new Intent(context, ClickPostActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
intent.putExtra("PostKey", usersPostsList.get(currentPosition).getId());
intent.putExtra("postImagePath", usersPostsList.get(currentPosition).getPostimage());
context.startActivity(intent);
});
}
#Override
public int getItemCount() {
return usersPostsList.size() ;
}
}
Seems that method getItemViewType is called after the click on LikePostButton so that : viewHolder.LikePostButton.setOnClickListener(v -> { gets an older currentPosition variable value
Thanks to everyone helping me to understand
you can override getItemViewType(position:Int) method and replace the line of super to return it with only position like this in Kotlin:
override fun getItemViewType(position: Int): Int {
return position
}
in Java :
#Override
public int getItemViewType(int position) {
return position;
}
Thanks, i solved it setting the listener on the button in the ViewHolder and then just calling getAbsoluteAdapterPosition() to get the correct position
Hi I have MainActivity which has ActionBar, and In Action Bar I Have CartIcon with textview. When i add from fragment i want to increase Textview of Action Bar. But i couldn't do this. Below is my code:
My Badge XML Here
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="48dp"
android:layout_height="fill_parent"
android:layout_gravity="right" >
<!-- Menu Item Image -->
<ImageView
android:id="#+id/cart"
android:layout_width="35dp"
android:layout_height="35dp"
android:clickable="true"
android:layout_marginLeft="-5dp"
android:layout_marginTop="8dp"
android:src="#drawable/ic_add_shopping_cart_black_24dp" />
<!-- Badge Count -->
<TextView
android:id="#+id/actionbar_notifcation_textview"
android:layout_width="25dp"
android:layout_height="25dp"
android:layout_alignParentRight="true"
android:gravity="center"
android:textStyle="bold"
android:padding="5dp"
android:textSize="12sp"
android:text="99"
android:background="#drawable/icon_background"
android:textColor="#android:color/white" />
MainActivity Code Here.
package pk.com.sabsons.sabsons.activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
import pk.com.sabsons.sabsons.R;
import pk.com.sabsons.sabsons.database.DBHelper;
public class MainActivity extends AppCompatActivity {
private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;
private TextView count;
protected DBHelper mDBHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mDBHelper = new DBHelper(MainActivity.this);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
count = (TextView) findViewById(R.id.actionbar_notifcation_textview);
viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new OphthalmicFragment(), "Ophthalmic");
adapter.addFragment(new ContactFragment(), "Contact");
adapter.addFragment(new LenseCareFragment(), "Lens Care");
viewPager.setAdapter(adapter);
viewPager.setSaveFromParentEnabled(false);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
MenuItem item = menu.findItem(R.id.badge);
MenuItemCompat.setActionView(item, R.layout.badger_menu);
RelativeLayout notifCount = (RelativeLayout) MenuItemCompat.getActionView(item);
TextView tv = (TextView) notifCount.findViewById(R.id.actionbar_notifcation_textview);
ImageView img = notifCount.findViewById(R.id.cart);
img.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent cartActivity = new Intent(MainActivity.this,CartActivity.class);
startActivity(cartActivity);
}
});
String count = String.valueOf(mDBHelper.numberOfRows());
tv.setText(count);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
Toast.makeText(this, "Cart Icon is Clicked", Toast.LENGTH_SHORT).show();
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
switch (item.getItemId()) {
case R.id.badge:
// User chose the "Settings" item, show the app settings UI...
Toast.makeText(MainActivity.this, "Its Working in OptionItemSlected here", Toast.LENGTH_SHORT).show();
return true;
case R.id.cart:
// User chose the "Settings" item, show the app settings UI...
Toast.makeText(MainActivity.this, "Its Working in OptionItemSlected here", Toast.LENGTH_SHORT).show();
return true;
default:
// If we got here, the user's action was not recognized.
// Invoke the superclass to handle it.
return super.onOptionsItemSelected(item);
}
}
public void myFunction(){
}
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
}
and My Fragment Code is this.
package pk.com.sabsons.sabsons.activity;
public class OphthalmicFragment extends Fragment implements RvAdapter.AdapterCallBack {
View view;
private List<Ophthamic> lstOphthalmic;
private RecyclerView myrv;
private RvAdapter recyleradpater;
//https://awsrh.blogspot.com/2018/03/volley-glide-tutorial-parse-json.html
// private String URL_JSON = "https://gist.githubusercontent.com/aws1994/f583d54e5af8e56173492d3f60dd5ebf/raw/c7796ba51d5a0d37fc756cf0fd14e54434c547bc/anime.json";
private String URL_JSON = "http://sabsoft.com.pk/Opticals/texting?category='Ophthalmic Lens'";
private JsonArrayRequest ArrayRequest;
private RequestQueue requestQueue;
private ProgressDialog dialog;
public OphthalmicFragment() {
// Required empty public constructor
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
dialog = new ProgressDialog(getActivity());
lstOphthalmic = new ArrayList<>();
jsoncall();
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
myrv = view.findViewById(R.id.rv);
recyleradpater = new RvAdapter(getContext(), lstOphthalmic,this);
myrv.setLayoutManager(new LinearLayoutManager(getActivity()));
myrv.setAdapter(recyleradpater);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
setHasOptionsMenu(true);
return inflater.inflate(R.layout.fragment_ophthalmic, container, false);
}
public void jsoncall() {
ArrayRequest = new JsonArrayRequest(URL_JSON, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
JSONObject jsonObject = null;
for (int i = 0; i < response.length(); i++) {
//Toast.makeText(getApplicationContext(),String.valueOf(i),Toast.LENGTH_SHORT).show();
try {
jsonObject = response.getJSONObject(i);
Ophthamic anime = new Ophthamic();
anime.setId(jsonObject.getString("id"));
anime.setItemCode(jsonObject.getString("code"));
anime.setCategorie(jsonObject.getString("category"));
anime.setAdditional(jsonObject.getString("additional"));
anime.setName(jsonObject.getString("name"));
anime.setDescription(jsonObject.getString("description"));
anime.setImage(jsonObject.getString("image"));
//Toast.makeText(MainActivity.this,anime.toString(),Toast.LENGTH_SHORT).show();
lstOphthalmic.add(anime);
} catch (JSONException e) {
e.printStackTrace();
}
recyleradpater.notifyDataSetChanged();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getActivity(), "Error" + error, Toast.LENGTH_SHORT).show();
}
});
requestQueue = Volley.newRequestQueue(getActivity());
requestQueue.add(ArrayRequest);
}
private synchronized void showDialog(String title) {
if (dialog != null && !dialog.isShowing()) {
dialog.setTitle(title);
dialog.show();
}
}
private synchronized void dismissDialog() {
if (dialog != null && dialog.isShowing()) {
dialog.dismiss();
}
}
#Override
public void onChangeBadgeCount() {
}
}
and My Adpater code is here.
package pk.com.sabsons.sabsons.adapter;
public class RvAdapter extends RecyclerView.Adapter<RvAdapter.MyViewHolder> {
RequestOptions options ;
private Context mContext ;
private List<Ophthamic> mData ;
private Dialog myDialogue;
private DBHelper mDBHelper;
private AlertDialog.Builder builder;
public RvAdapter(Context mContext, List lst, AdapterCallBack adpatercallback) {
this.mContext = mContext;
this.mData = lst;
options = new RequestOptions()
.centerCrop()
.placeholder(R.drawable.loading)
.error(R.drawable.loading);
adpatercallback = adpatercallback;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view ;
LayoutInflater mInflater = LayoutInflater.from(mContext);
view = mInflater.inflate(R.layout.opthalmic_item_row,parent,false);
// click listener here
final MyViewHolder viewHolder = new MyViewHolder(view);
myDialogue = new Dialog(mContext);
myDialogue.setContentView(R.layout.dialogue_box);
myDialogue.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
viewHolder.view_container.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(mContext, DetailsActivity.class);
i.putExtra("id",mData.get(viewHolder.getAdapterPosition()).getId());
i.putExtra("code",mData.get(viewHolder.getAdapterPosition()).getItemCode());
i.putExtra("name",mData.get(viewHolder.getAdapterPosition()).getName());
i.putExtra("additional",mData.get(viewHolder.getAdapterPosition()).getAdditional());
i.putExtra("description",mData.get(viewHolder.getAdapterPosition()).getDescription());
i.putExtra("image",mData.get(viewHolder.getAdapterPosition()).getImage());
mContext.startActivity(i);
}
});
viewHolder.addcart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//Initialize Dialogue Controls
final EditText qty,sph,cyl,addl;
Button qtyadd,qtysub,sphadd,sphsub,cyladd,cylsub,addladd,addlsub;
qtyadd = myDialogue.findViewById(R.id.qtyadd);
qtysub = myDialogue.findViewById(R.id.qtysub);
sphadd = myDialogue.findViewById(R.id.sphadd);
sphsub = myDialogue.findViewById(R.id.sphsub);
cyladd = myDialogue.findViewById(R.id.cyladd);
cylsub = myDialogue.findViewById(R.id.cylsub);
addladd = myDialogue.findViewById(R.id.addladd);
addlsub = myDialogue.findViewById(R.id.addlsub);
qty = myDialogue.findViewById(R.id.qty);
sph = myDialogue.findViewById(R.id.sph);
cyl = myDialogue.findViewById(R.id.cyl);
addl = myDialogue.findViewById(R.id.addl);
TextView dialogue_name = myDialogue.findViewById(R.id.prod_name);
TextView dialogue_category = myDialogue.findViewById(R.id.prod_category);
Button save = myDialogue.findViewById(R.id.btnsave);
Button cancel = myDialogue.findViewById(R.id.btnCancel);
ImageView img = myDialogue.findViewById(R.id.img);
//Hiding Or Showing Additional Layout
LinearLayout addlLayout = myDialogue.findViewById(R.id.addlLayout);
if(mData.get(viewHolder.getAdapterPosition()).getAdditional().equals("0")){
addlLayout.setVisibility(View.GONE);
}else{
addlLayout.setVisibility(View.VISIBLE);
}
//Setting Dialogue Controls
dialogue_name.setText(mData.get(viewHolder.getAdapterPosition()).getName());
dialogue_category.setText(mData.get(viewHolder.getAdapterPosition()).getCategorie());
img.setImageResource(R.drawable.uvs_logo);
myDialogue.show();
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String code = mData.get(viewHolder.getAdapterPosition()).getItemCode();
String name = mData.get(viewHolder.getAdapterPosition()).getName();
String category = mData.get(viewHolder.getAdapterPosition()).getCategorie();
String itemqty = qty.getText().toString() ;
String totalqty = "0" ;
String rp = "0" ;
String totalamount = "0" ;
String itemcyl = cyl.getText().toString();
String itemsph = sph.getText().toString();
String itemaddl = addl.getText().toString();
String itemcolor = "0";
if(mData.get(viewHolder.getAdapterPosition()).getAdditional().equals("0")){
itemaddl = "none";
itemcolor = "none";
}
String image = mData.get(viewHolder.getAdapterPosition()).getImage();
mDBHelper = new DBHelper(mContext);
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
Date d=new Date();
SimpleDateFormat sdf=new SimpleDateFormat("hh:mm a");
String currentDateTimeString = sdf.format(d);
try{
boolean result = mDBHelper.insertOrder(code,name,itemqty,totalqty,rp,totalamount,category,itemcyl,itemsph,itemaddl,itemcolor,image);
if(result == true) {
builder = new AlertDialog.Builder(mContext);
builder.setTitle("Database Status")
.setMessage("Data Inserted")
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
myDialogue.dismiss();
}
})
.setIcon(R.drawable.uvs_logo)
.show();
}else{
Toast.makeText(mContext, "Insert Failed", Toast.LENGTH_SHORT).show();
}
}catch (Exception e){
builder = new AlertDialog.Builder(mContext);
builder.setTitle("Error")
.setMessage(e.getMessage())
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
myDialogue.dismiss();
}
})
.show();
Toast.makeText(mContext, "Failed"+e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
cancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
myDialogue.dismiss();
}
});
qtyadd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Integer quantity = Integer.valueOf(qty.getText().toString());
quantity = quantity +1;
qty.setText(quantity.toString());
}
});
qtysub.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Integer quantity = Integer.valueOf(qty.getText().toString());
if(quantity > 1){
quantity = quantity - 1;
}else{
quantity = 1;
}
qty.setText(quantity.toString());
}
});
sphadd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Double spherical = Double.valueOf(sph.getText().toString());
spherical = spherical + 0.25;
sph.setText(spherical.toString());
}
});
sphsub.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Double spherical = Double.valueOf(sph.getText().toString());
spherical = spherical - 0.25;
sph.setText(spherical.toString());
}
});
cyladd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Double spherical = Double.valueOf(sph.getText().toString());
if(spherical >= 0.0){
Double cylinder = Double.valueOf(cyl.getText().toString());
if(cylinder > 0.0){
cylinder = 0.0;
cyl.setText(cylinder.toString());
Toast.makeText(mContext, "Inside grater than 0", Toast.LENGTH_SHORT).show();
}else if(cylinder < 0.0){
cylinder = cylinder + 0.25;
cyl.setText(cylinder.toString());
}
}else if(spherical <= 0.0) {
Double cylinder = Double.valueOf(cyl.getText().toString());
cylinder = cylinder + 0.25;
cyl.setText(cylinder.toString());
}
}
});
cylsub.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Double spherical = Double.valueOf(sph.getText().toString());
if(spherical <0.0){
Double cylinder = Double.valueOf(cyl.getText().toString());
if(cylinder != 0.0){
cylinder = cylinder - 0.25;
cyl.setText(cylinder.toString());
}
}else {
Double cylinder = Double.valueOf(cyl.getText().toString());
cylinder = cylinder - 0.25;
cyl.setText(cylinder.toString());
}
}
});
addladd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Double additional = Double.valueOf(addl.getText().toString());
additional = additional + 0.25;
addl.setText(additional.toString());
}
});
addlsub.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Double additional = Double.valueOf(addl.getText().toString());
if(additional > 0.0) {
additional = additional - 0.25;
}else{
additional = 0.0;
}
addl.setText(additional.toString());
}
});
}
});
return viewHolder;
}
#Override
public void onBindViewHolder(MyViewHolder holder, final int position) {
holder.tvname.setText(mData.get(position).getName());
holder.tvcat.setText(mData.get(position).getCategorie());
// load image from the internet using Glide
Glide.with(mContext).load(mData.get(position).getImage()).apply(options).into(holder.AnimeThumbnail);
}
#Override
public int getItemCount() {
return mData.size();
}
public static class MyViewHolder extends RecyclerView.ViewHolder {
TextView tvname,tv_rate,tvcat,count;
ImageView AnimeThumbnail,addcart;
LinearLayout view_container;
public MyViewHolder(View itemView) {
super(itemView);
tvname = itemView.findViewById(R.id.rowname);
tv_rate = itemView.findViewById(R.id.rating);
tvcat = itemView.findViewById(R.id.categorie);
AnimeThumbnail = itemView.findViewById(R.id.thumbnail);
view_container = itemView.findViewById(R.id.ophContainer);
addcart = itemView.findViewById(R.id.addcart);
count = itemView.findViewById(R.id.actionbar_notifcation_textview);
}
}
public interface AdapterCallBack{
public void onChangeBadgeCount();
}
}
on Save Click i want to increase cart count but i couldn't able to do so far. please kindly suggest me what can i do to increase cart count from adapter
Here is a screenshot of my activity
Basic approach would be to make use of interface which is what you are doing.
Below just 2 changes in your code :
Implement interface in your Main Activity not in your Fragment.
Replace with below
recyleradpater = new RvAdapter(getContext(), lstOphthalmic,getActivity());
Will work for sure.
Am working on an App in which implements a FOLLOW Button inside a View-pager.
when the user clicks the FOLLOW Button the button should change to FOLLOWING after getting success response from the server.
Although i have implemented it ...The button image doesn't change after the click.it has a very unusual behavior.
It sometimes shows FOLLOWING after the activity is reloaded or the pager slides.
Below is my code..
package comend.com.comendify.adapters;
import android.content.Context;
import android.content.Intent;
import android.support.v4.view.PagerAdapter;
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.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
import comend.com.comendify.R;
import comend.com.comendify.activity.ActViewUserProfile;
import comend.com.comendify.models.Home;
import comend.com.comendify.models.Tags;
import comend.com.comendify.models.User;
import comend.com.comendify.serverCommunication.WebServerSetGetUserActivities;
import comend.com.comendify.utility.RoundedImageView;
import comend.com.comendify.utility.UserJSONUtils;
import comend.com.comendify.utility.Utils;
/**
* Created by qamar on 14-03-2016.
*/
public class ImageViewPagerAdapter extends PagerAdapter {
public static final String TAG = ImageViewPagerAdapter.class.getSimpleName();
Context mContext;
LayoutInflater mLayoutInflater;
private ArrayList<String> imageList;
private ArrayList<Home> home_arrayList;
private String loggedInUserId;
private Button btnFollow,btnUnFollow;
int resourceId;
int START_INDEX;
private User userLogged;
private View itemView ;
Boolean val =true;
private boolean isFollowing = true;
boolean isIconChange;
public ImageViewPagerAdapter(Context context, ArrayList<String> imageList, int START_INDEX, int resoursceId, ArrayList<Home> home_arrayList) {
mContext = context;
this.imageList =imageList;
this.home_arrayList = home_arrayList;
this.resourceId = resoursceId;
this.START_INDEX = START_INDEX;
mLayoutInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
loggedInUserId = Utils.getLoggedInUserId(mContext);
Log.d(TAG,"In ImageViewAdapter: " +START_INDEX+" "+home_arrayList);
}
#Override
public int getCount() {
if(resourceId == R.layout.item_show_image_pager) {
return imageList.size();
}
return home_arrayList.size();
}
#Override
public boolean isViewFromObject(View view, Object object) {
if(resourceId == R.layout.item_home_pager_profile){
return view ==((RelativeLayout)object);
}
return view == ((LinearLayout) object);
}
#Override
public Object instantiateItem(ViewGroup container, final int position) {
Log.d(TAG,"In InstantiateItem" + position);
if(resourceId == R.layout.item_show_image_pager) {
itemView = mLayoutInflater.inflate(R.layout.item_show_image_pager, container, false);
Log.d(TAG, "In viewImage " + position + " " + START_INDEX);
ImageView imageView = (ImageView) itemView.findViewById(R.id.iv_asi_image);
Picasso.with(mContext).load(imageList.get(position))
.fit()
.centerCrop()
.error(R.drawable.logo_splash)
.into(imageView);
container.addView(itemView);
}else if(resourceId == R.layout.item_home_pager_header){
Log.d(TAG, "In homeImageHeader " + position + " " + START_INDEX);
itemView = mLayoutInflater.inflate(R.layout.item_home_pager_header, container, false);
ImageView imageView = (ImageView) itemView.findViewById(R.id.iv_home_image_header);
Picasso.with(mContext).load(String.valueOf(home_arrayList.get(position).getEnt_image()))
.fit()
.centerCrop()
.error(R.drawable.logo_splash)
.into(imageView);
container.addView(itemView);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int fragId = 2;
Intent intent = new Intent(mContext, ActViewUserProfile.class);
intent.putExtra("item_id", home_arrayList.get(position).ent_id);
intent.putExtra("frag_id", fragId);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mContext.startActivity(intent);
Toast.makeText(mContext, "complete item clicked", Toast.LENGTH_LONG).show();
}
});
}else if(resourceId == R.layout.item_home_pager_profile){
//here is the problem in yhis layout
Log.d(TAG, "In homeUserProfile " +home_arrayList);
itemView = mLayoutInflater.inflate(R.layout.item_home_pager_profile,container,false);
//function for setting all the elements of item
setUserCommends(itemView, position);
container.addView(itemView);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.d(TAG,"In ItemView Clicked");
int fragId = 3;
Intent intent = new Intent(mContext, ActViewUserProfile.class);
intent.putExtra("commend_id", home_arrayList.get(position).getUser_commend_id());
intent.putExtra("frag_id", fragId);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mContext.startActivity(intent);
Toast.makeText(mContext, "complete item clicked", Toast.LENGTH_LONG).show();
}
});
}
return itemView;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
if(resourceId ==R.layout.item_show_image_pager) {
container.removeView((LinearLayout) object);
}else if(resourceId == R.layout.item_home_pager_profile){
container.removeView((RelativeLayout)object);
//container.removeViewAt(position);
Log.d(TAG,"In destroy Item " +container.getChildCount());
}
}
//method for setting all the elements
private void setUserCommends(View itemView, final int position){
Log.d(TAG,"In homeprofile setUserCommends " +position );
//Log.d(TAG,"In homeProfile1" +home_arrayList.get(position).getUser_product_image() +" "+home_arrayList.get(position).getUser_image());
ImageView ivProductImage = (ImageView) itemView.findViewById(R.id.iv_hpp_product_pic);
TextView tvProductName = (TextView) itemView.findViewById(R.id.tv_hpp_product_name);
TextView tvProductDesc = (TextView) itemView.findViewById(R.id.tv_hpp_description);
RoundedImageView ivUserImage = (RoundedImageView) itemView.findViewById(R.id.iv_hpp_user_profile_pic);
TextView tvUserName = (TextView) itemView.findViewById(R.id.tv_hpp_profile_name);
btnFollow = (Button) itemView.findViewById(R.id.btn_hpp_follow);
// btnUnFollow = (Button) itemView.findViewById(R.id.btn_hpp_unfollow);
userLogged = new User();
userLogged.setmUserName(home_arrayList.get(position).getUser_name());
userLogged.setmImageUrl(home_arrayList.get(position).getUser_image());
userLogged.setmFirstName(home_arrayList.get(position).getUser_name());
//checking for the buttons for each slides or when the screen first turns up
if(home_arrayList.get(position).getIs_following()== 0){
Log.d(TAG, "In check if " + home_arrayList.get(position).getIs_following());
btnFollow.setCompoundDrawablesWithIntrinsicBounds(R.mipmap.profile_follow, 0, 0, 0);
}else{
Log.d(TAG, "In check else " + home_arrayList.get(position).getIs_following());
btnFollow.setCompoundDrawablesWithIntrinsicBounds(R.mipmap.profile_following, 0, 0, 0);
}
if(!home_arrayList.get(position).getUser_product_image().isEmpty()) {
setImageWithPicasso(ivProductImage, home_arrayList.get(position).getUser_product_image());
}
if(!home_arrayList.get(position).getUser_image().isEmpty()){
setImageWithPicasso(ivUserImage, home_arrayList.get(position).getUser_image());
}
tvProductName.setText(home_arrayList.get(position).getUser_product_name());
tvProductDesc.setText(home_arrayList.get(position).getUser_commend_review());
tvUserName.setText(home_arrayList.get(position).getUser_name());
ivUserImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.d(TAG,"In userImage Clicked");
int fragId = 1;
Intent intent = new Intent(mContext, ActViewUserProfile.class);
intent.putExtra("user_id", home_arrayList.get(position).getUser_id());
intent.putExtra("frag_id", fragId);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mContext.startActivity(intent);
Toast.makeText(mContext, "complete item clicked", Toast.LENGTH_LONG).show();
}
});
//isFollowing = false;
//puttong the clickListener on the follow button
btnFollow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.d(TAG,"In btnFollow Clicked");
//isIconC =!isIconChange;
if (isFollowing =true) {
Log.d(TAG, "in isFollowing");
isFollowing =false;
btnFollow.setCompoundDrawablesWithIntrinsicBounds(R.mipmap.profile_follow, 0, 0, 0);
unFollowUser(home_arrayList.get(position).getUser_id(), position);
} else {
Log.d(TAG, "in isNotFollowing");
isFollowing = true;
btnFollow.setCompoundDrawablesWithIntrinsicBounds(R.mipmap.profile_following, 0, 0, 0);
btnFollow.setText("UNFOLLOW");
//btnFollow.setEnabled(false);
followerUser(home_arrayList.get(position).getUser_id(), position);
}
}
});
}
private void setImageWithPicasso(ImageView imageView, String user_product_image){
Picasso.with(mContext).load(user_product_image)
.fit()
.centerCrop()
.error(R.drawable.logo_splash)
.into(imageView);
}
//Method for Following user
private void followerUser(String user_id, int position) {
final int FOLLOW_TAG = 0;
UserJSONUtils userJSONUtils = new UserJSONUtils(mContext);
String json =userJSONUtils. setDataToJson(userLogged,user_id);
//call the method to follow
callToServerToFollow(json, FOLLOW_TAG,position);
}
//method for UnFollowing user
private void unFollowUser(String user_id, int position){
final int UNFOLLOW_TAG = 1;
UserJSONUtils userJSONUtils = new UserJSONUtils(mContext);
String json = userJSONUtils.setDataToJson(userLogged,user_id);
//calling the method to follow
callToServerToFollow(json, UNFOLLOW_TAG,position);
}
// method for calling server
public void callToServerToFollow(String json,int TAG_FOLL,int position){
WebServerSetGetUserActivities webServerSetGetUserActivities = new WebServerSetGetUserActivities(mContext,btnFollow,btnUnFollow,null,null);
webServerSetGetUserActivities.addFollowUnFollow(json, TAG_FOLL, Tags.ACT_TAG.ACT_HOME_FEED,home_arrayList,position);
}
}
really appreciate any help.
Note, Fragments state on ViewPager are being initialize a Fragment before.
that is if three fragments A,B,C are use on ViewPager, B state is initialize on A while on user view, C also those the same when B is on user View.
There are two way to solve this
1) use A Fragment to implement the request method for response and set a public boolean to get response result true, then on B fragment where the button event is needed, check for boolean result.
2) In your AppController class check for result from A fragment and set to B fragment. This will always keep the result as it is even when the app is onPause.
check this http://www.androidhive.info/2014/05/android-working-with-volley-library-1/ for implementing AppController class.
I am having problem with fragments.I am developing an app like 360 security and i am having problem implementing fragments ,getting "Binary XML file line #1: Error inflating class fragment".
Here is my xml file.I have tried every solution please help me.
Thanks in advance.
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/item_list"
android:name="sabby.completesecurity.MainListFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".ItemListActivity"
tools:layout="#android:layout/list_content" />
This is my activity file:
package sabby.completesecurity;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.FrameLayout;
import android.widget.ImageView;
import sabby.completesecurity.R;
public class MainActivityCache extends FragmentActivity implements sabby.completesecurity.MainCallbacks {
private boolean mIsDualPane;
private boolean mIsArtShowed = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_cache);
mIsDualPane = findViewById(R.id.item_detail_container) != null;
//Show an art when no fragment is showed, we make sure no detail fragment is present.
if (mIsDualPane && getFragmentManager().findFragmentByTag(sabby.completesecurity.DetailFragment.FRAGMENT_TAG) == null) {
ImageView imageView = new ImageView(this);
imageView.setImageResource(R.mipmap.ic_launcher);
imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
((FrameLayout) findViewById(R.id.item_detail_container)).addView(imageView);
mIsArtShowed = true;
}
}
#Override
public void onItemSelected(String packageName) {
if (mIsDualPane) {
//Hide art when a fragment is showed.
if (mIsArtShowed) {
((FrameLayout) findViewById(R.id.item_detail_container)).removeAllViews();
mIsArtShowed = false;
}
getFragmentManager()
.beginTransaction()
.replace(R.id.item_detail_container, DetailFragment.getInstance(packageName), DetailFragment.FRAGMENT_TAG)
.commit();
} else {
Intent intent = new Intent(this, DetailActivity.class);
intent.putExtra(DetailFragment.EXTRA_PACKAGE_NAME, packageName);
startActivity(intent);
}
}
#Override
protected void onStart() {
super.onStart();
registerReceiver(receiver, getIntentFilter());
}
#Override
protected void onStop() {
super.onStop();
unregisterReceiver(receiver);
}
private void showAboutDialog() {
new AlertDialog.Builder(this)
.setTitle("About")
.setView(getLayoutInflater().inflate(R.layout.about_dialog_message, null))
.setNegativeButton(android.R.string.ok, null)
.show();
}
/**
* Used to update the list if a package is added or removed.
*/
private IntentFilter getIntentFilter() {
IntentFilter filter = new IntentFilter();
filter.addDataScheme("package");
filter.addAction(Intent.ACTION_PACKAGE_CHANGED);
filter.addAction(Intent.ACTION_PACKAGE_REPLACED);
filter.addAction(Intent.ACTION_PACKAGE_FULLY_REMOVED);
filter.addAction(Intent.ACTION_PACKAGE_ADDED);
return filter;
}
enter code here
BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
MainListFragment mainListFragment = (MainListFragment) getFragmentManager().findFragmentById(R.id.item_list);
if (mainListFragment != null)
mainListFragment.loadList();
}
};
}
MainListFragment.java
package sabby.completesecurity;
import android.app.ActionBar;
import android.app.Activity;
import android.app.ListFragment;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.IPackageStatsObserver;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageStats;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.RemoteException;
import android.text.format.Formatter;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.SectionIndexer;
import android.widget.Spinner;
import android.widget.TextView;
import sabby.completesecurity.utils.Utils;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
public class MainListFragment extends ListFragment implements AdapterView.OnItemClickListener, AdapterView.OnItemSelectedListener {
private static final int SORT_NAME = 0;
private static final int SORT_PKG = 1;
private static final int SORT_DOMAIN = 2;
private static final int SORT_INSTALLATION = 3;
private static final int SORT_SIZE = 4;
private static final String INSTANCE_STATE_SORT_BY = "sort_by";
private Adapter mAdapter;
private List<Item> mItemList = new ArrayList<Item>();
private int mOnSizeFinishedItemCount;
private PackageManager mPackageManager;
private ProgressDialog mProgressDialog;
private LayoutInflater mLayoutInflater;
private MainCallbacks mCallbacks;
private Context mContext;
private Async mAsyncLoader;
private Spinner mSpinner;
private boolean mSpinnerListenerAuthorized;
private SimpleDateFormat mSimpleDateFormat;
private int mSortBy = 0;
class Item {
ApplicationInfo applicationInfo;
String label;
Long date;
Long size = -1L;
}
private int mColorGrey1;
private int mColorGrey2;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
mProgressDialog = new ProgressDialog(mContext);
mProgressDialog.setTitle(R.string.loading_apps);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgressDialog.setCancelable(false);
//Used to prevent message not showing later
mProgressDialog.setMessage("");
mPackageManager = mContext.getPackageManager();
mSimpleDateFormat = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss");
mColorGrey1 = getResources().getColor(R.color.grey_1);
mColorGrey2 = getResources().getColor(R.color.grey_2);
ActionBar actionBar = getActivity().getActionBar();
actionBar.setDisplayShowCustomEnabled(true);
mSpinner = new Spinner(actionBar.getThemedContext());
SpinnerAdapter spinnerAdapter = new SpinnerAdapter(actionBar.getThemedContext(),
R.array.sort_spinner_items, android.R.layout.simple_list_item_1);
mSpinner.setAdapter(spinnerAdapter);
mSpinnerListenerAuthorized = false;
mSpinner.setOnItemSelectedListener(this);
ActionBar.LayoutParams layoutParams = new ActionBar.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT);
actionBar.setCustomView(mSpinner, layoutParams);
if (savedInstanceState != null)
setSortBy(savedInstanceState.getInt(INSTANCE_STATE_SORT_BY, -1), false);
}
#Override
public void onStart() {
super.onStart();
mSpinner.setSelection(mSortBy);
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(INSTANCE_STATE_SORT_BY, mSortBy);
}
private void onTaskEnded(List<Item> list) {
RetainedFragment retainedFragment = (RetainedFragment) getFragmentManager().findFragmentByTag(RetainedFragment.FRAGMENT_TAG);
retainedFragment.setList(list);
mItemList = list;
mAdapter.notifyDataSetChanged();
if (getListView().getAdapter() == null)
setListAdapter(mAdapter);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
getListView().setOnItemClickListener(this);
getListView().setFastScrollEnabled(true);
mAdapter = new Adapter();
RetainedFragment retainedFragment = (RetainedFragment) getFragmentManager()
.findFragmentByTag(RetainedFragment.FRAGMENT_TAG);
if (retainedFragment == null) {
retainedFragment = new RetainedFragment();
getFragmentManager()
.beginTransaction()
.add(retainedFragment, RetainedFragment.FRAGMENT_TAG)
.commit();
}
if (retainedFragment.getList() != null) {
onTaskEnded(retainedFragment.getList());
mOnSizeFinishedItemCount = mItemList.size();
//Notify spinner that size sort is available
SpinnerAdapter adapter = (SpinnerAdapter) mSpinner.getAdapter();
adapter.notifyDataSetChanged();
} else
loadList();
}
public void loadList() {
mAsyncLoader = new Async();
mAsyncLoader.execute();
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
mCallbacks = (MainCallbacks) activity;
mContext = activity;
mLayoutInflater = activity.getLayoutInflater();
}
#Override
public void onDetach() {
super.onDetach();
if (mAsyncLoader != null)
mAsyncLoader.cancel(true);
mCallbacks = null;
mContext = null;
mLayoutInflater = null;
}
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
if (mCallbacks != null)
mCallbacks.onItemSelected(mItemList.get(i).applicationInfo.packageName);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.fragment_main_list, menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_refresh:
loadList();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
if (mSpinnerListenerAuthorized)
setSortBy(i, true);
mSpinnerListenerAuthorized = true;
}
/**
* Sort main list if provided value is valid.
* #param sort Must be one of SORT_*
* #param checkViews Set if views have to be updated, eg. when restoring state, views aren't
* created yet, so value must be false
*/
public void setSortBy(int sort, boolean checkViews) {
if (sort >= SORT_NAME && sort <= SORT_SIZE) {
mSortBy = sort;
if (checkViews) {
checkFastScroll();
sortApplicationList(mItemList, mSortBy);
mAdapter.notifyDataSetChanged();
}
}
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
private void checkFastScroll() {
getListView().setFastScrollEnabled(mSortBy == SORT_NAME);
}
public void sortApplicationList(List<Item> list, final int sortBy) {
Collections.sort(list, new Comparator<Item>() {
#Override
public int compare(Item item1, Item item2) {
switch (sortBy) {
case SORT_NAME:
return item1.label.compareTo(item2.label);
case SORT_PKG:
return item1.applicationInfo.packageName.compareTo(item2.applicationInfo.packageName);
case SORT_DOMAIN:
boolean isSystem1 = (item1.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
boolean isSystem2 = (item2.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
return Utils.compareBooleans(isSystem1, isSystem2);
case SORT_INSTALLATION:
//Sort in decreasing order
return -item1.date.compareTo(item2.date);
case SORT_SIZE:
return -item1.size.compareTo(item2.size);
default:
return 0;
}
}
});
}
/**
* This method is called by each item when it has finished retrieving its size
* When all items have finished, we set size sort available in spinner, and invalidate
* main list to display sizes in UI.
*/
private void onItemFinishedSizeProcess() {
mOnSizeFinishedItemCount ++;
if (mOnSizeFinishedItemCount == mItemList.size()) {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
SpinnerAdapter adapter = (SpinnerAdapter) mSpinner.getAdapter();
adapter.notifyDataSetChanged();
mAdapter.notifyDataSetChanged();
}
});
}
}
class Adapter extends BaseAdapter implements SectionIndexer {
class ViewHolder {
ImageView icon;
TextView label;
TextView packageName;
TextView version;
TextView isSystemApp;
TextView date;
TextView size;
IconAsyncTask iconLoader;
}
String sections = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
#Override
public int getCount() {
return mItemList.size();
}
#Override
public Object getItem(int i) {
return mItemList.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
ViewHolder holder;
if (view == null) {
view = mLayoutInflater.inflate(R.layout.main_list_item, null);
holder = new ViewHolder();
holder.icon = (ImageView) view.findViewById(R.id.icon);
holder.label = (TextView) view.findViewById(R.id.label);
holder.packageName = (TextView) view.findViewById(R.id.packageName);
holder.version = (TextView) view.findViewById(R.id.version);
holder.isSystemApp = (TextView) view.findViewById(R.id.isSystem);
holder.date = (TextView) view.findViewById(R.id.date);
holder.size = (TextView) view.findViewById(R.id.size);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
holder.iconLoader.cancel(true);
}
view.setBackgroundColor(i % 2 == 0 ? mColorGrey2 : mColorGrey1);
Item item = mItemList.get(i);
ApplicationInfo info = item.applicationInfo;
try {
PackageInfo packageInfo = mPackageManager.getPackageInfo(info.packageName, 0);
holder.version.setText(packageInfo.versionName);
Date date = new Date(packageInfo.firstInstallTime);
holder.date.setText(mSimpleDateFormat.format(date));
} catch (PackageManager.NameNotFoundException e) {
//Do nothing
}
holder.iconLoader = new IconAsyncTask(holder.icon, info);
holder.iconLoader.execute();
holder.label.setText(info.loadLabel(mPackageManager));
holder.packageName.setText(info.packageName);
boolean isSystemApp = (info.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
holder.isSystemApp.setText(isSystemApp ? getString(R.string.system) : getString(R.string.user));
if (item.size != -1L)
holder.size.setText(Formatter.formatFileSize(getActivity(), item.size));
return view;
}
#Override
public int getPositionForSection(int section) {
for (int i = 0; i < this.getCount(); i++) {
String item = mItemList.get(i).label;
if (item.charAt(0) == sections.charAt(section))
return i;
}
return 0;
}
#Override
public int getSectionForPosition(int i) {
return 0;
}
#Override
public Object[] getSections() {
String[] sectionsArr = new String[sections.length()];
for (int i = 0; i < sections.length(); i++)
sectionsArr[i] = "" + sections.charAt(i);
return sectionsArr;
}
class IconAsyncTask extends AsyncTask<Void, Integer, Drawable> {
ImageView imageView;
ApplicationInfo info;
IconAsyncTask(ImageView imageView, ApplicationInfo info) {
this.imageView = imageView;
this.info = info;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
imageView.setVisibility(View.INVISIBLE);
}
#Override
protected Drawable doInBackground(Void... voids) {
if (!isCancelled())
return info.loadIcon(mPackageManager);
return null;
}
#Override
protected void onPostExecute(Drawable drawable) {
super.onPostExecute(drawable);
imageView.setImageDrawable(drawable);
imageView.setVisibility(View.VISIBLE);
}
}
}
class SpinnerAdapter extends BaseAdapter {
private Context mContext;
private int mLayoutResId;
private String[] mItems;
public SpinnerAdapter(Context themedContext, int arrayResId, int layoutResId) {
mContext = themedContext;
mItems = themedContext.getResources().getStringArray(arrayResId);
mLayoutResId = layoutResId;
}
#Override
public int getCount() {
return mItems.length;
}
#Override
public Object getItem(int i) {
return null;
}
#Override
public long getItemId(int i) {
return 0;
}
//It make no sense to implement recycled view system because there is only 5 items in list
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
view = View.inflate(mContext, mLayoutResId, null);
if (view instanceof TextView)
((TextView) view).setText(mItems[i]);
return view;
}
/**
* Set sort_by_size item disabled if all items haven't retrieved them size.
*/
#Override
public boolean isEnabled(int position) {
return position != SORT_SIZE || mItemList != null && mOnSizeFinishedItemCount == mItemList.size();
}
}
class Async extends AsyncTask<Void, Async.Progress, List<Item>> {
class Progress {
String label;
int totalSize;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog.show();
}
#Override
protected List<Item> doInBackground(Void... voids) {
List<ApplicationInfo> applicationInfos = mPackageManager.getInstalledApplications(PackageManager.GET_META_DATA);
Progress progress = new Progress();
progress.totalSize = applicationInfos.size();
List<Item> itemList = new ArrayList<Item>(applicationInfos.size());
mOnSizeFinishedItemCount = 0;
for (ApplicationInfo applicationInfo : applicationInfos) {
if (isCancelled())
break;
Item item = new Item();
item.applicationInfo = applicationInfo;
String label = applicationInfo.loadLabel(mPackageManager).toString();
item.label = label;
try {
item.date = mPackageManager.getPackageInfo(applicationInfo.packageName, 0).firstInstallTime;
} catch (PackageManager.NameNotFoundException e) {
item.date = 0L;
}
itemList.add(item);
getItemSize(item);
progress.label = label;
publishProgress(progress);
}
sortApplicationList(itemList, mSortBy);
return itemList;
}
private void getItemSize(final Item item) {
try {
Method getPackageSizeInfo = mPackageManager.getClass().getMethod(
"getPackageSizeInfo", String.class, IPackageStatsObserver.class);
getPackageSizeInfo.invoke(mPackageManager, item.applicationInfo.packageName, new IPackageStatsObserver.Stub() {
#Override
public void onGetStatsCompleted(final PackageStats pStats, boolean succeeded)
throws RemoteException {
if (succeeded)
item.size = pStats.codeSize + pStats.cacheSize + pStats.dataSize
+ pStats.externalCodeSize + pStats.externalCacheSize + pStats.externalDataSize
+ pStats.externalMediaSize + pStats.externalObbSize;
else
item.size = -1L;
onItemFinishedSizeProcess();
}
});
} catch (NoSuchMethodException e) {
e.printStackTrace();
onItemFinishedSizeProcess();
} catch (IllegalAccessException e) {
e.printStackTrace();
onItemFinishedSizeProcess();
} catch (InvocationTargetException e) {
e.printStackTrace();
onItemFinishedSizeProcess();
}
}
#Override
protected void onProgressUpdate(Progress... values) {
super.onProgressUpdate(values);
Progress progress = values[0];
mProgressDialog.setMessage(progress.label);
if (mProgressDialog.getMax() == 100)
mProgressDialog.setMax(progress.totalSize);
mProgressDialog.incrementProgressBy(1);
}
#Override
protected void onPostExecute(List<Item> list) {
super.onPostExecute(list);
mProgressDialog.hide();
onTaskEnded(list);
}
#Override
protected void onCancelled(List<Item> list) {
super.onCancelled(list);
mProgressDialog.hide();
}
}
}
In the xml that you have posted,replace the TAG <Fragment> with <LinearLayout> or <RelativeLayout> and inside this you simply show what you want to display in you UI
Make sure you extend Fragment class in you fragment activity
Could you post the code for your fragment? The problem could be with your import statements. You have 'import android.support.v4.app.FragmentActivity'. Do you have 'import android.support.v4.app.Fragment' in your fragment file?
I have a Fragment called User Management where I collect data from a server and display it in a ListView. It's also refreshable via SwipeRefreshLayout.
What happens is, if I get data on 1-4 users, it displays the data correctly. However, if I get data on more than 4 users, it displays the first 4 correctly, and instead of the fifth, it's the first one again, instead of the 6th, it's the second one and so on and so on.
I've tried everything I could think of, the adapter is getting the data correctly, the ListView is getting the adapter correctly, but for some reason, it peaks at 4 users displayed, and simply repeats them after that (the funny thing is, if I add a user and then refresh, it simply repeats the next user one more time in the list, so it's definitely aware of the change in user number)
Can you help me finding the problem?
The java class:
package com.softwarenation.jetfuel.fragments.userManagement;
import android.app.AlertDialog;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.ListFragment;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.softwarenation.jetfuel.R;
import com.softwarenation.jetfuel.activities.MainActivity;
import com.softwarenation.jetfuel.fragments.Stations;
import com.softwarenation.jetfuel.managers.JetfuelManager;
import com.softwarenation.jetfuel.managers.StatusManager;
import com.softwarenation.jetfuel.managers.UserManager;
import com.softwarenation.jetfuel.utility.Global;
import com.softwarenation.jetfuel.utility.GlobalConnection;
import com.softwarenation.jetfuel.utility.users.User_pictures;
import com.softwarenation.jetfuel.utility.users.Users_mana;
import org.nicktate.projectile.Method;
import org.nicktate.projectile.Projectile;
import org.nicktate.projectile.StringListener;
import java.io.InputStream;
import java.util.ArrayList;
public class UserManagement extends Fragment {
private SwipeRefreshLayout swipeRefreshLayout;
//private View refreshView;
private Global font = new Global();
private ListView listView;
private ArrayList<User_pictures> pictureses = new ArrayList<User_pictures>();
private static boolean isfirst = false;
private PullToRefreshListView pullToRefreshView;
/**---------------------------------------------------------------------------------------------*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
/**---------------------------------------------------------------------------------------------*/
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_usermanagemnet, container, false);
listView = (ListView)rootView.findViewById(R.id.list);
swipeRefreshLayout = (SwipeRefreshLayout)rootView.findViewById(R.id.swipe);
// refreshView = (View) rootView.findViewById(R.id.swipe);
//First time, we get the data from a server, then only display that data until the user calls for a refresh
if(!StatusManager.getInstance().getUsermStatus()){
UsersTask usersTask = new UsersTask();
usersTask.execute();
}else{
setContent();
}
Button addUser = (Button)rootView.findViewById(R.id.addUser_button);
addUser.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Fragment fragment = new AddUser();
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();
}
});
// Set a listener to be invoked when the list should be refreshed.
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
Log.e("start","onRefresh");
new GetDataTask().execute();
}
}
);
/* pullToRefreshView = (PullToRefreshListView)rootView.findViewById(R.id.pull_to_refresh_listview);
pullToRefreshView.bringToFront();
pullToRefreshView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ListView>() {
#Override
public void onRefresh(PullToRefreshBase<ListView> refreshView) {
// Do work to refresh the list here.
new GetDataTask().execute();
}
});*/
return rootView;
}
public void setOnRefreshListener (SwipeRefreshLayout.OnRefreshListener listener){
swipeRefreshLayout.setOnRefreshListener(listener);
}
public boolean isRefreshing(){
return swipeRefreshLayout.isRefreshing();
}
public void setRefreshing(boolean refreshing){
swipeRefreshLayout.setRefreshing(refreshing);
}
public SwipeRefreshLayout getSwipeRefreshLayout(){
return swipeRefreshLayout;
}
//on refresh, get new data from the server
private class GetDataTask extends AsyncTask<Void, Void, String[]> {
#Override
protected String[] doInBackground(Void... voids) {Log.e("start","GetDataTask");
UsersTask usersTask = new UsersTask();
usersTask.execute();
return new String[0];
}
#Override
protected void onPostExecute(String[] result) {
// Call onRefreshComplete when the list has been refreshed.
// pullToRefreshView.onRefreshComplete();
super.onPostExecute(result);
MainActivity.setBackDisabled(false);
Log.e("GetDataTask","completed");
}
}
private class SampleItem {
public String id;
public String title;
public String username;
public String groupName;
public int userPicture;
public int editPicture;
public int dPicture;
public String activated;
public SampleItem(String id, String title, String username, String groupName, int userPicture, int editPicture, int dPicture, String activated ) {
this.id = id;
this.title = title;
this.username = username;
this.groupName = groupName;
this.userPicture = userPicture;
this.editPicture = editPicture;
this.dPicture = dPicture;
this.activated = activated;
}
}
static class ViewHolder {
private String checkBox;
private RelativeLayout relativeLayout;
private LinearLayout linearLayout;
private RelativeLayout relativeLayout2;
public void setCheckBox(String checkBox) {
this.checkBox = checkBox;
}
public void setLinearLayout(LinearLayout linearLayout) {
this.linearLayout = linearLayout;
}
public void setRelativeLayout(RelativeLayout relativeLayout) {
this.relativeLayout = relativeLayout;
}
public void setRelativeLayout2(RelativeLayout relativeLayout2) {
this.relativeLayout2 = relativeLayout2;
}
public LinearLayout getLinearLayout() {
return linearLayout;
}
public RelativeLayout getRelativeLayout() {
return relativeLayout;
}
public RelativeLayout getRelativeLayout2() {
return relativeLayout2;
}
public RelativeLayout getCheckBox() {
return relativeLayout;
}
}
public class SampleAdapter extends ArrayAdapter<SampleItem> {
final ViewHolder holder = new ViewHolder();
public SampleAdapter(Context context) {
super(context, 0);
}
public View getView(final int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.row_usermana, null);
ImageView userPicture = (ImageView)convertView.findViewById(R.id.userpicture);
userPicture.setImageDrawable(getResources().getDrawable(getItem(position).userPicture));
TextView title = (TextView)convertView.findViewById(R.id.user_name);
font.setFont(title, 3, getActivity());
title.setText(getItem(position).title);
TextView username = (TextView)convertView.findViewById(R.id.username);
font.setFont(username, 2, getActivity());
username.setText(getItem(position).username);
TextView groupname = (TextView)convertView.findViewById(R.id.groupName);
font.setFont(groupname, 2, getActivity());
groupname.setText(getItem(position).groupName);
ImageView useredit = (ImageView)convertView.findViewById(R.id.editbutton);
useredit.setImageDrawable(getResources().getDrawable(getItem(position).editPicture));
useredit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Bundle bundle = new Bundle();
bundle.putString("user_id", getItem(position).id);
Fragment fragment = new EditProfile();
fragment.setArguments(bundle);
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();
}
});
/**---------------*/
ImageView userdelate = (ImageView)convertView.findViewById(R.id.deletebutton);
userdelate.setImageDrawable(getResources().getDrawable(getItem(position).dPicture));
holder.setLinearLayout((LinearLayout)convertView.findViewById(R.id.lin_show_profile));
//LinearLayout show = (LinearLayout)convertView.findViewById(R.id.lin_show_profile);
holder.getLinearLayout().setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Bundle bundle = new Bundle();
bundle.putString("user_id", getItem(position).id);
Fragment fragment = new ShowProfile();
fragment.setArguments(bundle);
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();
}
});
//
holder.setRelativeLayout((RelativeLayout)convertView.findViewById(R.id.delate_user));
//RelativeLayout delete_user = (RelativeLayout)convertView.findViewById(R.id.delate_user);
holder.getRelativeLayout().setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
DialogStop("Are you sure?", getItem(position).username, getActivity(), getItem(position).id);
}
});
//
//holder.setCheckBox(getItem(position).activated);
//
/**---------------*/
//Red or Blue background
// RelativeLayout settings = (RelativeLayout)convertView.findViewById(R.id.settingsbutton);
holder.setRelativeLayout2((RelativeLayout) convertView.findViewById(R.id.settingsbutton));
//if(getItem(position).activated.equals("false")) {
if (getItem(position).activated.equals("false")) {
holder.getLinearLayout().setBackground(getResources().getDrawable(R.drawable.discrepancy_background_red));
holder.getRelativeLayout().setBackground(getResources().getDrawable(R.drawable.discrepancy_background_red));
holder.getRelativeLayout2().setBackground(getResources().getDrawable(R.drawable.discrepancy_background_red));
}
//holder.setCheckBox(getItem(position).activated);
convertView.setTag(holder);
} else {
convertView.getTag();
}
return convertView;
}
}
public void DialogStop(String title, String message,Context context, final String id){
new AlertDialog.Builder(context)
.setTitle(title)
.setMessage(message)
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
//dialog.cancel();
DeleteTask deleteTask = new DeleteTask();
deleteTask.execute(id);
}
})
.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
})
.setIcon(android.R.drawable.ic_dialog_alert)
.show();
}
private class DeleteTask extends AsyncTask<String, String, String>{
#Override
protected String doInBackground(String... params) {
String response = null;
try {
response = new GlobalConnection().DELETE( getString(R.string.apicdeleteuser) + params[0].toString() );
Log.v("response", response + "");
} catch (Exception e) {
e.printStackTrace();
}
return response;
}
#Override
protected void onPostExecute(String response) {
Log.v("response", response + "");
}
}
private class UsersTask extends AsyncTask<String, Void, ArrayList<Users_mana>> {
#Override
protected ArrayList<Users_mana> doInBackground(String... strings) {
//Users_mana users = null;
String response = null;
ArrayList<Users_mana> users_manas = null;
try{Log.e("start","GET via GlobalConnection()");
response = new GlobalConnection().GET( getString(R.string.apiusers));
users_manas = new Gson().fromJson(response, new TypeToken<ArrayList<Users_mana>>(){}.getType());
Log.e("start","setUsers_mana");
UserManager.getInstance().setUsers_mana(users_manas);
}catch (Exception e){
Log.e("response error", e.getMessage().toString());
}
return users_manas;
}
#Override
protected void onPostExecute(ArrayList<Users_mana> response) {
if(!response.isEmpty()) {Log.e("start","setContent()");
setContent();
StatusManager.getInstance().setUsermStatus(true);
Log.e("UsermStatus:",String.valueOf(StatusManager.getInstance().getUsermStatus()));
}
super.onPostExecute(response);
}
}
private void setContent(){
SampleAdapter adapter = new SampleAdapter(getActivity());
adapter.notifyDataSetChanged();
try {
if (!UserManager.getInstance().getUsers_mana().isEmpty()) {
for (int i = 0; i < UserManager.getInstance().getUsers_mana().size(); i++) {
Log.e("adding to adapter:",UserManager.getInstance().getUsers_mana().get(i).firstName + " " + UserManager.getInstance().getUsers_mana().get(i).lastName + "" + UserManager.getInstance().getUsers_mana().get(i).id + "" + UserManager.getInstance().getUsers_mana().get(i).username + "group:" + UserManager.getInstance().getUsers_mana().get(i).group);
adapter.add(new SampleItem(
UserManager.getInstance().getUsers_mana().get(i).id
, UserManager.getInstance().getUsers_mana().get(i).firstName + " " + UserManager.getInstance().getUsers_mana().get(i).lastName
, UserManager.getInstance().getUsers_mana().get(i).username
, UserManager.getInstance().getUsers_mana().get(i).group
, R.drawable.users_test
, R.drawable.settings
, R.drawable.delete
, UserManager.getInstance().getUsers_mana().get(i).activated
));
}
listView.setAdapter(adapter);Log.e("setting","ListView");
}
}catch (Exception e){
Log.e("error setContent", e.getMessage().toString());
}
}
/*
private class PicturesTask extends AsyncTask<String, String ,String>{
#Override
protected String doInBackground(String... urls) {
//String urldisplay = urls[0];
Bitmap mIcon11 = null;
try {
for(int i = 0; i < urls.length; i++) {
if(UserManager.getInstance().getUsers_mana().get(i).photo != null) {
InputStream in = new java.net.URL(getString(R.string.jetfuel_url ) + UserManager.getInstance().getUsers_mana().get(i).username).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
pictureses.add(new User_pictures(mIcon11, UserManager.getInstance().getUsers_mana().get(i).username, UserManager.getInstance().getUsers_mana().get(i).id));
UserManager.getInstance().setUserPictureses(pictureses);
}
}
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String s) {
if(!UserManager.getInstance().getUserPictureses().isEmpty()) {
for (int i = 0; i < UserManager.getInstance().getUserPictureses().size(); i++) {
Log.v("pictures", UserManager.getInstance().getUserPictureses().get(i).picture + "");
}
}
super.onPostExecute(s);
}
}
*/
/**---------------------------------------------------------------------------------------------*/
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.main, menu);
//menu.removeItem(R.id.Station);
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.Station:
Fragment fragment = new Stations();
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
/**---------------------------------------------------------------------------------------------*/
}
The xml view:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<LinearLayout
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/blue">
<Button
android:id="#+id/addUser_button"
android:layout_width="fill_parent"
android:layout_height="50dp"
android:text="#string/add_user"
android:background="#drawable/button_yellow_background"
android:textStyle="bold"
android:textSize="20sp"
android:textColor="#color/blue"/>
<android.support.v4.widget.SwipeRefreshLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/swipe">
<ListView
android:id="#+id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#color/blue"
/>
</android.support.v4.widget.SwipeRefreshLayout>
</LinearLayout>
</RelativeLayout>
Thank you!
There is a huge problem in your SampleAdapter.getView() method.
When you scroll down the View disappearing at the top of the screen is reused to be injected at the bottom. This reused View is the convertView you get as getView parameter.
As you code is, the reused view is injected with the exact same data (because if (convertView == null) { is always false when you scroll).
Images and texts are not updated.
When you scroll down, the element disappearing at the top just appears at the bottom, and so does others...
You should be doing something like:
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.row_usermana, null);
// The ViewHolder constructor should handle the mapping of its views
holder = new ViewHolder(convertView);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
// Here you should only use holder as in:
holder.userpicture.setImageDrawable(getResources().getDrawable(getItem(position).userPicture));
...
}
This method looks strange, and is perhaps suspect. I don't see getUsers_mana() defined anywhere in this sample code, so I don't know if it is the problem or not. For one, you should call that 'UserManager.getInstance().getUsers_mana()' and then 'get(i)' once each and store the results in variables.
private void setContent(){
SampleAdapter adapter = new SampleAdapter(getActivity());
adapter.notifyDataSetChanged();
try {
if (!UserManager.getInstance().getUsers_mana().isEmpty()) {
for (int i = 0; i < UserManager.getInstance().getUsers_mana().size(); i++) {
Log.e("adding to adapter:",UserManager.getInstance().getUsers_mana().get(i).firstName + " " + UserManager.getInstance().getUsers_mana().get(i).lastName + "" + UserManager.getInstance().getUsers_mana().get(i).id + "" + UserManager.getInstance().getUsers_mana().get(i).username + "group:" + UserManager.getInstance().getUsers_mana().get(i).group);
adapter.add(new SampleItem(
UserManager.getInstance().getUsers_mana().get(i).id
, UserManager.getInstance().getUsers_mana().get(i).firstName + " " + UserManager.getInstance().getUsers_mana().get(i).lastName
, UserManager.getInstance().getUsers_mana().get(i).username
, UserManager.getInstance().getUsers_mana().get(i).group
, R.drawable.users_test
, R.drawable.settings
, R.drawable.delete
, UserManager.getInstance().getUsers_mana().get(i).activated
));
}
listView.setAdapter(adapter);Log.e("setting","ListView");
}
}catch (Exception e){
Log.e("error setContent", e.getMessage().toString());
}
}
It is because you are not doing anything in the
else {
convertView.getTag();
}
Check here
Why we should re-assign values for a recycled convertView in getView()
You have to reassign values to the convertView with the data of the 5th roq, 6th row etc. otherwise it still contains the old data
Remove the initialization of holder on the top and just put this line of code in the beginning of getView function.
ViewHolder holder = null;
You need to re initialize holder if its null and you need to update it with latest data if its not null.
See this sample it might help you
https://github.com/erikwt/PullToRefresh-ListView