Save and retrieve Shape object in android give JAVA.io.NotSerializableExeception - android

I am using the following code to save and load arraylist of shapes Objects in drawing. but it gives AVA.io.NotSerializableExeception. how to solve this,
public class OffLineCanvas extends SurfaceView implements
SurfaceHolder.Callback {
private boolean canTakeImage;
private OffLineCanvasThread uiThread;
private List<List<MyShape>> dequeUndo;
private List<List<MyShape>> dequeRedo;
private List<MyShape> shapesList;
private CopyOnWriteArrayList<MyShape> objectsToDraw;
private Context context;
private Canvas can;
private Bitmap toDisk = null;
public OffLineCanvas(Context context) {
super(context);
this.context = context;
getHolder().addCallback(this);
objectsToDraw = new CopyOnWriteArrayList<MyShape>();
setZOrderOnTop(false);
dequeUndo = new ArrayList<List<MyShape>>();
dequeRedo = new ArrayList<List<MyShape>>();
shapesList = new ArrayList<MyShape>();
getObject(context);
}
public void AddShapeOffline(MyShape shape, boolean canDraw) {
if (canDraw) {
objectsToDraw.add(shape);
shapesList = Conversion(objectsToDraw);
} else {
shapesList = Conversion(objectsToDraw);
shapesList.add(shape);
}
push(shapesList);
}
private List<MyShape> Conversion(CopyOnWriteArrayList<MyShape> objectsToDraw) {
List<MyShape> tList = new ArrayList<MyShape>();
Iterator<MyShape> iTemp = objectsToDraw.iterator();
while (iTemp.hasNext()) {
MyShape value = iTemp.next();
tList.add(value);
}
return tList;
}
private void push(List<MyShape> msL) {
if (dequeUndo != null)
dequeUndo.add(msL);
}
public void pop() {
if (dequeUndo != null && dequeUndo.size() >= 0) {
if (dequeUndo.size() > 0) {
if (dequeRedo.size() == 0) {
undo(); // undo first view
}
List<MyShape> temp = undo();
objectsToDraw.clear();
if(temp.size() > 0){
for (int i = 0; i < temp.size(); i++) {
objectsToDraw.add(temp.get(i));
}
}
} else {
objectsToDraw.clear();
}
}
}
private List<MyShape> undo() {
List<MyShape> temp = new CopyOnWriteArrayList<MyShape>();
if(dequeUndo.size()>0){
temp = new ArrayList<MyShape>(dequeUndo.get(dequeUndo
.size() - 1));
dequeRedo.add(temp);
dequeUndo.remove(dequeUndo.size() - 1);
}
return temp;
}
public void popR() {
if (dequeRedo != null && dequeRedo.size() > 0) {
if (dequeRedo.size() > 0) {
List<MyShape> temp = new ArrayList<MyShape>(
dequeRedo.get(dequeRedo.size() - 1));
dequeUndo.add(temp);
dequeRedo.remove(dequeRedo.size() - 1);
objectsToDraw.clear();
for (int i = 0; i < temp.size(); i++) {
objectsToDraw.add(temp.get(i));
}
}
}
}
public void SelectShapeOffile(Point point) {
for (int i = 0; i < objectsToDraw.size(); i++) {
if (objectsToDraw.get(i).getBorderRegion().contains((int) point.x, (int) point.y)) {
objectsToDraw.get(i).setSelectd(true);
((Main) context).AddShapeToOnlineCanvas(objectsToDraw.get(i));
objectsToDraw.remove(i);
break;
} else {
((Main) context).NoShapeSelected();
objectsToDraw.get(i).setSelectd(false);
Log.e("asdasdasdasdadasd", "Touch OUT");
}
}
}
#Override
public void onDraw(Canvas canvas) {
if (canvas != null) {
synchronized (getHolder()) {
canvas.drawColor(Color.WHITE);
Iterator<MyShape> drawableObject = objectsToDraw.iterator();
while (drawableObject.hasNext()) {
MyShape value = drawableObject.next();
if (canTakeImage) {
try {
value.draw(can, value.getPaint());
} catch (Exception ex) {
ex.printStackTrace();
}
canvas.setBitmap(toDisk);
} else {
value.draw(canvas, value.getPaint());
}
}
if (canTakeImage) {
try {
saveSignature();
canTakeImage = false;
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
}
}
public Bitmap saveSignature() {
ContextWrapper cw = new ContextWrapper(context);
// path to /data/data/yourapp/app_data/imageDir
File directory = cw.getDir("images", Context.MODE_PRIVATE);
// Create imageDir
File mypath = new File(directory, "profile.png");
try {
toDisk.compress(Bitmap.CompressFormat.PNG, 100,
new FileOutputStream(mypath));
} catch (Exception e) {
e.printStackTrace();
}
return toDisk;
}
public void stopUIThread() {
uiThread.setRunning(false);
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
uiThread = new OffLineCanvasThread(this);
uiThread.setRunning(true);
uiThread.start();
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
uiThread.setRunning(false);
}
public void clearCanvas() {
objectsToDraw.clear();
}
/****************************** save file ******************************/
public void saveCanvas() {
canTakeImage = true;
toDisk = null;
Bitmap.Config conf = Bitmap.Config.ARGB_8888;
toDisk = Bitmap.createBitmap(this.getWidth(), this.getHeight(), conf);
can = new Canvas(toDisk);
can.drawColor(Color.WHITE);
File cacheDir = null;
if (android.os.Environment.getExternalStorageState().equals(
android.os.Environment.MEDIA_MOUNTED)) {
cacheDir = new File(
android.os.Environment.getExternalStorageDirectory(),
"MyCustomObject");
} else {
cacheDir = context.getCacheDir();
}
if (!cacheDir.exists()) {
cacheDir.mkdirs();
}
boolean result = saveObject(objectsToDraw, context);
if (result)
Toast.makeText(context, "Saved object", Toast.LENGTH_LONG).show();
else
Toast.makeText(context, "Error saving object", Toast.LENGTH_LONG)
.show();
}
public boolean saveObject(CopyOnWriteArrayList<MyShape> obj, Context c) {
final File suspend_f = new File(c.getCacheDir(), "test");
FileOutputStream fos = null;
ObjectOutputStream oos = null;
boolean keep = true;
try {
fos = new FileOutputStream(suspend_f);
oos = new ObjectOutputStream(fos);
oos.writeObject(obj);
} catch (Exception e) {
e.printStackTrace();
keep = false;
} finally {
try {
if (oos != null)
oos.close();
if (fos != null)
fos.close();
if (keep == false)
suspend_f.delete();
} catch (Exception e) {
e.printStackTrace();
}
}
return keep;
}
#SuppressWarnings("unchecked")
public CopyOnWriteArrayList<MyShape> getObject(Context c) {
final File suspend_f = new File(c.getCacheDir(), "test");
CopyOnWriteArrayList<MyShape> simpleClass = null;
FileInputStream fis = null;
ObjectInputStream is = null;
try {
fis = new FileInputStream(suspend_f);
is = new ObjectInputStream(fis);
objectsToDraw = (CopyOnWriteArrayList<MyShape>) is.readObject();
} catch (Exception e) {
#SuppressWarnings("unused")
String val = e.getMessage();
} finally {
try {
if (fis != null)
fis.close();
if (is != null)
is.close();
} catch (Exception e) {
}
}
return simpleClass;
}
}
Regards

It means either your MyShape class, or some of its field doesn't implement Serializable (which is required to be implemented, though it contains no method (it's a marker interface)).

Related

SurfaceView hangs after rendering first few frames

I am currently trying to output processed opencv mat images from openCV to SurfaceView at fps of 30 or more.
I am using asynctasks to process the mat images into bitmaps, with the results added to bitmap buffer in the MSurface class.
Then another repetitive thread will call outputDisplay of the same Msurface class which will pop the first bitmap from the bitmap buffer and output it SurfaceView through lockCanvas and unlockCanvasAndPost.
But only first or first few frames will be displayed before it freezes forever.
Code snippets below
In main activity
this.backGroundPool = new ScheduledThreadPoolExecutor(2);
this.backGroundPool.setMaximumPoolSize(2);
this.backgroundThread = new Runnable() {
#Override
public void run() {
try {
if (cameraTasks != null && mSurface != null) {
//Log.w("Output Task", "Processing");
if (outputTasks != null) {
if (outputTasks.size() <= cameraTasks.size()) {
//Log.w("Output Task", "Adding");
outputTasks.addLast(new OutputTask(mSurface));
outputTasks.getLast().execute(imageBuffer.getFinalImg());
}
if (outputTasks.getFirst().getStatus() == AsyncTask.Status.FINISHED) {
outputTasks.removeFirst();
}
}
}
if (cameraTasks == null) {
Log.w("CameraTask", "Not initialized");
}
if (mSurface == null) {
Log.w("mSurface View", "Not initialized");
}
} catch (Exception e) {
e.printStackTrace();
}
}
};
this.backGroundPool.scheduleAtFixedRate(this.backgroundThread,
START_DELAY,
TIME_PERIOD,
TIME_UNIT);
this.outputThread = new Runnable() {
#Override
public void run() {
try {
while (true) {
mSurface.outputDisplay();
}
} catch (Exception e) {
e.printStackTrace();
}
}
};
this.backGroundPool.scheduleAtFixedRate(this.outputThread,
START_DELAY,
TIME_PERIOD,
TIME_UNIT);
In OutputTask class
public class OutputTask extends AsyncTask<Mat, Void, Bitmap> {
private MSurface mSurface;
public OutputTask(MSurface mSurface) {
this.mSurface = mSurface;
}
#RequiresApi(api = Build.VERSION_CODES.O)
#Override
protected Bitmap doInBackground(Mat... images) {
//Log.i("Camera Task", "Running");
if (images.length != 0 && images[0] != null) {
Bitmap bm = Bitmap.createBitmap(images[0].cols(), images[0].rows(), Bitmap.Config.ARGB_8888);;
Utils.matToBitmap(images[0], bm);
ByteArrayOutputStream out = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.PNG, 100, out);
Bitmap compressedBM = BitmapFactory.decodeStream(new ByteArrayInputStream(out.toByteArray()));
return compressedBM;
}
else {
Log.w("Mat Image", "Not Found");
return null;
}
}
#Override
protected void onPostExecute(Bitmap result) {
try {
if (result != null) {
synchronized (this.mSurface.getHolder()) {
//Log.i("Buffer", "Updating");
this.mSurface.addBitmapBuffer(result);
}
}
} catch (Exception e) {
e.printStackTrace();
}
super.onPostExecute(result);
}
In MSurface class
public class MSurface extends SurfaceView implements SurfaceHolder.Callback {
private static int MAXBUFFERSIZE = 30;
public LinkedList<Bitmap> bitmapBuffer;
private boolean surfaceAvailable;
private int surfaceWidth;
private int surfaceHeight;
public MSurface(Context context, AttributeSet attrs) {
super(context, attrs);
this.getHolder().addCallback(this);
this.getHolder().setFormat(PixelFormat.RGBA_8888);
this.bitmapBuffer = new LinkedList<Bitmap>();
this.surfaceAvailable = false;
}
public void addBitmapBuffer(Bitmap bitmap) {
this.bitmapBuffer.addLast(bitmap);
if (this.bitmapBuffer.size() > MAXBUFFERSIZE) {
Bitmap bm = this.bitmapBuffer.pop();
bm.recycle();
}
}
public void outputDisplay() {
if (this.bitmapBuffer.size() > 0 && this.surfaceAvailable) {
Canvas canvas = getHolder().lockCanvas();
//Log.i("Canvas", "Drawing new frame");
//canvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.MULTIPLY);
Bitmap bm = this.bitmapBuffer.pop();
Rect src = new Rect(0, 0, bm.getWidth(), bm.getHeight());
Rect dst = new Rect((int)((this.surfaceWidth - bm.getWidth()) / 2),
((int)(this.surfaceHeight - bm.getHeight()) / 2),
((int)(this.surfaceWidth - bm.getWidth()) / 2 + bm.getWidth()),
((int)(this.surfaceHeight - bm.getHeight()) / 2 + bm.getHeight()));
canvas.drawColor( 0, PorterDuff.Mode.CLEAR );
canvas.drawBitmap(bm, src, dst, null);
this.getHolder().unlockCanvasAndPost(canvas);
bm.recycle();
}
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
// TODO Auto-generated method stub
Log.i("Surface", "Changed");
Log.d("SurfaceHolder", String.valueOf(holder));
Log.i("Surface Format", String.valueOf(format));
Log.i("Surface Width", String.valueOf(width));
Log.i("Surface Height", String.valueOf(height));
this.surfaceWidth = width;
this.surfaceHeight = height;
if (holder.getSurface() == null) {
Log.i("Surface", "Missing");
}
setWillNotDraw(false);
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
Log.i("Surface", "Created");
Log.d("SurfaceHolder", String.valueOf(holder));
this.surfaceAvailable = true;
//this.setWillNotDraw(false);
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
// TODO Auto-generated method stub
this.surfaceAvailable = false;
Log.i("Surface", "Destroyed");
}
}
Thanks in advance for those who are able to provide suggestions/solutions

Subtitles are not displaying the when seek to backward in videoview

In my Android app videos are played with subtitles using videoview. The problem is when I'm pressing forward or dragging the seekbar subtitles are displaying, but when I'm pressing backward or dragging the seekbar backwards subtitles are not displaying. Below is the full code.
public class MainActivity extends AppCompatActivity implements View.OnTouchListener,MediaPlayer.OnInfoListener,MediaPlayer.OnSeekCompleteListener {
MediaController ctlr;
VideoView videoview;
FrameLayout playercontrolerview;
View view_full_cc;
TextView tv_subtitleText;
private static Handler handler = new Handler();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
videoview = (VideoView) findViewById(R.id.VideoView);
tv_subtitleText=(TextView) findViewById(R.id.tv_subtitleText);
try {
// Start the MediaController
setVideoView();
preparedvideo();
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
}
private void setVideoView() {
ctlr = new MediaController(MainActivity.this) {
#Override
public void show() {
repositionSubtitle(true);
super.show();
}
#Override
public void hide() {
repositionSubtitle(false);
super.hide();
}
};
playercontrolerview = (FrameLayout) ctlr.getParent();
ctlr.setMediaPlayer(videoview);
ctlr.setAnchorView(videoview);
videoview.setMediaController(ctlr);
videoview.requestFocus();
}
private void preparedvideo(){
videoview.setVideoURI(Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.samplevideo));
videoview.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
try {
mp.addTimedTextSource(getSubtitleFile(R.raw.sub1), MediaPlayer.MEDIA_MIMETYPE_TEXT_SUBRIP);
int textTrackIndex = findTrackIndexFor(MediaPlayer.TrackInfo.MEDIA_TRACK_TYPE_TIMEDTEXT, mp.getTrackInfo());
if (textTrackIndex >= 0) {
try {
mp.selectTrack(textTrackIndex);
}catch (Exception e){
e.printStackTrace();
}
} else {
Log.w("subtitles", "Cannot find text track!");
}
mp.setOnTimedTextListener(new MediaPlayer.OnTimedTextListener() {
#Override
public void onTimedText(final MediaPlayer mp, final TimedText text) {
if(text!=null){
handler.post(new Runnable() {
#Override
public void run() {
try {
int seconds = mp.getCurrentPosition() / 1000;
Log.e("Subtitle", "subtitle Info " + text.getText());
tv_subtitleText.setText(text.getText());
}catch (Exception w){
w.printStackTrace();
}
}
});
}else{
Log.e("Subtitle", "subtitle Info null ");
}
}
});
}catch (Exception e){
e.printStackTrace();
}
try {
videoview.start();
}catch (Exception e){
e.printStackTrace();
}
}
});
}
public void repositionSubtitle(boolean isShown) {
FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) tv_subtitleText.getLayoutParams();
if (params != null) {
if (isShown)
params.bottomMargin = 150;
else
params.bottomMargin = 0;
tv_subtitleText.setLayoutParams(params);
}
}
private int findTrackIndexFor(int mediaTrackType, MediaPlayer.TrackInfo[] trackInfo) {
int index = -1;
for (int i = 0; i < trackInfo.length; i++) {
if (trackInfo[i].getTrackType() == mediaTrackType) {
return i;
}
}
return index;
}
private String getSubtitleFile(int resId) {
String fileName = getResources().getResourceEntryName(resId);
File subtitleFile = getFileStreamPath(fileName);
if (subtitleFile.exists()) {
Log.d("subtitle", "Subtitle already exists");
return subtitleFile.getAbsolutePath();
}
Log.d("subtitle", "Subtitle does not exists, copy it from res/raw");
// Copy the file from the res/raw folder to your app folder on the
// device
InputStream inputStream = null;
OutputStream outputStream = null;
try {
inputStream = getResources().openRawResource(resId);
outputStream = new FileOutputStream(subtitleFile, false);
copyFile(inputStream, outputStream);
return subtitleFile.getAbsolutePath();
} catch (Exception e) {
e.printStackTrace();
} finally {
closeStreams(inputStream, outputStream);
}
return "";
}
private void copyFile(InputStream inputStream, OutputStream outputStream)
throws IOException {
final int BUFFER_SIZE = 1024;
byte[] buffer = new byte[BUFFER_SIZE];
int length = -1;
while ((length = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, length);
}
}
// A handy method I use to close all the streams
private void closeStreams(Closeable... closeables) {
if (closeables != null) {
for (Closeable stream : closeables) {
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
#Override
public boolean onInfo(MediaPlayer mp, int what, int extra) {
videoview.getCurrentPosition();
// Collection<Caption> subtitles = srt.captions.values();
return false;
}
#Override
public boolean onTouch(View v, MotionEvent event) {
return false;
}
#Override
public void onSeekComplete(MediaPlayer mp) {
}
}

application integration with google drive

I am working with android application integration with google drive.I want to upload .csv file of backup to google drive..But error found. my code is here..there is error after choose picture from gallery that : com.google.api.client.googleapis.extentions.android.gms.auth.GoogleAuthIOException
MainActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Connect to Google Drive
mCredential = GoogleAccountCredential.usingAudience(MainActivity.this,"852032254538-54h2nh1h5f2c4bg7ubash64d4vtcsc4f.apps.googleusercontent.com");
startActivityForResult(mCredential.newChooseAccountIntent(),
REQUEST_ACCOUNT_PICKER);
mContext = MainActivity.this;
setContentView(R.layout.activity_main);
mListView = (ListView) findViewById(R.id.listView1);
OnItemClickListener mMessageClickedHandler = new OnItemClickListener() {
public void onItemClick(AdapterView parent, View v, int position,
long id) {
downloadItemFromList(position);
}
};
mListView.setOnItemClickListener(mMessageClickedHandler);
final Button button = (Button) findViewById(R.id.button1);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
final Intent galleryIntent = new Intent(Intent.ACTION_PICK);
galleryIntent.setType("*/*");
startActivityForResult(galleryIntent, RESULT_STORE_FILE);
}
});
final Button button2 = (Button) findViewById(R.id.button2);
button2.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Thread t = new Thread(new Runnable() {
#Override
public void run() {
mResultList = new ArrayList<File>();
com.google.api.services.drive.Drive.Files f1 = mService
.files();
Files.List request = null;
do {
try {
request = f1.list();
request.setQ("trashed=false");
FileList fileList = request.execute();
mResultList.addAll(fileList.getItems());
request.setPageToken(fileList
.getNextPageToken());
} catch (UserRecoverableAuthIOException e) {
startActivityForResult(e.getIntent(),
REQUEST_AUTHORIZATION);
} catch (IOException e) {
e.printStackTrace();
if (request != null) {
request.setPageToken(null);
}
}
} while (request.getPageToken() != null
&& request.getPageToken().length() > 0);
populateListView();
}
});
t.start();
}
});
}
private void downloadItemFromList(int position) {
mDLVal = (String) mListView.getItemAtPosition(position);
showToast("You just pressed: " + mDLVal);
Thread t = new Thread(new Runnable() {
#Override
public void run() {
for (File tmp : mResultList) {
if (tmp.getTitle().equalsIgnoreCase(mDLVal)) {
if (tmp.getDownloadUrl() != null
&& tmp.getDownloadUrl().length() > 0) {
try {
com.google.api.client.http.HttpResponse resp = mService
.getRequestFactory()
.buildGetRequest(
new GenericUrl(tmp
.getDownloadUrl()))
.execute();
InputStream iStream = resp.getContent();
try {
final java.io.File file = new java.io.File(
Environment
.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DOWNLOADS)
.getPath(), tmp.getTitle());
showToast("Downloading: "
+ tmp.getTitle()
+ " to "
+ Environment
.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DOWNLOADS)
.getPath());
storeFile(file, iStream);
} finally {
iStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
});
t.start();
}
private void populateListView() {
runOnUiThread(new Runnable() {
#Override
public void run() {
mFileArray = new String[mResultList.size()];
int i = 0;
for (File tmp : mResultList) {
mFileArray[i] = tmp.getTitle();
i++;
}
mAdapter = new ArrayAdapter<String>(mContext,
android.R.layout.simple_list_item_1, mFileArray);
mListView.setAdapter(mAdapter);
}
});
}
private void storeFile(java.io.File file, InputStream iStream) {
try {
final OutputStream oStream = new FileOutputStream(file);
try {
try {
final byte[] buffer = new byte[1024];
int read;
while ((read = iStream.read(buffer)) != -1) {
oStream.write(buffer, 0, read);
}
oStream.flush();
} finally {
oStream.close();
}
} catch (Exception e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
protected void onActivityResult(final int requestCode,
final int resultCode, final Intent data) {
switch (requestCode) {
case REQUEST_ACCOUNT_PICKER:
if (resultCode == RESULT_OK && data != null
&& data.getExtras() != null) {
String accountName = data
.getStringExtra(AccountManager.KEY_ACCOUNT_NAME);
if (accountName != null) {
mCredential.setSelectedAccountName(accountName);
mService = getDriveService(mCredential);
}
}
break;
case REQUEST_AUTHORIZATION:
if (resultCode == Activity.RESULT_OK) {
// account already picked
} else {
startActivityForResult(mCredential.newChooseAccountIntent(),
REQUEST_ACCOUNT_PICKER);
}
break;
case RESULT_STORE_FILE:
mFileUri = data.getData();
// Save the file to Google Drive
saveFileToDrive();
break;
}
}
private Drive getDriveService(GoogleAccountCredential credential) {
return new Drive.Builder(AndroidHttp.newCompatibleTransport(),
new GsonFactory(), credential).build();
}
private void saveFileToDrive() {
Thread t = new Thread(new Runnable() {
#Override
public void run() {
try {
// Create URI from real path
String path;
path = getPathFromUri(mFileUri);
mFileUri = Uri.fromFile(new java.io.File(path));
ContentResolver cR = MainActivity.this.getContentResolver();
Log.d("tag123", "go to save in drive");
// File's binary content
java.io.File fileContent = new java.io.File(mFileUri
.getPath());
Log.d("tag123", "get path from resourse");
FileContent mediaContent = new FileContent(cR
.getType(mFileUri), fileContent);
Log.d("tag123", "selected");
showToast("Selected " + mFileUri.getPath() + "to upload");
// File's meta data.
File body = new File();
body.setTitle(fileContent.getName());
body.setMimeType(cR.getType(mFileUri));
Log.d("tag123", "store in other file");
com.google.api.services.drive.model.File file = mService
.files().insert(body, mediaContent).execute();
if (file != null) {
showToast("Uploaded: " + file.getTitle());
}
} catch (UserRecoverableAuthIOException e) {
startActivityForResult(e.getIntent(), REQUEST_AUTHORIZATION);
} catch (IOException e) {
e.printStackTrace();
showToast("Transfer ERROR: " + e.toString());
}
}
});
t.start();
}
public void showToast(final String toast) {
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), toast,
Toast.LENGTH_SHORT).show();
}
});
}
public String getPathFromUri(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(uri, projection, null, null,
null);
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}

Android Image to View in Full Screen

I'm new to Android and Java. I have been working on my task i.e, Image Downloader. Where I have to download images with progress bar and display them in grid View. I have created two classes 1. URLImageAdapter 2. CacheActivity. Everything works fine but now I want these images to open in full screen when clicked Any help? thank You.
Any Simple Method.
public class URLImageAdapter extends BaseAdapter {
private File sdImageMainDirectory;
private Context myContext;
private class Image {
String url;
Bitmap thumb;
}
private Image[] images;
private LoadThumbsTask thumbnailGen;
private Object previousList;
public URLImageAdapter(Context c) {
myContext = c;
thumbnailGen = new LoadThumbsTask();
if (previousList != null) {
images = (Image[]) previousList;
thumbnailGen.execute(images);
return;
}
images = new Image[imageURLs.length];
for (int i = 0, j = imageURLs.length; i < j; i++) {
images[i] = new Image();
images[i].url = imageURLs[i];
}
thumbnailGen.execute(images);
}
private void saveDataInSdCard(Bitmap bt,int i) {
OutputStream fOut = null;
Uri outputFileUri;
try {
File root = new File(Environment.getExternalStorageDirectory()
+ File.separator + "urFlodername" + File.separator);
root.mkdirs();
sdImageMainDirectory = new File(root,i+"myPicName.jpg");
outputFileUri = Uri.fromFile(sdImageMainDirectory);
fOut = new FileOutputStream(sdImageMainDirectory);
} catch (Exception e) {
}
Bitmap bm =bt;
try {
bm.compress(Bitmap.CompressFormat.PNG, 100, fOut);
fOut.flush();
fOut.close();
} catch (Exception e) {
}
}
public int getCount() {
return images.length;
}
public Object getItem(int position) {
return images[position].url;
}
public long getItemId(int position) {
return position;
}
public Object getData() {
if (thumbnailGen != null
&& thumbnailGen.getStatus() != AsyncTask.Status.FINISHED) {
thumbnailGen.cancel(true);
}
return images;
}
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imgView;
Image cached = images[position];
if (convertView == null) {
imgView = new ImageView(myContext);
imgView.setLayoutParams(new GridView.LayoutParams(100, 100));
} else {
imgView = (ImageView) convertView;
}
if (cached.thumb == null) {
imgView.setImageResource(R.drawable.ic_action_search);
imgView.setScaleType(ScaleType.CENTER);
} else {
imgView.setScaleType(ScaleType.FIT_CENTER);
imgView.setImageBitmap(cached.thumb);
saveDataInSdCard(cached.thumb,position);
}
return imgView;
}
private void cacheUpdated() {
this.notifyDataSetChanged();
}
private Bitmap loadThumb(String url) {
Bitmap thumb = null;
BitmapFactory.Options opts = new BitmapFactory.Options();
opts.inSampleSize = 4;
try {
URL u = new URL(url);
URLConnection c = u.openConnection();
c.connect();
BufferedInputStream stream = new BufferedInputStream(
c.getInputStream());
thumb = BitmapFactory.decodeStream(stream, null, opts);
stream.close();
} catch (MalformedURLException e) {
Log.e("ERROR", "malformed url: " + url);
} catch (IOException e) {
Log.e("ERROR", "An error has occurred downloading the image: "
+ url);
}
return thumb;
}
private class LoadThumbsTask extends AsyncTask<Image, Void, Void> {
/*private ProgressDialog dialog;
#Override
protected void onPreExecute() {
this.dialog = ProgressDialog.show(myContext, "Please wait",
"Downloading.....", true);
}
#Override
protected void onPostExecute(Void unused) {
//Intent for next activity
this.dialog.dismiss();
}*/
#Override
protected Void doInBackground(Image... cache) {
BitmapFactory.Options opts = new BitmapFactory.Options();
opts.inSampleSize = 4;
for (Image i : cache) {
if (isCancelled())
return null;
if (i.thumb != null)
continue;
SystemClock.sleep(500);
i.thumb = loadThumb(i.url);
publishProgress();
}
return null;
}
#Override
protected void onProgressUpdate(Void... param) {
cacheUpdated();
}
}
private String[] imageURLs = {
"http://cdn.cs76.net/2011/spring/lectures/6/imgs/img_2851.jpg",
"http://cdn.cs76.net/2011/spring/lectures/6/imgs/img_2944.jpg",
"http://cdn.cs76.net/2011/spring/lectures/6/imgs/img_2989.jpg",
"http://cdn.cs76.net/2011/spring/lectures/6/imgs/img_3005.jpg",
"http://cdn.cs76.net/2011/spring/lectures/6/imgs/img_3012.jpg",
"http://cdn.cs76.net/2011/spring/lectures/6/imgs/img_3034.jpg",
"http://cdn.cs76.net/2011/spring/lectures/6/imgs/img_3047.jpg",
"http://cdn.cs76.net/2011/spring/lectures/6/imgs/img_3092.jpg",
"http://cdn.cs76.net/2011/spring/lectures/6/imgs/img_3110.jpg",
"http://cdn.cs76.net/2011/spring/lectures/6/imgs/img_3113.jpg",
"http://cdn.cs76.net/2011/spring/lectures/6/imgs/img_3128.jpg",
"http://cdn.cs76.net/2011/spring/lectures/6/imgs/img_3160.jpg",
"http://cdn.cs76.net/2011/spring/lectures/6/imgs/img_3226.jpg",
"http://cdn.cs76.net/2011/spring/lectures/6/imgs/img_3228.jpg",};
}
CacheActivity
public class CacheActivity extends Activity {
Button btnStartProgress;
ProgressDialog progressBar;
private int progressBarStatus = 0;
private Handler progressBarHandler = new Handler();
private GridView gridview;
private long fileSize = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cache);
gridview = (GridView) findViewById(R.id.grid_view);
addListenerOnButton();
}
public void addListenerOnButton() {
btnStartProgress = (Button) findViewById(R.id.btnStartProgress);
btnStartProgress.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
progressBar = new ProgressDialog(v.getContext());
progressBar.setCancelable(true);
progressBar.setMessage("File downloading ...");
progressBar.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressBar.setProgress(0);
progressBar.setMax(100);
progressBar.show();
progressBarStatus = 0;
fileSize = 0;
new Thread(new Runnable() {
public void run() {
while (progressBarStatus < 100) {
progressBarStatus = doInBackground();
try {
Thread.sleep(7500);
} catch (InterruptedException e) {
e.printStackTrace();
}
progressBarHandler.post(new Runnable() {
public void run() {
progressBar.setProgress(progressBarStatus);
}
});
}
if (progressBarStatus >= 100) {
try {
Thread.sleep(450);
} catch (InterruptedException e) {
e.printStackTrace();
}
progressBar.dismiss();
}
}
}).start();
try {
gridview.setAdapter(new URLImageAdapter(CacheActivity.this));
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public int doInBackground() {
while (fileSize <= 1000000) {
fileSize++;
if (fileSize == 100000) {
return 10;
} else if (fileSize == 200000) {
return 20;
} else if (fileSize == 300000) {
return 30;
}else if (fileSize == 400000) {
return 40;
}else if (fileSize == 500000) {
return 50;
}else if (fileSize == 600000) {
return 60;
}else if (fileSize == 700000) {
return 70;
}else if (fileSize == 800000) {
return 80;
}else if (fileSize == 900000) {
return 90;
}
}
return 100;
}
}
set onClickListener to your imageView in getView when it get thumb image.
else {
imgView.setScaleType(ScaleType.FIT_CENTER);
imgView.setImageBitmap(cached.thumb);
saveDataInSdCard(cached.thumb,position);
//somewhat here
// and start a new activity and put file path , and your next activity there is
imgView.setOnClickListener(new OnClickListener())
{
#Override
public void onClick(View v) {
Intent intent =new Intent(context,FullScreenActivity.class)
intent.putExtra("file_path",PATH);
context.startActivity(intent);
}
});
}
And in your next activity there is a full screen imageView
in onCreate
Bundle bundle=getIntent().getExtras();
if(bundle!=null)
{
String path=bundle.getString("file_path");
imageView.setImageURI(Uri.parse(path));
}
you can create a custom alert dialog imageview with full size imageview.get image from grid view and display it in alert dialog.

