How can I save my current ImageView when I press onClick?
Im currently having the problem that the image that is next in line is being saved instead of the current actual image..
My Code for saving onLike
public class MainActivity extends Activity implements SwipeView.OnCardSwipedListener {
// Declaring variables
private final static int CARDS_MAX_ELEMENTS = 5;
private FrameLayout contentLayout;
private SwipeView mSwipeView;
private View addCardc41;
private Firebase mRef;
public ImageView imageLogo;
public ImageView imageview;
private static final String TAG = "MyActivity";
// Creating array of meals, getting them from the drawable folder
private int[] meals = {
R.drawable.a,
R.drawable.b,
R.drawable.c,
R.drawable.d,
R.drawable.e,
R.drawable.f,
R.drawable.g,
R.drawable.h,
R.drawable.i,
R.drawable.j
};
// Declaring a counter for the next method
private int count = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_swipe_view_demo);
contentLayout = (FrameLayout) findViewById(R.id.contentLayout);
imageLogo = (ImageView) findViewById(R.id.imageView3);
imageview = (ImageView) findViewById(R.id.imageView);
// Add the swipe view
mSwipeView = new SwipeView(this, R.id.imgSwipeLike, R.id.imgSwipeNope,
this);
contentLayout.addView(mSwipeView);
// Adding the cards initially with the maximum limits of cards.
for (int i = 0; i < CARDS_MAX_ELEMENTS; i++) {
addCard(i);
}
}
/**
* On clicked view.
*
* #param clickedView
* the clicked view
*/
public void onClickedView(View clickedView) {
switch (clickedView.getId()) {
case R.id.imgDisLike: {
mSwipeView.dislikeCard();
break;
}
case R.id.imgLike: {
mSwipeView.likeCard();
break;
}
}
}
#Override
public void onLikes() {
imageview.setDrawingCacheEnabled(true); //Add this line.
imageview.buildDrawingCache();
Bitmap bm=imageview.getDrawingCache();
OutputStream fOut = null;
Uri outputFileUri;
try {
File root = new File(Environment.getExternalStorageDirectory()
+ File.separator + "folder_name" + File.separator);
root.mkdirs();
File sdImageMainDirectory = new File(root, "myPicName.jpg");
outputFileUri = Uri.fromFile(sdImageMainDirectory);
fOut = new FileOutputStream(sdImageMainDirectory);
MediaScannerConnection.scanFile(this, new String[] { sdImageMainDirectory.getAbsolutePath() }, null, null);
} catch (Exception e) {
Toast.makeText(this, "Error occured. Please try again later.",
Toast.LENGTH_SHORT).show();
}
try {
bm.compress(Bitmap.CompressFormat.PNG, 100, fOut);
fOut.flush();
fOut.close();
} catch (Exception e){}
System.out.println("An Card removed");
// Add a card if you needed after any previous card swiped
addCard(0);
}
#Override
public void onDisLikes() {
System.out.println("An Card removed");
// Add a card if you needed after any previous card swiped
addCard(0);
}
#Override
public void onSingleTap() {
}
/**
* Adds the card to the swipe.
*/
private void addCard(int position) {
final View cardView = LayoutInflater.from(this).inflate(
R.layout.item_swipe_view, null);
final ImageView imgMeal = (ImageView) cardView
.findViewById(R.id.imgMeals);
imgMeal.setImageResource(meals[count]);
count++;
if (count == meals.length) {
count = 0;
}
// Add a card to the swipe view..
mSwipeView.addCard(cardView, position);
// Create OnClickListener for the CookBookActivity
// Declare Button for the Cookbook
Button btn = (Button) findViewById(R.id.button3);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, CookbookActivity.class));
}
});
// Check Authentication
mRef = new Firebase(Constants.FIREBASE_URL);
if (mRef.getAuth() == null) {
loadLoginView();
}
}
private void loadLoginView() {
Intent intent = new Intent(this, LoginActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
}
The Library that i'm using for the swiping
//
// credits to IntelliJ IDEA
// (powered by Fernflower decompiler)
package com.rk.lib.view;
import android.content.Context;
import android.os.Handler;
import android.os.Build.VERSION;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.View.OnTouchListener;
import android.view.animation.AlphaAnimation;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.FrameLayout.LayoutParams;
public class SwipeView extends FrameLayout {
private View mFocusedView;
private View mFocusedViewLike;
private View mFocusedViewNope;
private int mFocusedViewWidth;
private float mPreviousAlpha = 0.0F;
private Integer mLikeResource = Integer.valueOf(0);
private Integer mNopeResource = Integer.valueOf(0);
private static final int MAX_ELEMENTS = 3;
private static final long DELAY_SCROLL_RUNNABLE = 1L;
private static final int SCROLL_LENGTH = 5;
private int mScrolledPixelsX;
private int mScrolledPixelsY;
private int mNeedToScrollX;
private int mNeedToScrollY;
private int mTotalScrolledX;
private int mTotalScrolledY;
private int mScrollLengthX = 5;
private int mScrollLengthY = 5;
private boolean enableTouchSwipe = true;
private Context mContext;
private SwipeView.ScrollMode mScrollModeX;
private SwipeView.ScrollMode mScrollModeY;
private SwipeView.ScrollDirection mScrollDirection;
private int[] paddingX;
private int[] paddingYTop;
private int[] paddingYBottom;
private SwipeView.OnCardSwipedListener mOnCardSwipedListener;
private Handler mScrollHandler;
private Runnable mScrollRunnable;
private final SimpleOnGestureListener simpleOnGestureListener;
public SwipeView(Context context, Integer likeResource, Integer nopeResource, SwipeView.OnCardSwipedListener cardSwipeListener) {
super(context);
this.mScrollModeX = SwipeView.ScrollMode.NONE;
this.mScrollModeY = SwipeView.ScrollMode.NONE;
this.mScrollDirection = SwipeView.ScrollDirection.NONE;
this.paddingX = new int[]{0, 10, 20};
this.paddingYTop = new int[]{0, 10, 20};
this.paddingYBottom = new int[]{20, 10, 0};
this.mScrollHandler = new Handler();
this.mScrollRunnable = new Runnable() {
public void run() {
boolean scrollX;
boolean scrollY;
int scrollX1;
int scrollY1;
if(SwipeView.this.mScrollDirection == SwipeView.ScrollDirection.OUT) {
if(SwipeView.this.mNeedToScrollX <= 0 && SwipeView.this.mNeedToScrollY <= 0) {
SwipeView.this.mScrollHandler.removeCallbacks(SwipeView.this.mScrollRunnable);
SwipeView.this.removeView(SwipeView.this.mFocusedView);
if(SwipeView.this.mScrollModeX == SwipeView.ScrollMode.LEFT) {
SwipeView.this.mOnCardSwipedListener.onLikes();
} else if(SwipeView.this.mScrollModeX == SwipeView.ScrollMode.RIGHT) {
SwipeView.this.mOnCardSwipedListener.onDisLikes();
}
SwipeView.this.alignCardsPadding();
} else {
if(SwipeView.this.mNeedToScrollX < SwipeView.this.mScrollLengthX) {
SwipeView.this.mScrollLengthX = SwipeView.this.mNeedToScrollX;
SwipeView.this.mNeedToScrollX = 0;
} else {
SwipeView.this.mNeedToScrollX = SwipeView.this.mNeedToScrollX - SwipeView.this.mScrollLengthX;
}
if(SwipeView.this.mNeedToScrollY < SwipeView.this.mScrollLengthY) {
SwipeView.this.mScrollLengthY = SwipeView.this.mNeedToScrollY;
SwipeView.this.mNeedToScrollY = 0;
} else {
SwipeView.this.mNeedToScrollY = SwipeView.this.mNeedToScrollY - SwipeView.this.mScrollLengthY;
}
scrollX = false;
scrollY = false;
if(SwipeView.this.mScrollModeX == SwipeView.ScrollMode.LEFT) {
scrollX1 = -SwipeView.this.mScrollLengthX;
} else {
scrollX1 = SwipeView.this.mScrollLengthX;
}
if(SwipeView.this.mScrollModeY == SwipeView.ScrollMode.TOP) {
scrollY1 = -SwipeView.this.mScrollLengthY;
} else {
scrollY1 = SwipeView.this.mScrollLengthY;
}
SwipeView.this.mFocusedView.scrollBy(scrollX1, scrollY1);
SwipeView.this.mScrollHandler.postDelayed(SwipeView.this.mScrollRunnable, 1L);
}
} else if(SwipeView.this.mScrollDirection == SwipeView.ScrollDirection.IN) {
if(SwipeView.this.mTotalScrolledX <= 0 && SwipeView.this.mTotalScrolledY <= 0) {
SwipeView.this.mScrollHandler.removeCallbacks(SwipeView.this.mScrollRunnable);
SwipeView.this.mScrollDirection = SwipeView.ScrollDirection.NONE;
} else {
if(SwipeView.this.mTotalScrolledX < SwipeView.this.mScrollLengthX) {
SwipeView.this.mScrollLengthX = SwipeView.this.mTotalScrolledX;
SwipeView.this.mTotalScrolledX = 0;
} else {
SwipeView.this.mTotalScrolledX = SwipeView.this.mTotalScrolledX - SwipeView.this.mScrollLengthX;
}
if(SwipeView.this.mTotalScrolledY < SwipeView.this.mScrollLengthY) {
SwipeView.this.mScrollLengthY = SwipeView.this.mTotalScrolledY;
SwipeView.this.mTotalScrolledY = 0;
} else {
SwipeView.this.mTotalScrolledY = SwipeView.this.mTotalScrolledY - SwipeView.this.mScrollLengthY;
}
scrollX = false;
scrollY = false;
if(SwipeView.this.mScrollModeX == SwipeView.ScrollMode.LEFT) {
scrollX1 = SwipeView.this.mScrollLengthX;
} else {
scrollX1 = -SwipeView.this.mScrollLengthX;
}
if(SwipeView.this.mScrollModeY == SwipeView.ScrollMode.TOP) {
scrollY1 = -SwipeView.this.mScrollLengthY;
} else {
scrollY1 = SwipeView.this.mScrollLengthY;
}
SwipeView.this.mFocusedView.scrollBy(scrollX1, scrollY1);
SwipeView.this.mScrollHandler.postDelayed(SwipeView.this.mScrollRunnable, 1L);
}
}
}
};
this.simpleOnGestureListener = new SimpleOnGestureListener() {
public boolean onSingleTapConfirmed(MotionEvent e) {
SwipeView.this.mOnCardSwipedListener.onSingleTap();
return super.onSingleTapConfirmed(e);
}
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
if(SwipeView.this.mFocusedView != null) {
SwipeView.this.mScrolledPixelsX = SwipeView.this.mScrolledPixelsX + (int)distanceX;
SwipeView.this.mScrolledPixelsY = SwipeView.this.mScrolledPixelsY + (int)distanceY;
SwipeView.this.mFocusedView.scrollBy((int)distanceX, (int)distanceY);
float alpha = (float)SwipeView.this.mScrolledPixelsX / (float)SwipeView.this.mFocusedViewWidth;
if(alpha > 0.0F) {
SwipeView.this.mFocusedViewNope.setVisibility(0);
SwipeView.this.mFocusedViewLike.setVisibility(8);
SwipeView.setAlpha(SwipeView.this.mFocusedViewNope, SwipeView.this.mPreviousAlpha, alpha);
SwipeView.this.mPreviousAlpha = alpha;
} else {
SwipeView.this.mFocusedViewNope.setVisibility(8);
SwipeView.this.mFocusedViewLike.setVisibility(0);
SwipeView.setAlpha(SwipeView.this.mFocusedViewLike, SwipeView.this.mPreviousAlpha, -alpha);
SwipeView.this.mPreviousAlpha = -alpha;
}
}
return true;
}
};
this.mContext = context;
this.mLikeResource = likeResource;
this.mNopeResource = nopeResource;
this.mOnCardSwipedListener = cardSwipeListener;
float density = this.getResources().getDisplayMetrics().density;
for(int gestureDetector = 0; gestureDetector < this.paddingX.length; ++gestureDetector) {
this.paddingX[gestureDetector] = (int)((float)this.paddingX[gestureDetector] * density);
this.paddingYTop[gestureDetector] = (int)((float)this.paddingYTop[gestureDetector] * density);
this.paddingYBottom[gestureDetector] = (int)((float)this.paddingYBottom[gestureDetector] * density);
}
final GestureDetector var7 = new GestureDetector(this.mContext, this.simpleOnGestureListener);
this.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
if(SwipeView.this.getChildCount() > 0) {
if(SwipeView.this.mScrollDirection != SwipeView.ScrollDirection.NONE) {
return false;
} else if(!SwipeView.this.enableTouchSwipe) {
return false;
} else {
var7.onTouchEvent(event);
switch(event.getAction()) {
case 0:
if(SwipeView.this.getChildCount() > 0) {
SwipeView.this.mFocusedView = SwipeView.this.getChildAt(SwipeView.this.getChildCount() - 1);
SwipeView.this.mFocusedViewLike = SwipeView.this.mFocusedView.findViewById(SwipeView.this.mLikeResource.intValue());
SwipeView.this.mFocusedViewNope = SwipeView.this.mFocusedView.findViewById(SwipeView.this.mNopeResource.intValue());
SwipeView.this.mFocusedViewWidth = SwipeView.this.mFocusedView.getWidth();
SwipeView.this.mFocusedView.setPadding(SwipeView.this.paddingX[0], 0, SwipeView.this.paddingX[0], 0);
}
SwipeView.this.resetScrollingValues();
break;
case 1:
SwipeView.this.alignCardsPadding();
if(SwipeView.this.mScrolledPixelsX < 0) {
SwipeView.this.mScrollModeX = SwipeView.ScrollMode.LEFT;
SwipeView.this.mTotalScrolledX = -SwipeView.this.mScrolledPixelsX;
} else {
SwipeView.this.mScrollModeX = SwipeView.ScrollMode.RIGHT;
SwipeView.this.mTotalScrolledX = SwipeView.this.mScrolledPixelsX;
}
if(SwipeView.this.mScrolledPixelsY < 0) {
SwipeView.this.mScrollModeY = SwipeView.ScrollMode.BOTTOM;
SwipeView.this.mTotalScrolledY = -SwipeView.this.mScrolledPixelsY;
} else {
SwipeView.this.mScrollModeY = SwipeView.ScrollMode.TOP;
SwipeView.this.mTotalScrolledY = SwipeView.this.mScrolledPixelsY;
}
SwipeView.this.detectSwipe();
}
return true;
}
} else {
return false;
}
}
});
}
public void addCard(View view, int position) {
if(this.getChildCount() <= 3 && position < 3) {
LinearLayout viewLayout = new LinearLayout(this.mContext);
viewLayout.setLayoutParams(new LayoutParams(-1, -1));
view.setLayoutParams(new LayoutParams(-1, -1));
viewLayout.addView(view);
viewLayout.setPadding(this.paddingX[position], this.paddingYTop[position], this.paddingX[position], this.paddingYBottom[position]);
this.addView(viewLayout, 0);
}
}
public void removeFocusedCard() {
this.removeView(this.mFocusedView);
this.alignCardsPadding();
}
private void alignCardsPadding() {
int i = 0;
for(int j = this.getChildCount() - 1; j >= 0; --j) {
this.getChildAt(j).setPadding(this.paddingX[i], this.paddingYTop[i], this.paddingX[i], this.paddingYBottom[i]);
++i;
}
this.mScrollDirection = SwipeView.ScrollDirection.NONE;
}
private void resetScrollingValues() {
this.mPreviousAlpha = 0.0F;
this.mNeedToScrollX = 0;
this.mScrolledPixelsX = 0;
this.mTotalScrolledX = 0;
this.mNeedToScrollY = 0;
this.mScrolledPixelsY = 0;
this.mTotalScrolledY = 0;
this.mScrollLengthX = 5;
this.mScrollLengthY = 5;
this.mScrollModeX = SwipeView.ScrollMode.NONE;
this.mScrollModeY = SwipeView.ScrollMode.NONE;
}
public void resetFocuedView() {
if(this.getChildCount() > 0) {
View mFocusedView = this.getChildAt(this.getChildCount() - 1);
View mFocusedViewLike = mFocusedView.findViewById(this.mLikeResource.intValue());
View mFocusedViewNope = mFocusedView.findViewById(this.mNopeResource.intValue());
setAlpha(mFocusedViewLike, 0.0F, 0.0F);
setAlpha(mFocusedViewNope, 0.0F, 0.0F);
mFocusedView.scrollTo(0, 0);
}
}
private void detectSwipe() {
int imageHalf = this.mFocusedView.getWidth() / 2;
this.mNeedToScrollX = this.mFocusedView.getWidth() - this.mTotalScrolledX;
if(this.mScrollDirection == SwipeView.ScrollDirection.NONE) {
if(this.mNeedToScrollX < imageHalf) {
this.mScrollDirection = SwipeView.ScrollDirection.OUT;
} else {
this.mScrollDirection = SwipeView.ScrollDirection.IN;
setAlpha(this.mFocusedViewLike, 0.0F, 0.0F);
setAlpha(this.mFocusedViewNope, 0.0F, 0.0F);
}
}
this.mScrollHandler.post(this.mScrollRunnable);
}
public void likeCard() {
if(this.getChildCount() > 0) {
this.mFocusedView = this.getChildAt(this.getChildCount() - 1);
this.mFocusedViewLike = this.mFocusedView.findViewById(this.mLikeResource.intValue());
this.mFocusedViewNope = this.mFocusedView.findViewById(this.mNopeResource.intValue());
if(this.mScrollDirection != SwipeView.ScrollDirection.NONE) {
return;
}
this.resetScrollingValues();
this.mScrollDirection = SwipeView.ScrollDirection.OUT;
this.mScrollModeX = SwipeView.ScrollMode.LEFT;
this.mFocusedViewLike.setVisibility(0);
setAlpha(this.mFocusedViewLike, 0.0F, 1.0F);
this.detectSwipe();
}
}
public void dislikeCard() {
if(this.getChildCount() > 0) {
this.mFocusedView = this.getChildAt(this.getChildCount() - 1);
this.mFocusedViewLike = this.mFocusedView.findViewById(this.mLikeResource.intValue());
this.mFocusedViewNope = this.mFocusedView.findViewById(this.mNopeResource.intValue());
if(this.mScrollDirection != SwipeView.ScrollDirection.NONE) {
return;
}
this.resetScrollingValues();
this.mScrollDirection = SwipeView.ScrollDirection.OUT;
this.mScrollModeX = SwipeView.ScrollMode.RIGHT;
this.mFocusedViewNope.setVisibility(0);
setAlpha(this.mFocusedViewNope, 0.0F, 1.0F);
this.detectSwipe();
}
}
public void setTouchable(boolean touchable) {
this.enableTouchSwipe = touchable;
}
public static void setAlpha(View view, float fromAlpha, float toAlpha) {
if(VERSION.SDK_INT < 11) {
AlphaAnimation alphaAnimation = new AlphaAnimation(fromAlpha, toAlpha);
alphaAnimation.setDuration(0L);
alphaAnimation.setFillAfter(true);
view.startAnimation(alphaAnimation);
} else {
view.setAlpha(toAlpha);
}
}
public interface OnCardSwipedListener {
void onLikes();
void onDisLikes();
void onSingleTap();
}
private static enum ScrollDirection {
IN,
OUT,
NONE;
private ScrollDirection() {
}
}
private static enum ScrollMode {
LEFT,
RIGHT,
TOP,
BOTTOM,
NONE;
private ScrollMode() {
}
}
}
ATTEMPT #3
This is the code that i've tried but I keep getting the same result (read comment below what I have done:
FrameLayout view = (FrameLayout)findViewById(R.id.contentLayout);
view.setDrawingCacheEnabled(true);
view.buildDrawingCache();
Bitmap bitmap = view.getDrawingCache();
I believe the image you are trying to save is getting removed during the onSwipe due to the library code. I think you need to move your code to before the onLike is called.
You're also attempting to get a bitmap from the cache of the entire layout, rather than the wanted ImageView here:
bm=contentLayout.getDrawingCache();
You'll want to get your current card view as a View, then, from my understanding of your code, the ID of your actual ImageView containing the expected bitmap is R.id.imgMeals, so I the suggest replacing the line:
bm=contentLayout.getDrawingCache();
with the following:
ImageView imageView = (ImageView) cardView.findViewById(R.id.imgMeals);
BitmapDrawable drawable = (BitmapDrawable) imageView.getDrawable();
Bitmap bm = drawable.getBitmap();
Move all of the below code from where you have it, to where I have marked //HERE!! in the following part of your code (or better, move it to a new method and call the method here).
// If the imageview of like is clicked
case R.id.imgLike: {
// HERE!!
// The imageview in the contentlayout will be swiped to the right
mSwipeView.likeCard();
break;
}
This is the code to me moved including the change I mention above:
View cardView = mSwipeView.getChildAt(mSwipeView.getChildCount() - 1);
ImageView imageView = (ImageView) cardView.findViewById(R.id.imgMeals);
BitmapDrawable drawable = (BitmapDrawable) imageView.getDrawable();
Bitmap bm = drawable.getBitmap();
OutputStream fOut = null;
try {
// Save on my sd card
File root = new File(Environment.getExternalStorageDirectory()
// Making a folder name Food Inspiration
+ File.separator + "Food Inspiration" + File.separator);
root.mkdirs();
File sdImageMainDirectory = null;
// Loop for having a different name for every image
int i = 0;
do {
sdImageMainDirectory = new File(root, "pic-" + i + ".png");
i++;
} while (sdImageMainDirectory.exists());
fOut = new FileOutputStream(sdImageMainDirectory);
// Updates the gallery of your phone with the folder and the "liked" images in it
MediaScannerConnection.scanFile(this, new String[] { sdImageMainDirectory.getAbsolutePath() }, null, null);
// If something goes wrong
} catch (Exception e) {
Toast.makeText(this, "Error occured. Please try again later.",
Toast.LENGTH_SHORT).show();
}
// Compresses the actual bitmap image
try {
bm.compress(Bitmap.CompressFormat.PNG, 100, fOut);
fOut.flush();
fOut.close();
} catch (Exception e){}
Related
I made the game flappy bird on Android studio with the libgdx library and now i want to connect it to a mysql database. My point is to send the score and a name when the player dies. I've done a lot of searching so my last hope is here, thanks.
Here is my gameplay screen:
public class GameplayScreen extends ScreenAdapter {
public static final float PIPE_SPACING = 200f;
public static final int PIPE_SETS = 3;
protected OrthographicCamera camera;
protected FlappyGame game;
private Stage gameplayStage;
private Stage uiStage;
private Label scoreLabel;
private Label tapToRetry;
private Label best;
private Label tapToFlap;
private Image whitePixel;
private Image backgroundBuildings;
public int score;
private Bird bird;
private Array<PipePair> pipePairs;
private Ground ground;
private boolean justTouched;
private Color backgroundColor;
private State screenState = State.PREGAME;
private boolean allowRestart = false;
private enum State {PREGAME, PLAYING, DYING, DEAD}
;
public GameplayScreen(FlappyGame game) {
this.game = game;
camera = new OrthographicCamera(FlappyGame.WIDTH, FlappyGame.HEIGHT);
gameplayStage = new Stage(new StretchViewport(FlappyGame.WIDTH, FlappyGame.HEIGHT, camera));
uiStage = new Stage(new StretchViewport(FlappyGame.WIDTH, FlappyGame.HEIGHT));
bird = new Bird();
bird.setPosition(FlappyGame.WIDTH * .25f, FlappyGame.HEIGHT / 2, Align.center);
bird.addAction(Utils.getFloatyAction());
bird.setState(Bird.State.PREGAME);
whitePixel = new Image(Assets.whitePixel);
scoreLabel = new Label("0", new Label.LabelStyle(Assets.fontMedium, Color.WHITE));
scoreLabel.setPosition(FlappyGame.WIDTH / 2, FlappyGame.HEIGHT * .9f, Align.center);
uiStage.addActor(scoreLabel);
tapToRetry = new Label("Tap To Retry!", new Label.LabelStyle(Assets.fontMedium, Color.WHITE));
tapToRetry.setPosition(FlappyGame.WIDTH / 2, 0, Align.top);
uiStage.addActor(tapToRetry);
best = new Label("Best: ", new Label.LabelStyle(Assets.fontMedium, Color.WHITE));
best.setPosition(FlappyGame.WIDTH / 2, 0, Align.top);
uiStage.addActor(best);
tapToFlap = new Label("Tap To Flap!", new Label.LabelStyle(Assets.fontMedium, Color.WHITE));
tapToFlap.setPosition(FlappyGame.WIDTH / 2, FlappyGame.HEIGHT, Align.bottom);
uiStage.addActor(tapToFlap);
initBackgroundBuildings();
pipePairs = new Array<PipePair>();
ground = new Ground();
ground.setPosition(0, 0);
backgroundColor = Utils.getRandomBackgroundColor();
gameplayStage.addActor(ground);
gameplayStage.addActor(backgroundBuildings);
gameplayStage.addActor(bird);
initInputProcessor();
}
private void initBackgroundBuildings() {
backgroundBuildings = new Image(Assets.backgroundBuildings);
backgroundBuildings.setWidth(FlappyGame.WIDTH);
backgroundBuildings.setHeight(backgroundBuildings.getHeight()*2f);
backgroundBuildings.setY(Ground.HEIGHT);
}
#Override
public void show() {
tapToFlap.addAction(Actions.moveToAligned(FlappyGame.CENTER_X, FlappyGame.CENTER_Y + 100f, Align.center, .75f, Interpolation.sine));
Assets.playWooshSound();
}
#Override
public void render(float delta) {
Gdx.graphics.getGL20().glClearColor(backgroundColor.r, backgroundColor.g, backgroundColor.b, 1f);
Gdx.graphics.getGL20().glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT);
switch (screenState) {
case PREGAME:
updateAndDrawStages();
break;
case PLAYING:
renderPlaying();
break;
case DYING:
case DEAD:
renderDeadOrDying();
break;
}
}
private void renderDeadOrDying() {
if (bird.getState() == Bird.State.DEAD) {
screenState = State.DEAD;
}
updateAndDrawStages();
}
private void renderPlaying() {
if (justTouched) {
bird.jump();
justTouched = false;
}
updatePipePairs();
gameplayStage.act();
uiStage.act();
checkCollisions();
if (bird.getState() == Bird.State.DYING) {
stopTheWorld();
RunnableAction playWooshAction = Actions.run(new Runnable() {
#Override
public void run() {
Assets.playWooshSound();
}
});
SequenceAction actions = Actions.sequence(Actions.delay(1f), playWooshAction, Actions.moveToAligned(FlappyGame.CENTER_X, FlappyGame.CENTER_Y, Align.bottom,
.75f, Interpolation.sine), Actions.run(new Runnable() {
#Override
public void run() {
allowRestart = true;
}
}));
tapToRetry.addAction(actions);
best.setText("Best: " + SavedDataManager.getInstance().getHighScore());
best.setPosition(FlappyGame.CENTER_X, 0, Align.top);
best.addAction(Actions.delay(1f, Actions.moveToAligned(FlappyGame.CENTER_X, FlappyGame.CENTER_Y, Align.top,
.75f, Interpolation.sine)));
screenState = State.DYING;
}
gameplayStage.draw();
uiStage.draw();
}
private void updateAndDrawStages() {
gameplayStage.act();
gameplayStage.draw();
uiStage.act();
uiStage.draw();
}
#Override
public void resize(int width, int height) {
camera.setToOrtho(false, width, height);
Assets.batch.setProjectionMatrix(camera.combined);
gameplayStage.getViewport().update(width, height, true);
uiStage.getViewport().update(width, height, true);
}
#Override
public void dispose() {
gameplayStage.dispose();
uiStage.dispose();
}
private void checkCollisions() {
for (int i = 0; i < pipePairs.size; i++) {
PipePair pair = pipePairs.get(i);
if (pair.getBottomPipe().getBounds().overlaps(bird.getBounds()) || pair.getTopPipe().getBounds().overlaps(bird.getBounds())) {
stopTheWorld();
SavedDataManager.getInstance().setHighScore(score);
showWhiteScreen();
} else if (bird.isBelowGround()) {
bird.setY(FlappyGame.GROUND_LEVEL);
bird.clearActions();
bird.setToDying();
showWhiteScreen();
} else if (bird.isAboveCeiling()) {
bird.setY(FlappyGame.HEIGHT - bird.getHeight());
bird.setToDying();
showWhiteScreen();
} else if (pair.getRuby().getBounds().overlaps(bird.getBounds())) {
score++;
updateScoreLabel();
pair.moveCoinOffscreen();
Assets.playBingSound();
}
}
}
private void showWhiteScreen() {
whitePixel.setWidth(FlappyGame.WIDTH);
whitePixel.setHeight(FlappyGame.HEIGHT);
gameplayStage.addActor(whitePixel);
whitePixel.addAction(Actions.fadeOut(.5f));
}
private void updateScoreLabel() {
scoreLabel.setText(String.valueOf(score));
scoreLabel.setPosition(FlappyGame.WIDTH / 2, FlappyGame.HEIGHT * .9f, Align.center);
}
private void stopTheWorld() {
bird.setToDying();
killPipePairs();
stopTheGround();
screenState = State.DYING;
}
private void stopTheGround() {
ground.vel.x = 0;
}
private void killPipePairs() {
for (PipePair pair : pipePairs) {
pair.getBottomPipe().setState(Pipe.State.dead);
pair.getTopPipe().setState(Pipe.State.dead);
pair.getRuby().setVel(0, 0);
}
}
private void updatePipePairs() {
for (int i = 0; i < pipePairs.size; i++) {
pipePairs.get(i).update();
}
}
private void addPipes(Stage gameplayStage) {
for (int i = 0; i < pipePairs.size; i++) {
gameplayStage.addActor(pipePairs.get(i).getBottomPipe());
gameplayStage.addActor(pipePairs.get(i).getTopPipe());
gameplayStage.addActor(pipePairs.get(i).getRuby());
}
}
private void initThirdSetOfPipes() {
Pipe topPipe = new Pipe();
Pipe bottomPipe = new Pipe();
topPipe.getRegion().flip(false, true);
PipePair pair = new PipePair(topPipe, bottomPipe);
pair.initThird();
pipePairs.add(pair);
}
private void initSecondSetOfPipes() {
Pipe topPipe = new Pipe();
Pipe bottomPipe = new Pipe();
topPipe.getRegion().flip(false, true);
PipePair pair = new PipePair(topPipe, bottomPipe);
pair.initSecond();
pipePairs.add(pair);
}
private void initFirstSetOfPipes() {
Pipe topPipe = new Pipe();
Pipe bottomPipe = new Pipe();
topPipe.getRegion().flip(false, true);
PipePair pair = new PipePair(topPipe, bottomPipe);
pair.initFirst();
pipePairs.add(pair);
}
private void initInputProcessor() {
Gdx.input.setInputProcessor(new InputAdapter() {
// We only care about the touch down event
#Override
public boolean touchDown(int screenX, int screenY, int pointer, int button) {
switch (screenState) {
case DYING:
justTouched = true;
break;
case DEAD:
if (allowRestart) {
game.setScreen(new GameplayScreen(game));
}
justTouched = true;
break;
case PLAYING:
justTouched = true;
break;
case PREGAME:
justTouched = true;
screenState = State.PLAYING;
bird.setState(Bird.State.ALIVE);
bird.clearActions();
tapToFlap.addAction(Actions.moveToAligned(FlappyGame.CENTER_X, FlappyGame.HEIGHT, Align.bottom, .75f, Interpolation.sine));
initFirstSetOfPipes();
initSecondSetOfPipes();
initThirdSetOfPipes();
addPipes(gameplayStage);
gameplayStage.addActor(ground);
gameplayStage.addActor(bird);
break;
}
return true;
}
});
}
}
You can connect to your Mysql server with Java JDBC. But it means you have to write your Mysql server username and password in your program. It's not safe.
I am trying to add a feature like or dislike to my post(Question). But it is not updating the like button image.
public class QuestionDetailActivity extends AppCompatActivity implements View.OnClickListener {
private static final String TAG = "QuestionDetailActivity";
private Context mContext;
private TextView questionTitleTv;
private RadioGroup radioLL;
private EditText answerEt;
private LinearLayout checkboxLL;
private LinearLayout commentLL;
private FirebaseFirestore db = null;
private String questionID;
private String userID;
private TextView likeCountTv,favouriteCountTv;
private boolean isLikedByUser = false,isFavouriteByUser = false;
private DocumentReference questionRef;
private QuestionBO questionBO;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_question_detail);
mContext = QuestionDetailActivity.this;
db = FirebaseFirestore.getInstance();
userID = "V5BUeBFYR8WKOQUiBFxKrfMHK8Y2";
questionTitleTv = findViewById(R.id.tv_question_title);
radioLL = findViewById(R.id.ll_radio);
answerEt = findViewById(R.id.et_answer);
checkboxLL = findViewById(R.id.ll_checkbox);
commentLL = findViewById(R.id.ll_comments);
likeCountTv = findViewById(R.id.tv_like_count);
favouriteCountTv = findViewById(R.id.tv_favourite_count);
likeCountTv.setOnClickListener(this);
favouriteCountTv.setOnClickListener(this);
if (getIntent() != null) {
questionID = getIntent().getExtras().getString("keyQuestionID", "");
}
questionRef = db.collection("questionCollection").document(questionID);
if (!questionID.isEmpty()) {
getQuestionDetail();
///showComments();
updateFavouriteAndLikeIcons();
}
}
private void updateFavouriteAndLikeIcons() {
questionRef.collection("favouriteCollection").document(userID).get()
.addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
#Override
public void onSuccess(DocumentSnapshot documentSnapshot) {
if(documentSnapshot.exists()){
isFavouriteByUser = true;
// and make it blue
Drawable image = getResources().getDrawable( R.drawable.icn_fav_yes );
int h = image.getIntrinsicHeight();
int w = image.getIntrinsicWidth();
image.setBounds( 0, 0, w, h );
favouriteCountTv.setCompoundDrawables( image, null, null, null );
}
}
});
questionRef.collection("likeCollection").document(userID).get()
.addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
#Override
public void onSuccess(DocumentSnapshot documentSnapshot) {
if(documentSnapshot.exists()){
boolean isLiked = documentSnapshot.getBoolean(userID);
if(isLiked){
isLikedByUser = true;
// and make it blue
Drawable image = getResources().getDrawable( R.drawable.icn_like_yes );
int h = image.getIntrinsicHeight();
int w = image.getIntrinsicWidth();
image.setBounds( 0, 0, w, h );
likeCountTv.setCompoundDrawables( image, null, null, null );
}
else{//dislike
}
}
}
});
}
private void showComments() {
db.collection("commentCollection").whereEqualTo("questionID", questionID)
.get()
.addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
#Override
public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
if (queryDocumentSnapshots.isEmpty()) {
Log.d(TAG, "onSuccess: LIST EMPTY");
return;
} else {
// Convert the whole Query Snapshot to a list
// of objects directly! No need to fetch each
// document.
List<CommentBO> commentList = queryDocumentSnapshots.toObjects(CommentBO.class);
if (commentList != null && commentList.size() > 0) {
for (int x = 0; x < commentList.size(); x++) {
try {
LinearLayout.LayoutParams childParam = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
childParam.setMargins(20, 10, 0, 0);
View commentByView = LayoutInflater.from(mContext).inflate(R.layout.item_comment, null);
TextView tvCommenter = (TextView) commentByView.findViewById(R.id.item_tv_commenter_name);
TextView tvCommenterComment = (TextView) commentByView.findViewById(R.id.item_tv_commenter_comment);
TextView tvCommentDate = (TextView) commentByView.findViewById(R.id.item_tv_comment_date);
tvCommenter.setText(commentList.get(x).getCommentedBy());
tvCommenterComment.setText(commentList.get(x).getComment());
///tvCommentDate.setText();
commentLL.addView(commentByView, childParam);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
});
}
private void getQuestionDetail() {
questionRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
#Override
public void onComplete(#NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()) {
DocumentSnapshot document = task.getResult();
if (document.exists()) {
Log.d(TAG, "DocumentSnapshot data: " + document.getData());
questionBO = document.toObject(QuestionBO.class);
updateView(questionBO);
} else {
Log.d(TAG, "No such document");
}
} else {
Log.d(TAG, "get failed with ", task.getException());
}
}
});
}
private void updateView(QuestionBO mQuestionBO) {
if (mQuestionBO != null) {
questionTitleTv.setText(mQuestionBO.getTitle());
likeCountTv.setText(mQuestionBO.getTotalLikes() + "");
favouriteCountTv.setText(mQuestionBO.getTotalFavourites() + "");
switch (mQuestionBO.getQuestionType()) {
case CHECKBOX:
checkboxLL.setVisibility(View.VISIBLE);
if (mQuestionBO.getOptions() != null && mQuestionBO.getOptions().size() > 0) {
checkboxLL.removeAllViews();
for (int x = 0; x < mQuestionBO.getOptions().size(); x++) {
final CheckBox subCheckbox = new CheckBox(mContext);
subCheckbox.setText(mQuestionBO.getOptions().get(x));
subCheckbox.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
checkboxLL.addView(subCheckbox, new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
}
}
break;
case RADIO:
radioLL.setVisibility(View.VISIBLE);
if (mQuestionBO.getOptions() != null && mQuestionBO.getOptions().size() > 0) {
radioLL.removeAllViews();
for (int x = 0; x < mQuestionBO.getOptions().size(); x++) {
final RadioButton subRadio = new RadioButton(mContext);
subRadio.setText(mQuestionBO.getOptions().get(x));
radioLL.addView(subRadio, new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
}
}
break;
case DESCRIPTIVE:
answerEt.setVisibility(View.VISIBLE);
break;
}
}
}
private void likeOrDislikeThisQuestion(){
final Task<Boolean> booleanTask = db.runTransaction(new Transaction.Function<Boolean>() {
#Nullable
#Override
public Boolean apply(#NonNull Transaction transaction) throws FirebaseFirestoreException {
DocumentReference likeRef = questionRef.collection("likeCollection")
.document(userID);
Map<String,Object> map = new HashMap<>();
DocumentSnapshot snapshot = transaction.get(likeRef);
if(snapshot.exists()){ // it means this is a favourite question of this user.
if(snapshot.getBoolean(questionID) && isLikedByUser){
isLikedByUser = false;
map.put(questionID,isLikedByUser);
transaction.update(likeRef,map);
int numberOfLikes = questionBO.getTotalLikes();
transaction.update(questionRef,"totalLikes",--numberOfLikes);
likeCountTv.setText(numberOfLikes + "");
return isLikedByUser;
}
else if(!snapshot.getBoolean(questionID) && !isLikedByUser){
isLikedByUser = true;
map.put(questionID,isLikedByUser);
transaction.update(likeRef,map);
int numberOfLikes = questionBO.getTotalLikes();
transaction.update(questionRef,"totalLikes",-++numberOfLikes);
likeCountTv.setText(numberOfLikes + "");
return isLikedByUser;
}
}
else {
isLikedByUser = !isLikedByUser;
map.put(questionID,isLikedByUser);// pass oposite of it..
transaction.set(likeRef,map);
int numberOfLikes = questionBO.getTotalLikes();
if(isLikedByUser)
++numberOfLikes;
else
--numberOfLikes;
transaction.update(questionRef,"totalLikes",numberOfLikes);
likeCountTv.setText(numberOfLikes + "");
return isLikedByUser;
}
return null;
}
});
booleanTask.addOnSuccessListener(new OnSuccessListener<Boolean>() {
#Override
public void onSuccess(Boolean isLiked) {
if(isLiked == null){
}
else if(isLiked){
Drawable image = getResources().getDrawable( R.drawable.icn_like_yes );
int h = image.getIntrinsicHeight();
int w = image.getIntrinsicWidth();
image.setBounds( 0, 0, w, h );
likeCountTv.setCompoundDrawables( image, null, null, null );
}
else{
Drawable image = getResources().getDrawable( R.drawable.icn_like_no );
int h = image.getIntrinsicHeight();
int w = image.getIntrinsicWidth();
image.setBounds( 0, 0, w, h );
likeCountTv.setCompoundDrawables( image, null, null, null );
}
}
});
}
private void favouriteOrDisFavouriteQuestion(){
}
#Override
public void onClick(View view) {
switch (view.getId()){
case R.id.tv_like_count:
likeOrDislikeThisQuestion();
break;
case R.id.tv_favourite_count:
break;
}
}
}
I updated icon using updateFavouriteAndLikeIcons() for the first time. then when user clicks on like button I called likeOrDislikeThisQuestion() . Counter updating but left drawable not updating. and sometimes variable isLikedByUser become false .
If the question is already liked then likeCollection must have that Document. if that document don't exist it means User didn't like or dislike it.
My architecture of db is like
- likeCollection
userID (Document ID)
questionID = true // true for like and false for dislike..
From Firebase docs :
Do not modify application state inside of your transaction functions. Doing so will introduce concurrency issues, because transaction functions can run multiple times and are not guaranteed to run on the UI thread. Instead, pass information you need out of your transaction functions.
This is what happens here, you have to run every application modifications inside a listener on your variable booleanTask. Do not change class variable in the transaction's apply method.
I have pdf reader with listview with icon pdf
and how to make cover pdf show in listview like this?
or
source code: https://deepshikhapuri.wordpress.com/2017/04/24/open-pdf-file-from-sdcard-in-android-programmatically/
How to change pdf icon to cover pdf in listview?
thanks
Main Activity.java
ListView lv_pdf;
public static ArrayList<File> fileList = new ArrayList<File>();
PDFAdapter obj_adapter;
public static int REQUEST_PERMISSIONS = 1;
boolean boolean_permission;
File dir;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
}
private void init() {
lv_pdf = (ListView) findViewById(R.id.lv_pdf);
dir = new File(Environment.getExternalStorageDirectory().getAbsolutePath(),"Pdf");
fn_permission();
lv_pdf.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int i, long l) {
Intent intent = new Intent(getApplicationContext(), PdfActivity.class);
intent.putExtra("position", i);
startActivity(intent);
Log.e("Position", i + "Pdf");
}
});
}
public static ArrayList<File> getfile(File dir) {
File listFile[] = dir.listFiles();
if (listFile != null && listFile.length > 0) {
for (int i = 0; i < listFile.length; i++) {
if (listFile[i].isDirectory()) {
getfile(listFile[i]);
} else {
boolean booleanpdf = false;
if (listFile[i].getName().endsWith(".pdf")) {
for (int j = 0; j < fileList.size(); j++) {
if (fileList.get(j).getName().equals(listFile[i].getName())) {
booleanpdf = true;
} else {
}
}
if (booleanpdf) {
booleanpdf = false;
} else {
fileList.add(listFile[i]);
}
}
}
}
}
return fileList;
}
private void fn_permission() {
if ((ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)) {
if ((ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, android.Manifest.permission.READ_EXTERNAL_STORAGE))) {
} else {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{android.Manifest.permission.READ_EXTERNAL_STORAGE},
REQUEST_PERMISSIONS);
}
} else {
boolean_permission = true;
getfile(dir);
obj_adapter = new PDFAdapter(getApplicationContext(), fileList);
lv_pdf.setAdapter(obj_adapter);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == REQUEST_PERMISSIONS) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
boolean_permission = true;
getfile(dir);
obj_adapter = new PDFAdapter(getApplicationContext(), fileList);
lv_pdf.setAdapter(obj_adapter);
} else {
Toast.makeText(getApplicationContext(), "Please allow the permission", Toast.LENGTH_LONG).show();
}
}
}
PdfActivity
public static final String SAMPLE_FILE = "android_tutorial.pdf";
PDFView pdfView;
Integer pageNumber = 0;
String pdfFileName;
String TAG = "PdfActivity";
int position = -1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pdf);
init();
}
private void init() {
pdfView = (PDFView) findViewById(R.id.pdfView);
//position = Environment.getExternalStorageDirectory()+"/sdcard/Pdf"
position = getIntent().getIntExtra("position", -1);
displayFromSdcard();
//String position = Environment.getExternalStorageDirectory().getAbsolutePath() +"/Pdf/";
}
private void displayFromSdcard() {
pdfFileName = MainActivity.fileList.get(position).getName();
pdfView.fromFile(MainActivity.fileList.get(position))
.defaultPage(pageNumber)
.enableSwipe(true)
.password("123456")
.swipeHorizontal(false)
.onPageChange(this)
.enableAnnotationRendering(true)
.onLoad(this)
.scrollHandle(new DefaultScrollHandle(this))
.load();
}
#Override
public void onPageChanged(int page, int pageCount) {
pageNumber = page;
setTitle(String.format("%s %s / %s", pdfFileName, page + 1, pageCount));
}
#Override
public void loadComplete(int nbPages) {
PdfDocument.Meta meta = pdfView.getDocumentMeta();
printBookmarksTree(pdfView.getTableOfContents(), "-");
}
public void printBookmarksTree(List<PdfDocument.Bookmark> tree, String sep) {
for (PdfDocument.Bookmark b : tree) {
Log.e(TAG, String.format("%s %s, p %d", sep, b.getTitle(), b.getPageIdx()));
if (b.hasChildren()) {
printBookmarksTree(b.getChildren(), sep + "-");
}
}
}
PdfAdapter
Context context;
ViewHolder viewHolder;
ArrayList<File> al_pdf;
public PDFAdapter(Context context, ArrayList<File> al_pdf) {
super(context, R.layout.adapter_pdf, al_pdf);
this.context = context;
this.al_pdf = al_pdf;
}
#Override
public int getItemViewType(int position) {
return position;
}
#Override
public int getViewTypeCount() {
if (al_pdf.size() > 0) {
return al_pdf.size();
} else {
return 1;
}
}
#Override
public View getView(final int position, View view, ViewGroup parent) {
if (view == null) {
view = LayoutInflater.from(getContext()).inflate(R.layout.adapter_pdf, parent, false);
viewHolder = new ViewHolder();
viewHolder.tv_filename = (TextView) view.findViewById(R.id.tv_name);
view.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) view.getTag();
}
viewHolder.tv_filename.setText(al_pdf.get(position).getName());
return view;
}
public class ViewHolder {
TextView tv_filename;
}
You can create the image by creating the bitmap of pdf first page. Then save the image to your app directory to be used later. You can use PdfiumCore (which is dependency of barteks PdfView) to generate the image.
You can use the following:
import android.content.Context;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.ParcelFileDescriptor;
import com.shockwave.pdfium.PdfDocument;
import com.shockwave.pdfium.PdfiumCore;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
class PDFUtils {
static String generateAndSaveFirstPageImage(Context context, Uri uri, long bookId) {
try {
ParcelFileDescriptor fd = context.getContentResolver().openFileDescriptor(uri, "r");
int pageNum = 0;
PdfiumCore pdfiumCore = new PdfiumCore(context);
try {
PdfDocument pdfDocument = pdfiumCore.newDocument(fd);
pdfiumCore.openPage(pdfDocument, 0); // open first page for cover.
int width = pdfiumCore.getPageWidthPoint(pdfDocument, pageNum);
int height = pdfiumCore.getPageHeightPoint(pdfDocument, pageNum);
// do a fit center to 1920x1080
//double scaleBy = Math.min(1080 / (double) width, //
// 1920 / (double) height);
//width = (int) (width * scaleBy);
//height = (int) (height * scaleBy);
// ARGB_8888 - best quality, high memory usage, higher possibility of OutOfMemoryError
// RGB_565 - little worse quality, twice less memory usage
Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
pdfiumCore.renderPageBitmap(pdfDocument, bitmap, pageNum, 0, 0, width, height);
//if you need to render annotations and form fields, you can use
//the same method above adding 'true' as last param
String fileName = bookId + ".jpg";
// save the file
File outputFile = new File(context.getFilesDir(), fileName);
FileOutputStream outputStream = new FileOutputStream(outputFile);
// a bit long running
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
outputStream.close();
fd.close();
pdfiumCore.closeDocument(pdfDocument); // important!
return fileName;
} catch (FileNotFoundException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
Then, you need to use the class by using the following:
long bookId = 2345; // your book identifier
Url yourPdfUrl; // url of pdf in your device
PdfUtils.generateAndSaveFirstPageImage(context, yourPdfUrl, bookId);
After you have saved the image, you can use the image again with something like this:
String imagePath = getFilesDir() + "/" + yourBookId + ".jpg";
I need to add a progress listener to each element of the horizontal list view, how can I do that?
For each item I upload a file.
I wanna to do something like that but holder is not final, so I have an error.
public class UploadsViewAdapter extends BaseAdapter {
private Context mContext;
private int mLayoutResourceId;
List<Upload> listFileToUpload;
public UploadsViewAdapter(Context context, int layoutResourceId, List<Upload> data) {
this.mLayoutResourceId = layoutResourceId;
this.mContext = context;
this.listFileToUpload = data;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
ViewHolder holder = null;
if (row == null) {
LayoutInflater inflater = ((Activity) mContext).getLayoutInflater();
row = inflater.inflate(mLayoutResourceId, parent, false);
holder = new ViewHolder();
holder.image = (ImageView) row.findViewById(R.id.upload_item_image);
holder.progressUpdate = (ProgressBar) row.findViewById(R.id.progressUpdate);
row.setTag(holder);
} else {
holder = (ViewHolder) row.getTag();
}
final Upload item = getItem(position);
holder.image.setImageBitmap(item.getThumbnail(160, 160));
item.setProgressListener(new ProgressListener() {
#Override
public void onProgress(int progress) {
holder.progressUpdate.setProgress(item.getProgress());
}
});
holder.progressUpdate.setProgress(item.getProgress());
return row;
}
static class ViewHolder {
ImageView image;
ProgressBar progressUpdate;
}
public void updateListFileToUpdate(List<Upload> listFileToUpload) {
this.listFileToUpload = listFileToUpload;
}
#Override
public int getCount() {
return listFileToUpload.size();
}
#Override
public Upload getItem(int location) {
return listFileToUpload.get(location);
}
#Override
public long getItemId(int position) {
return 0;
}
}
Class Update.java
public class Upload {
public String path;
public String type;
private int mProgress = 0;
private ProgressListener mListener;
public Upload(String path, String type) {
this.path = path;
this.type = type;
}
public void setProgressListener(ProgressListener listener) {
mListener = listener;
}
public void setProgress(int progress) {
mProgress = progress;
if (mListener != null) {
mListener.onProgress(progress);
}
}
public int getProgress() {
return mProgress;
}
public Bitmap getThumbnail(int reqWidth, int reqHeight) {
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(path, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeFile(path, options);
}
private int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
final int halfHeight = height / 2;
final int halfWidth = width / 2;
// Calculate the largest inSampleSize value that is a power of 2 and keeps both
// height and width larger than the requested height and width.
while (
(halfHeight / inSampleSize) > reqHeight &&
(halfWidth / inSampleSize) > reqWidth
) {
inSampleSize *= 2;
}
}
return inSampleSize;
}
public interface ProgressListener {
public void onProgress(int progress);
}
}
Class which updates the file:
public class TheFormFragment extends Fragment {
private AmazonS3Client mS3Client = new AmazonS3Client(
new BasicAWSCredentials(Config.AWS_ACCESS_KEY, Config.AWS_SECRET_KEY));
public static final int RESULT_PHOTO_DISK = 10;
public static final int RESULT_PHOTO_APN = 100;
public static final int RESULT_VIDEO_APN = 1000;
public static final String INTENT_PHOTO_APN_PATH = "INTENT_PHOTO_APN_PATH";
public static final String INTENT_VIDEO_APN_PATH = "INTENT_VIDEO_APN_PATH";
private List<Medias> mTheFormPictures;
private static Activity mActivity;
private static ArrayList<Upload> mQueue;
private KeyboardEventLinearLayout mLinearLayoutBackground;
private LinearLayout mLinearLayoutPublish;
private TextView mTextViewPublish;
private ImageView mImageViewPublish; // todo image du bouton
private EditText mEditTextText;
private TextView mTextViewTitle;
private CircularImageView mCircularImageViewAvatar;
private ImageButton mImageButtonClose;
private ImageButton mImageButtonCamera;
private ImageButton mImageButtonLibrary;
private Tag[] mTags = null;
private Range mAutocompleting;
private LinearLayout mAutocompleteContainer;
private HorizontalListView mUploadsList;
private UploadsViewAdapter mUploading;
/**Contains list of images, vidoe to update*/
private List<Upload> listFileToUpload;
private KeyboardEventLinearLayout.KeyboardListener mKeyboardListener = new KeyboardEventLinearLayout.KeyboardListener() {
#Override
public void onShow() {
if (mUploadsList != null) {
mUploadsList.setVisibility(View.GONE);
}
}
#Override
public void onHide() {
if (mUploadsList != null) {
mUploadsList.setVisibility(View.VISIBLE);
}
}
};
private class Range {
public int start;
public int end;
public String value;
public Range(int start, int end, String value) {
this.start = start;
this.end = end;
this.value = value;
}
}
private TextWatcher textWatcher = new TextWatcher() {
#Override
public void onTextChanged(CharSequence text, int start, int oldCount, int newCount) {
String before = text.subSequence(0, start + newCount).toString();
Range range = findEditingTag(before);
autocompete(range);
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
#Override
public void afterTextChanged(Editable s) {}
};
private OnClickListener mAutocompleteItemClickListener = new OnClickListener() {
#Override
public void onClick(View view) {
Editable text = mEditTextText.getText();
CharSequence tag = ((TextView) view).getText();
text.replace(mAutocompleting.start, mAutocompleting.end, tag);
}
};
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
mActivity = activity;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_the_form, container, false);
return rootView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
mTheFormPictures = new ArrayList<Medias>();
mQueue = new ArrayList<Upload>();
mS3Client.setRegion(Region.getRegion(Config.AWS_REGION));
mLinearLayoutBackground = (KeyboardEventLinearLayout) mActivity.findViewById(R.id.linearLayoutBackground);
mLinearLayoutPublish = (LinearLayout) mActivity.findViewById(R.id.linearLayoutPublish);
mTextViewPublish = (TextView) mActivity.findViewById(R.id.textViewPublish);
mTextViewTitle = (TextView) mActivity.findViewById(R.id.textViewTitle);
mImageViewPublish = (ImageView) mActivity.findViewById(R.id.imageViewPublish);
mCircularImageViewAvatar = (CircularImageView) mActivity.findViewById(R.id.circularImageViewAvatar);
mEditTextText = (EditText) mActivity.findViewById(R.id.editTextText);
mImageButtonClose = (ImageButton) mActivity.findViewById(R.id.imageButtonClose);
mImageButtonCamera = (ImageButton) mActivity.findViewById(R.id.imageButtonCamera);
mImageButtonLibrary = (ImageButton) mActivity.findViewById(R.id.imageButtonLibrary);
mAutocompleteContainer = (LinearLayout) mActivity.findViewById(R.id.autocompleteLayout);
mUploadsList = (HorizontalListView) mActivity.findViewById(R.id.uploadsList);
listFileToUpload =new ArrayList<Upload>();
mUploading = new UploadsViewAdapter(mActivity, R.layout.upload_item, listFileToUpload);
mUploadsList.setAdapter(mUploading);
mLinearLayoutBackground.setKeyboardListener(mKeyboardListener);
configure();
super.onActivityCreated(savedInstanceState);
}
#SuppressLint("NewApi")
#SuppressWarnings("deprecation")
private void configure() {
AQuery aq = new AQuery(mActivity);
ImageOptions options = new ImageOptions();
//options.round = 180;
options.fileCache = false;
options.memCache = true;
//options.animation = AQuery.FADE_IN;
User user = Preferences.getUser(mActivity);
if (user != null) {
mTextViewTitle.setText(user.getFirst_name() + " " + user.getLast_name());
if (user.getAvatar() != null && user.getAvatar().length() > 0) {
aq.id(mCircularImageViewAvatar).image(user.getAvatar(), options);
}
}
StatusConfigTheForm configTheForm = Preferences.getConfigTheForm(mActivity);
if (configTheForm != null) {
Log.i("theform config success");
Log.d("avatar: " + user.getAvatar() + " " + configTheForm.getBorderWidth());
if (configTheForm.getColors().getBackground().length == 3) {
mLinearLayoutBackground.setBackgroundColor(Color.parseColor(Utils.getHexaColor(configTheForm.getColors().getBackground())));
}
if (configTheForm.getColors().getBackgrounPublishButton().length == 3) {
// mButtonPublish.setBackgroundColor(Color.parseColor(Utils.getHexaColor(configTheForm.getColors().getBackgrounPublishButton())));
// prepare
int roundRadius = 6;
// normal state
GradientDrawable background_normal = new GradientDrawable();
background_normal.setColor(Color.parseColor(Utils.getHexaColor(configTheForm.getColors().getBackgrounPublishButton())));
background_normal.setCornerRadius(roundRadius);
// pressed state
GradientDrawable bacground_pressed = new GradientDrawable();
bacground_pressed.setColor(Color.parseColor(Utils.getHexaColor(configTheForm.getColors().getBackgrounPublishButton()).replace("#", "#CC"))); // opacity
bacground_pressed.setCornerRadius(roundRadius);
// states (normal and pressed)
StateListDrawable states = new StateListDrawable();
states.addState(new int[] {android.R.attr.state_pressed}, bacground_pressed);
states.addState(new int[] {-android.R.attr.state_pressed}, background_normal);
if (Build.VERSION.SDK_INT >= 16) {
mLinearLayoutPublish.setBackground(states);
} else {
mLinearLayoutPublish.setBackgroundDrawable(states);
}
}
if (configTheForm.getColors().getBackgroundTextView().length == 3) {
mEditTextText.setBackgroundColor(Color.parseColor(Utils.getHexaColor(configTheForm.getColors().getBackgroundTextView())));
}
if (configTheForm.getColors().getBorderColorPicture().length == 3) {
mCircularImageViewAvatar.setBorderColor(Utils.getHexaColor(configTheForm.getColors().getBorderColorPicture()));
}
// add color tag here
if (configTheForm.getColors().getColorTextPublish().length == 3) {
mTextViewPublish.setTextColor(Color.parseColor(Utils.getHexaColor(configTheForm.getColors().getColorTextPublish())));
}
if (configTheForm.getColors().getColorTextAttachment().length == 3) {
mCircularImageViewAvatar.setBorderColor(Utils.getHexaColor(configTheForm.getColors().getColorTextAttachment()));
}
if (configTheForm.getColors().getColorTextUser().length == 3) {
mTextViewTitle.setTextColor(Color.parseColor(Utils.getHexaColor(configTheForm.getColors().getColorTextUser())));
}
if (configTheForm.getBorderWidth() > 0) {
mCircularImageViewAvatar.setBorderWidth(configTheForm.getBorderWidth() * Integer.valueOf(Float.valueOf(getResources().getDisplayMetrics().density).intValue()));
}
// pictures
if (configTheForm.getPictures() != null) {
String baseUrl = configTheForm.getUrlPicto() + configTheForm.getFolder() + File.separator;
String ext = Utils.setExtension(mActivity, Config.PICTURE_EXTENSION);
Pictures pics = configTheForm.getPictures();
if (configTheForm.getPictures().getPictureBack() != null) {
aq.id(mImageButtonClose).image(baseUrl + pics.getPictureBack() + ext, options);
}
if (configTheForm.getPictures().getPictureCamera() != null) {
aq.id(mImageButtonCamera).image(baseUrl + pics.getPictureCamera() + ext, options);
}
if (configTheForm.getPictures().getPictureLibrary() != null) {
aq.id(mImageButtonLibrary).image(baseUrl + pics.getPictureLibrary() + ext, options);
}
if (configTheForm.getPictures().getPicturePublish() != null) {
mImageViewPublish.setVisibility(View.VISIBLE);
aq.id(mImageViewPublish).image(baseUrl + pics.getPicturePublish() + ext, options);
} else {
mImageViewPublish.setVisibility(View.GONE);
}
}
}
mEditTextText.addTextChangedListener(textWatcher);
}
private Range findEditingTag(String text) {
Pattern pattern = Pattern.compile("#[A-z0-9_]+$");
Matcher match = pattern.matcher(text);
if (match.find()) {
String value = text.substring(match.start());
return new Range(match.start(), match.end(), value);
}
return null;
}
private void autocompete(Range range) {
mAutocompleting = range;
mAutocompleteContainer.removeAllViews();
if (range != null && mTags != null) {
String tag;
for (int i = 0; i < mTags.length; i++) {
tag = "#" + mTags[i].getName();
if (tag.startsWith(range.value) && tag.equals(range.value) == false) {
addAutocompleteItem(tag);
}
}
}
}
#SuppressWarnings("deprecation")
#SuppressLint("NewApi")
private void addAutocompleteItem(String text) {
Drawable background = mActivity.getResources().getDrawable(R.drawable.autocomplete_item);
int textColor = mActivity.getResources().getColor(R.color.autocomplete_item_text);
TextView view = new TextView(mActivity);
view.setText(text);
view.setTextColor(textColor);
view.setPadding(20, 10, 20, 10);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
params.setMargins(10, 0, 10, 0);
view.setLayoutParams(params);
if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.JELLY_BEAN) {
view.setBackgroundDrawable(background);
} else {
view.setBackground(background);
}
view.setClickable(true);
view.setOnClickListener(mAutocompleteItemClickListener);
mAutocompleteContainer.addView(view);
}
private void updateProgress() {
//int progress = 0;
//for (Upload file: mUploading) {
// progress += file.getProgress();
//}
//progress /= mUploading.size();
//mProgressBarFile.setProgress(progress);
//mTextViewFileProgress.setText(String.format(getString(R.string.theform_text_file_progress), Integer.valueOf(progress).toString()));
}
private class S3PutObjectTask extends AsyncTask<Upload, Integer, S3TaskResult> {
//private Dialog progressDialog;
ObjectMetadata mMetadata = new ObjectMetadata();
private String mS3Filename;
private Upload mFile;
#Override
protected void onPreExecute() {
updateProgress();
}
#Override
protected void onProgressUpdate(Integer... values) {
int progress = Integer.valueOf( (int) ((values[0] * 100) / mMetadata.getContentLength()) );
mFile.setProgress(progress);
updateProgress();
super.onProgressUpdate(values);
}
protected S3TaskResult doInBackground(Upload... files) {
if (files == null || files.length != 1 || files[0] == null) {
return null;
} else {
mFile = files[0];
}
ContentResolver resolver = mActivity.getContentResolver();
// The file location of the image selected.
Uri selectedSource = Uri.parse(mFile.path);
if (mFile.type.equals("image")) {
String size = null;
String fileSizeColumn[] = { OpenableColumns.SIZE };
Cursor cursor = resolver.query(selectedSource, fileSizeColumn, null, null, null);
if (cursor != null && cursor.getCount() > 0) {
cursor.moveToFirst();
int sizeIndex = cursor.getColumnIndex(OpenableColumns.SIZE);
// If the size is unknown, the value stored is null. But since an int can't be
// null in java, the behavior is implementation-specific, which is just a fancy
// term for "unpredictable". So as a rule, check if it's null before assigning
// to an int. This will happen often: The storage API allows for remote
// files, whose size might not be locally known.
if (!cursor.isNull(sizeIndex)) {
// Technically the column stores an int, but cursor.getString will do the
// conversion automatically.
size = cursor.getString(sizeIndex);
}
cursor.close();
}
mMetadata.setContentType(resolver.getType(selectedSource));
if (size != null) {
mMetadata.setContentLength(Long.parseLong(size));
}
}
if (mMetadata.getContentType() == null) {
BitmapFactory.Options opt = new BitmapFactory.Options();
opt.inJustDecodeBounds = true;
BitmapFactory.decodeFile(selectedSource.toString(), opt);
mMetadata.setContentType(opt.outMimeType);
}
if (mMetadata.getContentLength() <= 0) {
mMetadata.setContentLength(new File(selectedSource.toString()).length());
}
selectedSource = Uri.parse("file://" + selectedSource.toString().replace("content://", ""));
S3TaskResult result = new S3TaskResult();
// Put the image data into S3.
try {
Calendar cal = Calendar.getInstance();
if (mFile.type.equals("image")) {
mS3Filename = Long.valueOf(cal.getTime().getTime()).toString() + ".jpg";
} else {
mS3Filename = Long.valueOf(cal.getTime().getTime()).toString() + ".mp4";
}
PutObjectRequest por = new PutObjectRequest(
Config.getPictureBucket(cal.getTime().getTime()), mS3Filename,
resolver.openInputStream(selectedSource), mMetadata
).withGeneralProgressListener(new ProgressListener() {
int total = 0;
#Override
public void progressChanged(ProgressEvent pv) {
total += (int) pv.getBytesTransferred();
publishProgress(total);
}
});
mS3Client.putObject(por);
result.setName(mS3Filename);
} catch (Exception exception) {
exception.printStackTrace();
result.setName(null);
result.setErrorMessage(exception.getMessage());
}
return result;
}
protected void onPostExecute(S3TaskResult result) {
//mProgressBarFile.setProgress(0);
//mTextViewFileProgress.setText("");
// AWS Error
if (result != null && result.getErrorMessage() != null && result.getName() == null) {
FastDialog.showDialog(mActivity, FastDialog.SIMPLE_DIALOG, result.getErrorMessage());
} else {
// add picture name
mTheFormPictures.add(new Medias(result.getName()));
}
}
}
public static String getRealPathFromUri(Context context, Uri contentUri) {
Cursor cursor = null;
try {
String[] proj = { MediaStore.Images.Media.DATA };
cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} finally {
if (cursor != null) {
cursor.close();
}
}
}
/** close activity **/
public void close(View v) {
mActivity.finish();
}
/** select picture **/
public void selectPicture(View v) {
//Intent intent;
Intent intent = new Intent(
Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
/*if (Build.VERSION.SDK_INT < 19) {
intent = new Intent();
intent.setAction(Intent.ACTION_GET_CONTENT);
} else {
intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
}
if (Build.VERSION.SDK_INT >= 18) {
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
}*/
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
intent.setType("image/* video/*");
startActivityForResult(intent, RESULT_PHOTO_DISK);
}
/** take picture **/
public void tackePicture(View v) {
ApnActivity.show(mActivity, RESULT_PHOTO_APN);
}
/** record video **/
public void recordVideo(View v) {
RecordVideoActivity.show(mActivity, RESULT_VIDEO_APN);
}
/** publish button **/
public void publish(View v) {
// object
WebViewTheFormResult theFormResult = new WebViewTheFormResult(mEditTextText.getText().toString(), mTheFormPictures);
if (theFormResult.isEmpty()) {
FastDialog.showDialog(mActivity, FastDialog.SIMPLE_DIALOG, getString(R.string.theform_publish_error));
} else {
// intent
Intent dataIntent = new Intent();
Bundle bundle = new Bundle();
bundle.putSerializable(WebViewActivity.INTENT_OBJECT, (Serializable) theFormResult);
dataIntent.putExtras(bundle);
mActivity.setResult(Activity.RESULT_OK, dataIntent);
mActivity.finish();
}
}
#SuppressLint("NewApi")
public static void actionOnActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_CANCELED) {
return;
}
if (requestCode != RESULT_PHOTO_APN && requestCode != RESULT_VIDEO_APN) {
requestCode = RESULT_PHOTO_DISK;
}
switch (requestCode) {
case RESULT_PHOTO_DISK:
if (Build.VERSION.SDK_INT >= 18 && data.getData() == null) {
ClipData clipdata = data.getClipData();
for (int i = 0, l = clipdata.getItemCount(); i < l; i++) {
onDiskResult(clipdata.getItemAt(i).getUri());
}
} else {
onDiskResult(data.getData());
}
break;
case RESULT_PHOTO_APN:
onApnPhotoResult(data);
break;
case RESULT_VIDEO_APN:
onApnVideoResult(data);
break;
}
}
private static void onDiskResult(Uri selectedImage) {
InputStream imageStream;
try {
File file = new File(
Environment.getExternalStorageDirectory() + File.separator +
"Android" + File.separator +
"data" + File.separator +
mActivity.getPackageName()
);
if (new File(file.getAbsolutePath()).exists() == false) {
file.mkdirs();
}
imageStream = mActivity.getContentResolver().openInputStream(selectedImage);
Bitmap goodPicture = BitmapFactory.decodeStream(imageStream);
String filePath = file.getAbsoluteFile().toString() + "/" + String.valueOf(Utils.uid()) + Config.PHOTO_TMP_NAME;
try {
//goodPicture = ThumbnailUtils.createVideoThumbnail(filePath, MediaStore.Images.Thumbnails.MINI_KIND);
FileOutputStream out = new FileOutputStream(filePath);
goodPicture = Bitmap.createScaledBitmap(goodPicture, 800, 600, false);
goodPicture.compress(Bitmap.CompressFormat.JPEG, 80, out);
} catch (FileNotFoundException e) {
e.printStackTrace();
return;
}
queueFile(filePath, "image");
} catch (FileNotFoundException e1) {
e1.printStackTrace();
return;
}
}
private static void onApnPhotoResult(Intent data) {
String filePath = data.getExtras().getString(TheFormFragment.INTENT_PHOTO_APN_PATH);
if (filePath.equals(Integer.valueOf(RESULT_VIDEO_APN).toString())) {
RecordVideoActivity.show(mActivity, RESULT_VIDEO_APN);
} else {
queueFile(filePath, "image");
}
}
private static void onApnVideoResult(Intent data) {
String filePath = data.getExtras().getString(TheFormFragment.INTENT_VIDEO_APN_PATH);
if (filePath.equals(Integer.valueOf(RESULT_PHOTO_APN).toString())) {
ApnActivity.show(mActivity, RESULT_PHOTO_APN);
} else {
queueFile(filePath, "video");
}
}
private static void queueFile(String filePath, String fileType) {
mQueue.add(new Upload(filePath, fileType));
}
#Override
public void onResume() {
fetchTags();
while (mQueue.size() > 0) {
uploadFile(mQueue.remove(mQueue.size() - 1));
}
super.onResume();
}
private void uploadFile(Upload file) {
new S3PutObjectTask().execute(file);
listFileToUpload.add(file);
mUploading.updateListFileToUpdate(listFileToUpload);
mUploading.notifyDataSetChanged();
}
private void fetchTags() {
Api.getTags(mActivity, new Api.Callback() {
#Override
public void onSuccess(String json) {
Gson gson = new Gson();
mTags = gson.fromJson(json, Tag[].class);
}
});
}
}
How can I resolve the problem?
Something like this should be enough:
...
holder.image.setImageBitmap(item.getThumbnail(160, 160));
final ViewHolder finalHolder = holder;
item.setProgressListener(new ProgressListener() {
#Override
public void onProgress(int progress) {
finalHolder.progressUpdate.setProgress(item.getProgress());
}
});
finalHolder.progressUpdate.setProgress(item.getProgress());
Think that you can remove setProgressListener() from Upload class.
Instead add a ProgressBar variable and a method setProgressBar() to Upload.
In getView():
Upload upload = getItem(position )
upload.setProgressBar(holder.progressUpdate);
In Upload: in setProgress() you can now directly address the ProgressBar variable
this is the setProgress() that in your AsyncTask is called with mFile.setProgress(progress);
Instead of removing better out comment the function and the call.
Untested. Please test. This will not be much work.
Don't make holder final. It will not help you. You also made item final in order to use it in onProgress. But that will not do either. You have to determine the right holder with getTag() and if you put position in the holder (as int variable) then you can use holder.position to get the right item again with a getItem(holder.position)
Thanks for your responses all.
I resolved the problem like this:
public class UploadsViewAdapter extends BaseAdapter {
private Context mContext;
List<Upload> listFileToUpload;
UploadsViewAdapter instanceUploadsViewAdapter;
public UploadsViewAdapter(Context context,
List<Upload> data) {
this.mContext = context;
this.listFileToUpload = data;
this.instanceUploadsViewAdapter = this;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View row = convertView;
ViewHolder holder = null;
if (row == null) {
LayoutInflater inflater = ((Activity) mContext).getLayoutInflater();
row = inflater.inflate(R.layout.upload_item, parent, false);
holder = new ViewHolder();
holder.image = (ImageView) row.findViewById(R.id.upload_item_image);
holder.play = (ImageView) row.findViewById(R.id.play);
holder.progressUpdate = (ProgressBar) row
.findViewById(R.id.progressUpdate);
holder.deleteFileUploaded = (ImageView) row.findViewById(R.id.delete_file_uploaded);
row.setTag(holder);
} else {
holder = (ViewHolder) row.getTag();
}
final Upload item = getItem(position);
holder.image.setImageBitmap(item.getThumbnail(160, 160));
final ViewHolder finalHolder = holder;
item.setProgressListener(new ProgressListener() {
#Override
public void onProgress(int progress) {
//item.setProgress(progress);
finalHolder.progressUpdate.setProgress(progress);
if(progress==100){
finalHolder.image.setAlpha(1.0f);
finalHolder.progressUpdate.setVisibility(View.GONE);
}
else{
finalHolder.image.setAlpha(0.5f);
finalHolder.progressUpdate.setVisibility(View.VISIBLE);
}
}
});
if(item.getProgress()==100){
finalHolder.image.setAlpha(1.0f);
finalHolder.progressUpdate.setVisibility(View.GONE);
}
else{
finalHolder.image.setAlpha(0.5f);
finalHolder.progressUpdate.setVisibility(View.VISIBLE);
}
holder.deleteFileUploaded.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
listFileToUpload.remove(position);
instanceUploadsViewAdapter.notifyDataSetChanged();
}
});
if(item.getType().equals(EnumTypeFile.IMAGE.getTypeFile())){
holder.play.setVisibility(View.GONE);
}
else{
holder.play.setVisibility(View.VISIBLE);
}
finalHolder.progressUpdate.setProgress(item.getProgress());
return row;
}
static class ViewHolder {
ImageView image;
ProgressBar progressUpdate;
ImageView deleteFileUploaded;
ImageView play;
}
public void updateListFileToUpdate(List<Upload> listFileToUpload) {
this.listFileToUpload = listFileToUpload;
}
#Override
public int getCount() {
return listFileToUpload.size();
}
#Override
public Upload getItem(int location) {
return listFileToUpload.get(location);
}
#Override
public long getItemId(int position) {
return 0;
}
}
I create a image slide show type application, I my application used thread.
My application run successfully but after some time application suddenly close.
I am used following line of code to release memory
System.gc();
Runtime.getRuntime().gc();
without above code same issue occur.
Logcat:
03-13 12:45:09.250 / dalvikvm:
### ABORTING: DALVIK: HEAP MEMORY CORRUPTION IN internal_bulk_free addr=0x0
20713 20715 F03-13 12:45:09.250 / libc
Fatal signal 11 (SIGSEGV) at 0xdeadbaad (code=1), thread 20715 (GC)
How to solve my problem?
Please help me.
MY code is:
public class MyRunnable implements Runnable {
private int delayTime = 0;
private Vector<Integer> my_PlaylistRecord_ContentIds =new Vector<Integer>();
private Vector<Integer> delayArray =new Vector<Integer>();
private Vector<Long> video_Duration_List = new Vector<Long>();
private Vector<Integer> relative_Ids = new Vector<Integer>();
private Vector<RelativeLayout> layouts = new Vector<RelativeLayout>();
private RelativeLayout customRelativeLayout ;
private ArrayList<String> _idArray;
private ArrayList<String> _delayArray;
private int countPlus = 0;
private int totalSize = 0;
private ArrayList<Playlist_record> playlist_records;
private FinalPlaylist finalPlaylist;
private int fullscreenId =0;
private int screenId =0;
private int screenIndex =0;
private long videoDuration = 0;
public MyRunnable(ArrayList<Integer> _playlistRrecord_ContentIds, FinalPlaylist _finalPlaylist, List<Integer> delayLists, List<Long> videoDurationList) {
finalPlaylist = _finalPlaylist;
for (Integer id : _playlistRrecord_ContentIds) {
//System.out.println("content id:"+id);
my_PlaylistRecord_ContentIds.add(id);
}
for (Integer string : delayLists) {
//System.out.println("delay time :"+string);
delayArray.add(string);
}
for (Long videoDuration : videoDurationList) {
video_Duration_List.add(videoDuration);
}
totalSize = delayArray.size();
Iterator<Integer> myVeryOwnIterator = layoutMap.keySet().iterator();
while(myVeryOwnIterator.hasNext()) {
int key=(Integer) myVeryOwnIterator.next();
System.out.println("key:"+key);
customRelativeLayout = layoutMap.get(key);
//System.out.println(" test customRelativeLayout.getChildCount():"+customRelativeLayout.getChildCount());
layouts.add(customRelativeLayout);
relative_Ids.add(key);
}
// Find screen s
List<Container> containers = appDataBase.getAllCotainer();
for (Container container : containers) {
if(container.getName().equals("S")){
System.out.println("screen INVISIBLE index:");
screenId = container.getContainer_id();
System.out.println(" index :"+screenId);
}
if(container.getName().equals("FS")){
fullscreenId = container.getContainer_id();
}
}
// find index number of screen s container
for (int i = 0 ; i < relative_Ids.size() ; i++) {
if(screenId == relative_Ids.get(i)){
screenIndex = i;
}
}
/* for (int i = 0 ; i < relative_Ids.size() ; i++) {
List<Container> containers = appDataBase.getAllCotainer();
for (Container container : containers) {
if(container.getName().equals("FS")){
System.out.println("Full screen INVISIBLE index:"+i);
RelativeLayout relativeLayout = layouts.get(i);
//relativeLayout.setVisibility(View.INVISIBLE);
layouts.set(i, relativeLayout);
} else if(container.getName().equals("S")){
System.out.println("screen INVISIBLE index:"+i);
RelativeLayout relativeLayout = layouts.get(i);
relativeLayout.setVisibility(View.INVISIBLE);
layouts.set(i, relativeLayout);
}
}
}*/
}
public void run() {
System.out.println("screen container id:"+screenId);
while(IS_THREAD_RUN){
if(countPlus < totalSize){
Runnable iRunnable= new Runnable() {
public void run() {
// System.out.println(" ** countPlus:"+ countPlus);
// System.out.println(" ** totalSize:"+ totalSize);
// System.out.println("my_playlist_ids size:"+my_PlaylistRecord_ContentIds.size());
// System.out.println("my_playlist_ids content:"+my_PlaylistRecord_ContentIds.get(countPlus));
// Get all playlist record
List<Playlist_record> playlist_records = finalPlaylist.getPlayerArray();
Playlist_record playlist_record = playlist_records.get(countPlus);
//System.out.println("test run container id:"+playlist_record.getContainer_id());
// ***********************************
// Check playlist_record validation
// ***********************************
//System.out.println("playlist_recordId:"+my_playlist_ids.get(countPlus));
boolean isvalidContent = false;
isvalidContent = appDataBase.isPlayContent(playlist_record.getPlaylist_record_id());
System.out.println("Valid Content:"+isvalidContent);
if(isvalidContent){
// Hide layout, Fetch all container data and get name equals to FS and S then relative layout
/*
for (int i = 0 ; i < relative_Ids.size() ; i++) {
List<Container> containers = appDataBase.getAllCotainer();
for (Container container : containers) {
if(container.getName().equals("FS")){
System.out.println("Full screen INVISIBLE index:"+i);
RelativeLayout relativeLayout = layouts.get(i);
//relativeLayout.setVisibility(View.INVISIBLE);
layouts.set(i, relativeLayout);
} else if(container.getName().equals("S")){
System.out.println("screen INVISIBLE index:"+i);
RelativeLayout relativeLayout = layouts.get(i);
relativeLayout.setVisibility(View.INVISIBLE);
layouts.set(i, relativeLayout);
}
}
}*/
//System.out.println(" layouts:"+layouts.toString());
for (int i = 0 ; i < relative_Ids.size() ; i++) {
if(relative_Ids.get(i) == playlist_record.getContainer_id()){
//System.out.println("countainer id:"+relative_Ids.get(i));
// System.out.println("playlist_record.getContainer_id():"+playlist_record.getContainer_id());
customRelativeLayout = layouts.get(i);
// System.out.println("customRelativeLayout.getChildCount():"+customRelativeLayout.getChildCount());
// Fetch all container data and get name equals to FS and S then relative layout visible
if(screenId == playlist_record.getContainer_id()){
customRelativeLayout.setVisibility(View.VISIBLE);
//customRelativeLayout.bringToFront();
}else {
RelativeLayout relativeLayout = layouts.get(screenIndex);
relativeLayout.setVisibility(View.INVISIBLE);
layouts.set(screenIndex, relativeLayout);
}
//Weather id match
try {
Feature_Defination feature_Defination = appDataBase.getFeatureDefinition(relative_Ids.get(i));
if(relative_Ids.get(i)==feature_Defination.getContainerID()){
System.out.println("match");
displayWeatherData(customRelativeLayout,feature_Defination.getContainerID(),feature_Defination);
}
} catch (Exception e) {
e.printStackTrace();
}
//System.out.println("transition effect:"+playlist_record.getTransition());
//customRelativeLayout.setVisibility(View.VISIBLE);
setContent(my_PlaylistRecord_ContentIds.get(countPlus),customRelativeLayout,getAnimation(playlist_record.getTransition()),delayArray.get(countPlus));
}
} // End for loop
System.out.println("my_playlist_ids:"+my_PlaylistRecord_ContentIds.get(countPlus));
// setContent(my_playlist_ids.get(countPlus),customRelativeLayout);
countPlus =countPlus+1;
if(countPlus >= totalSize){
countPlus = 0;
}
}else{
countPlus =countPlus+2;
if(countPlus >= totalSize){
countPlus = 0;
}
}
} //run method end
};
handler.post(iRunnable);
}else{
countPlus = 0;
}
//System.out.println("countplus before thread sleep:"+delayArray.get(countPlus)+" countPlus:"+countPlus);
//System.out.println("countplus sleep video duration:"+videoDuration);
try {
long sleepTime = delayArray.get(countPlus);
// System.out.println("sleep delay :"+sleepTime);
if(sleepTime==0){
long videoTime = video_Duration_List.get(countPlus);
if(videoTime == 0 ){
sleepTime = 1000;
}else{
sleepTime = videoTime;
}
}else{
sleepTime = (sleepTime * 1000)+1000;
}
/*
if(videoDuration!=0){
System.out.println("sleep count plus"+countPlus);
countPlus = countPlus - 1;
if(countPlus<=0){
countPlus = 0;
}
System.out.println("sleep countPlus:"+countPlus);
sleepTime = videoDuration;
}*/
// new DisplayContentAsync().execute(""+my_PlaylistRecord_ContentIds.get(countPlus));
System.out.println("sleep time:"+sleepTime);
Thread.sleep(sleepTime);
//Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} // run method end
}
}
/* class DisplayContentAsync extends AsyncTask<String, String, String>{
#Override
protected String doInBackground(String... params) {
// get video file length
// check video
// *********************************************************
String play_FileName = "";
//Get all record from content table
File conFile = new File( Util.ROOT_PATH + "Contents/"+play_FileName);
//Check image file
ImageFileFilter imageFileFilter = new ImageFileFilter(conFile);
VideoFileFilter videoFileFilter = new VideoFileFilter(conFile);
Content content = appDataBase.getContentTemp(""+params[0]);
System.out.println("content id:"+content.getContent_id());
System.out.println("content path:"+content.getContent());
try {
String[] contentArray = null;
contentArray = content.getContent().split("/");
play_FileName = contentArray[contentArray.length-1];
} catch (Exception e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
String filePath = Util.ROOT_PATH + "Contents/"+conFile.getName();
if(videoFileFilter.accept(conFile)){
System.out.println("Video file name:"+play_FileName);
// Get video file play duration
MediaMetadataRetriever retriever = new MediaMetadataRetriever();
retriever.setDataSource(filePath);
String time = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);
long time1 = Long.parseLong( time );;
System.out.println("video time: "+time1);
}
// setContent(my_playlist_ids.get(countPlus),customRelativeLayout);
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
}
}
*/
#SuppressLint("NewApi")
public void setContent(int content_id,RelativeLayout _customRelativeLayout,List<Animation> _animations, int _videoTimeDuration){
//System.gc();
//Runtime.getRuntime().gc();
List<Animation> animations = _animations;
RelativeLayout customRelativeLayout = _customRelativeLayout;
ImageView imageView = null;
VideoView videoView = null;
WebView webView = null;
int height = customRelativeLayout.getHeight();
int width = customRelativeLayout.getWidth();
final int videoTimeDuration = _videoTimeDuration;
Animation anim1 = null ;
Animation anim2 = null;
Animation anim3 = null;
for(int p=0; p<animations.size();p++){
if(p==0){
anim1 = animations.get(p);
System.out.println("animation 1");
}else if(p==1){
anim2 = animations.get(p);
System.out.println("animation 2");
}else if(p==2){
anim3 = animations.get(p);
System.out.println("animation 3");
}
}
//System.out.println("layout height :"+height);
//System.out.println("layout height :"+height);
// Find all child from relative layout
int childcount = customRelativeLayout.getChildCount();
//System.out.println("get all child:"+childcount);
for (int i=0; i < childcount; i++){
View view = customRelativeLayout.getChildAt(i);
if (view instanceof ImageView) {
imageView = (ImageView) view;
// do what you want with imageView
}else if (view instanceof VideoView) {
videoView = (VideoView) view;
// do what you want with imageView
}else if (view instanceof WebView) {
webView = (WebView) view;
// do what you want with imageView
}
}
String play_FileName = "";
//Get all record from content table
//System.out.println("content id match with:"+content_id);
Content content = appDataBase.getContent(""+content_id);
//System.out.println("content id:"+content.getContent_id());
//System.out.println("content path:"+content.getContent());
try {
String[] contentArray = null;
contentArray = content.getContent().split("/");
play_FileName = contentArray[contentArray.length-1];
} catch (Exception e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
System.out.println("Play file name:"+play_FileName);
//Toast.makeText(Display.this, play_FileName, 1000).show();
//System.out.println("Play file duration:"+duration);
/*
// Set animation
if(animations!=null && animations.size()>=2){
System.out.println("animation 2 available ");
final Animation endanim = anim2;
final RelativeLayout relativeLayout = customRelativeLayout;
customRelativeLayout.startAnimation(anim1);
anim1.setAnimationListener(new AnimationListener() {
#Override
public void onAnimationStart(Animation arg0) {
}
#Override
public void onAnimationRepeat(Animation arg0) {
}
#Override
public void onAnimationEnd(Animation arg0) {
relativeLayout.startAnimation(endanim);
}
});
}else if(animations!=null && animations.size()==1){
System.out.println("animation 1 available");
imageView.setAnimation(anim1);
}else {
System.out.println("animation not available");
}
*/
File conFile = new File( Util.ROOT_PATH + "Contents/"+play_FileName);
//Check image file
ImageFileFilter imageFileFilter = new ImageFileFilter(conFile);
VideoFileFilter videoFileFilter = new VideoFileFilter(conFile);
WebFileFilter webFileFilter = new WebFileFilter(conFile);
String filePath = Util.ROOT_PATH + "Contents/"+conFile.getName();
//check file size is zero or not
File chkFile = new File(filePath);
if(chkFile.length()>0){
if(imageFileFilter.accept(conFile)){
//System.out.println("filter image file name:"+conFile.getName());
videoView.setVisibility(View.GONE);
imageView.setVisibility(View.VISIBLE);
webView.setVisibility(View.GONE);
// Check android os
int currentapiVersion = android.os.Build.VERSION.SDK_INT;
if (currentapiVersion >= android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH){
//System.out.println("jelly bean");
Drawable drawable = Drawable.createFromPath(filePath);
imageView.setBackground(drawable);
//imageView.setImageBitmap(decodeFile(chkFile, 1000, 1000));
// Set animation
if(animations!=null && animations.size()>=2){
System.out.println("animation 2 available ");
final Animation endanim = anim2;
final ImageView finalImage = imageView;
imageView.startAnimation(anim1);
anim1.setAnimationListener(new AnimationListener() {
#Override
public void onAnimationStart(Animation arg0) {
}
#Override
public void onAnimationRepeat(Animation arg0) {
}
You can try this.Add below line in android manifest file :
android:largeHeap="true"
Thanks.