Android Save Multiple Images to SDcard

I'm new to Android and Java. I have been working on my task i.e, Image Downloader. Where I have to download images with progress bar and display them in grid View. I have created two classes 1. URLImageAdapter 2. CacheActivity. Everything works fine but now I want to save those images to sd card. I have been looking on what methods and changes should be made? Any help? Thank You. I have added permission in Android Manifest File.
public class URLImageAdapter extends BaseAdapter {
private class Image {
String url;
Bitmap thumb;
}
private Image[] images;
private Context myContext;
public LoadThumbsTask thumbnailGen;
private Object previousList;
public URLImageAdapter(Context c) {
myContext = c;
thumbnailGen = new LoadThumbsTask();
if (previousList != null) {
images = (Image[]) previousList;
thumbnailGen.execute(images);
return;
}
images = new Image[imageURLs.length];
for (int i = 0, j = imageURLs.length; i < j; i++) {
images[i] = new Image();
images[i].url = imageURLs[i];
}
thumbnailGen.execute(images);
}
public int getCount() {
return images.length;
}
public Object getItem(int position) {
return images[position].url;
}
public long getItemId(int position) {
return position;
}
public Object getData() {
if (thumbnailGen != null
&& thumbnailGen.getStatus() != AsyncTask.Status.FINISHED) {
thumbnailGen.cancel(true);
}
return images;
}
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imgView;
Image cached = images[position];
if (convertView == null) {
imgView = new ImageView(myContext);
imgView.setLayoutParams(new GridView.LayoutParams(100, 100));
} else {
imgView = (ImageView) convertView;
}
if (cached.thumb == null) {
imgView.setImageResource(R.drawable.ic_action_search);
imgView.setScaleType(ScaleType.CENTER);
} else {
imgView.setScaleType(ScaleType.FIT_CENTER);
imgView.setImageBitmap(cached.thumb);
}
return imgView;
}
private void cacheUpdated() {
this.notifyDataSetChanged();
}
private Bitmap loadThumb(String url) {
Bitmap thumb = null;
BitmapFactory.Options opts = new BitmapFactory.Options();
opts.inSampleSize = 4;
try {
URL u = new URL(url);
URLConnection c = u.openConnection();
c.connect();
BufferedInputStream stream = new BufferedInputStream(
c.getInputStream());
thumb = BitmapFactory.decodeStream(stream, null, opts);
stream.close();
} catch (MalformedURLException e) {
Log.e("ERROR", "malformed url: " + url);
} catch (IOException e) {
Log.e("ERROR", "An error has occurred downloading the image: "
+ url);
}
return thumb;
}
private class LoadThumbsTask extends AsyncTask<Image, Void, Void> {
/*private ProgressDialog dialog;
#Override
protected void onPreExecute() {
this.dialog = ProgressDialog.show(myContext, "Please wait",
"Downloading.....", true);
}
#Override
protected void onPostExecute(Void unused) {
//Intent for next activity
this.dialog.dismiss();
}*/
#Override
protected Void doInBackground(Image... cache) {
BitmapFactory.Options opts = new BitmapFactory.Options();
opts.inSampleSize = 4;
for (Image i : cache) {
if (isCancelled())
return null;
if (i.thumb != null)
continue;
SystemClock.sleep(500);
i.thumb = loadThumb(i.url);
publishProgress();
}
return null;
}
#Override
protected void onProgressUpdate(Void... param) {
cacheUpdated();
}
}
private String[] imageURLs = {
"http://cdn.cs76.net/2011/spring/lectures/6/imgs/img_2851.jpg",
"http://cdn.cs76.net/2011/spring/lectures/6/imgs/img_2944.jpg",
"http://cdn.cs76.net/2011/spring/lectures/6/imgs/img_2989.jpg",
"http://cdn.cs76.net/2011/spring/lectures/6/imgs/img_3005.jpg",
"http://cdn.cs76.net/2011/spring/lectures/6/imgs/img_3012.jpg",
"http://cdn.cs76.net/2011/spring/lectures/6/imgs/img_3034.jpg",
"http://cdn.cs76.net/2011/spring/lectures/6/imgs/img_3047.jpg",
"http://cdn.cs76.net/2011/spring/lectures/6/imgs/img_3092.jpg",
"http://cdn.cs76.net/2011/spring/lectures/6/imgs/img_3110.jpg",
"http://cdn.cs76.net/2011/spring/lectures/6/imgs/img_3113.jpg",
"http://cdn.cs76.net/2011/spring/lectures/6/imgs/img_3128.jpg",
"http://cdn.cs76.net/2011/spring/lectures/6/imgs/img_3160.jpg",
"http://cdn.cs76.net/2011/spring/lectures/6/imgs/img_3226.jpg",
"http://cdn.cs76.net/2011/spring/lectures/6/imgs/img_3228.jpg",
"http://cdn.cs76.net/2011/spring/lectures/6/imgs/img_3251.jpg",
"http://cdn.cs76.net/2011/spring/lectures/6/imgs/img_3268.jpg",
"http://cdn.cs76.net/2011/spring/lectures/6/imgs/img_3275.jpg",
"http://cdn.cs76.net/2011/spring/lectures/6/imgs/img_3346.jpg",
"http://cdn.cs76.net/2011/spring/lectures/6/imgs/img_3365.jpg",
"http://cdn.cs76.net/2011/spring/lectures/6/imgs/img_3374.jpg",
"http://cdn.cs76.net/2011/spring/lectures/6/imgs/img_3385.jpg",
"http://cdn.cs76.net/2011/spring/lectures/6/imgs/img_3392.jpg", };
}
CacheActivity
public class CacheActivity extends Activity {
Button btnStartProgress;
ProgressDialog progressBar;
private int progressBarStatus = 0;
private Handler progressBarHandler = new Handler();
private GridView gridview;
private long fileSize = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cache);
gridview = (GridView) findViewById(R.id.grid_view);
addListenerOnButton();
}
public void addListenerOnButton() {
btnStartProgress = (Button) findViewById(R.id.btnStartProgress);
btnStartProgress.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
progressBar = new ProgressDialog(v.getContext());
progressBar.setCancelable(true);
progressBar.setMessage("File downloading ...");
progressBar.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressBar.setProgress(0);
progressBar.setMax(100);
progressBar.show();
progressBarStatus = 0;
fileSize = 0;
new Thread(new Runnable() {
public void run() {
while (progressBarStatus < 100) {
progressBarStatus = doInBackground();
try {
Thread.sleep(7500);
} catch (InterruptedException e) {
e.printStackTrace();
}
progressBarHandler.post(new Runnable() {
public void run() {
progressBar.setProgress(progressBarStatus);
}
});
}
if (progressBarStatus >= 100) {
try {
Thread.sleep(450);
} catch (InterruptedException e) {
e.printStackTrace();
}
progressBar.dismiss();
}
}
}).start();
try {
gridview.setAdapter(new URLImageAdapter(CacheActivity.this));
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public int doInBackground() {
while (fileSize <= 1000000) {
fileSize++;
if (fileSize == 100000) {
return 10;
} else if (fileSize == 200000) {
return 20;
} else if (fileSize == 300000) {
return 30;
}else if (fileSize == 400000) {
return 40;
}else if (fileSize == 500000) {
return 50;
}else if (fileSize == 600000) {
return 60;
}else if (fileSize == 700000) {
return 70;
}else if (fileSize == 800000) {
return 80;
}else if (fileSize == 900000) {
return 90;
}
}
return 100;
}
}
call this below methode in getView() under
imgView.setScaleType(ScaleType.FIT_CENTER);
imgView.setImageBitmap(cached.thumb);
saveDataInSdCard(cached.thumb,position);
private void saveDataInSdCard(Bitmap bt,int i) {
OutputStream fOut = null;
Uri outputFileUri;
try {
File root = new File(Environment.getExternalStorageDirectory()
+ File.separator + "urFlodername" + File.separator);
root.mkdirs();
sdImageMainDirectory = new File(root,i+"myPicName.jpg");
outputFileUri = Uri.fromFile(sdImageMainDirectory);
fOut = new FileOutputStream(sdImageMainDirectory);
} catch (Exception e) {
}
Bitmap bm =bt;
try {
bm.compress(Bitmap.CompressFormat.PNG, 100, fOut);
fOut.flush();
fOut.close();
} catch (Exception e) {
}
}
add permission
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Basically you have your downloaded image loaded into a Bitmap. So most of your work is complete. Next you need to do is
OutputStream fout = null;
File file = new File(name);
try {
fout = new FileOutputStream(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
thumb.compress(Bitmap.CompressFormat.JPEG, 100, fout);
try {
fout.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
fout.close();
}
http://negativeprobability.blogspot.in/2011/08/lazy-loading-of-images-in-listview.html
imagecursor = managedQuery(MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI, img, null,null, MediaStore.Images.Thumbnails.IMAGE_ID + "");
The above link will help you in making some better changes in your code. A common scenario is adding images to a Listview. For example, if you´re making a cocktail recipe app, you´d want a picture next to the cocktail name. Sometimes the images should be retrieved from the internet and then be displayed. Unfortunately, this is difficult to do right. If you´ve tried it, you´ve probably noticed performance hits, or some strange glitches. In this tutorial, I´ll show you how to download images and display them. We´ll also discuss some pitfalls, like recycling and concurrency.

Categories

Resources