application integration with google drive - android

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

Related

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

I am trying to upload video of phone screen recorder from my application in google drive

I am not play video on google drive which m uploading from application
this code will record screen nd store file as video nd then upload on google drive but m not able to play uploaded video on google drive provide some solution .
My code is as Below.
String email = null;
Pattern gmailPattern = Patterns.EMAIL_ADDRESS;
Account[] accounts = AccountManager.get(this).getAccounts();
for (Account account : accounts) {
if (gmailPattern.matcher(account.name).matches()) {
email = account.name;
}
}
Toast.makeText(this, "Android Device Registered Email Address: " + email, Toast.LENGTH_LONG).show();
mMediaProjectionManager = (MediaProjectionManager) getSystemService(MEDIA_PROJECTION_SERVICE);
// Connect to Google Drive
mCredential = GoogleAccountCredential.usingOAuth2(getApplicationContext(), Arrays.asList(DriveScopes.DRIVE));
mCredential.setSelectedAccountName(email);
mService = getDriveService(mCredential);
b1 = (Button) findViewById(R.id.button1);
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new LongOperation().execute();
}
});
}
#Override
public void onStart() {
super.onStart();
}
#Override
protected void onDestroy() {
super.onDestroy();
if (mRecorder != null) {
mRecorder.quit();
mRecorder = null;
}
}
private class LongOperation extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
for (int i = 0; i < 10; i++) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
Thread.interrupted();
}
}
return "Executed";
}
#Override
protected void onPreExecute() {
if (mRecorder == null) {
Intent captureIntent = mMediaProjectionManager.createScreenCaptureIntent();
startActivityForResult(captureIntent, REQUEST_CODE);
}
Log.d("result", "Starting Recording");
}
#Override
protected void onProgressUpdate(Void... values) {
}
#Override
protected void onPostExecute(String result) {
if (mRecorder != null) {
mRecorder.quit();
mRecorder = null;
Log.d("result", "Stopping Recording");
}
for (int i = 0; i < 4; i++) {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
Thread.interrupted();
}
}
saveFileToDrive();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
MediaProjection mediaProjection = mMediaProjectionManager.getMediaProjection(resultCode, data);
if (mediaProjection == null) {
Log.e("##", "media projection is null");
return;
}
String newFolder = "/FIREBASE";
String extSdcard = Environment.getExternalStorageDirectory().toString();
File file = new File(extSdcard + newFolder);
file.mkdir();
Log.d("result", "DIR:--" + file.getPath());
Log.d("result", "DIR:--" + file.mkdir());
final int width = 1280;
final int height = 720;
final int bitrate = 6000000;
if (file.exists()) {
File_Path = "record-" + width + "x" + height + "-" + System.currentTimeMillis() + ".mp4";
video_file = new File(file, File_Path);
Log.d("result", "VideoDIR:--" + video_file.getPath());
Log.d("Result", "Video file Name" + video_file);
Log.d("Result", "File Path" + File_Path);
mRecorder = new ScreenRecorder(width, height, bitrate, 1, mediaProjection, video_file.getPath());
mRecorder.start();
Toast.makeText(this, "Screen recorder is running...", Toast.LENGTH_SHORT).show();
moveTaskToBack(false);
}
}
#NonNull
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 {
// File's binary content
java.io.File fileContent = new java.io.File(video_file.getPath());
FileContent mediaContent = new FileContent("video/mp4", fileContent);
Log.d("Result", "File Content:-" + fileContent);
showToast("Selected " + fileContent + "to upload");
Log.d("Result", "File URI:-" + fileContent);
// File's meta data.
com.google.api.services.drive.model.File body = new com.google.api.services.drive.model.File();
body.setTitle(fileContent.getName());
body.setMimeType("video/mp4");
Drive.Files f1 = mService.files();
Drive.Files.Insert i1 = f1.insert(body, mediaContent);
com.google.api.services.drive.model.File file = i1.execute();
if (file != null) {
showToast("Uploaded: " + file.getTitle());
Log.d("Result", "File Titile:-" + file.getTitle());
} else {
Log.d("Result", "Else Part");
}
} catch (UserRecoverableAuthIOException e) {
Log.d("Result", "Exception" + e.toString());
} catch (IOException e) {
e.printStackTrace();
Log.d("Result", "Exception" + 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();
}
});
}

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

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

Android: using VideoView and RtpStream

I'm working with VideoView to stream a video with rtsp. I want to obtain details about it so I want to use android.net.rtp. When I call any RtpStream class's method like getLocalPort() the application doesn't work. Here is the code:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mVideoView = (VideoView) findViewById(R.id.surface_view);
mPath = (EditText) findViewById(R.id.edit_message);
text= "rtsp://192.168.1.37/sample_300kbit.mp4";
mPath.setText(text);
mPlay = (ImageButton) findViewById(R.id.play);
mPause = (ImageButton) findViewById(R.id.pause);
mReset = (ImageButton) findViewById(R.id.reset);
mStop = (ImageButton) findViewById(R.id.stop);
mPlay.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
reproducirVideo();
}
});
mPause.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
if (mVideoView != null) {
mVideoView.pause();
}
}
});
mReset.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
if (mVideoView != null) {
mVideoView.seekTo(0);
}
}
});
mStop.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
if (mVideoView != null) {
current = null;
mVideoView.stopPlayback();
}
}
});
runOnUiThread(new Runnable(){
public void run() {
reproducirVideo();
}
});
}
public void reproducirVideo() {
try {
final String path = mPath.getText().toString();
Log.v(TAG, "path: " + path);
if (path == null || path.length() == 0) {
Toast.makeText(MainActivity.this, "Campo URL vacío",
Toast.LENGTH_LONG).show();
} else {
if (path.equals(current) && mVideoView != null) {
mVideoView.start();
mVideoView.requestFocus();
return;
}
current = path;
mVideoView.setVideoPath(getDataSource(path));
mVideoView.start();
mVideoView.requestFocus();
TextView texto= (TextView) findViewById(R.id.mensaje);
InetAddress address = null;
mRtpStream.associate(InetAddress.getByAddress(new byte[] {(byte)192, (byte)168, (byte)1, (byte)37 }), 1220);
address=mRtpStream.getRemoteAddress();
String address_string = address.getHostAddress();
texto.setText(" La dirección local es "+(address_string)+" ");
}
} catch (Exception e) {
Log.e(TAG, "error: " + e.getMessage(), e);
if (mVideoView != null) {
mVideoView.stopPlayback();
}
}
}
private String getDataSource(String path) throws IOException {
if (!URLUtil.isNetworkUrl(path)) {
return path;
} else {
URL url = new URL(path);
URLConnection cn = url.openConnection();
cn.connect();
InputStream stream = cn.getInputStream();
if (stream == null)
throw new RuntimeException("stream is null");
File temp = File.createTempFile("mediaplayertmp", "dat");
temp.deleteOnExit();
String tempPath = temp.getAbsolutePath();
FileOutputStream out = new FileOutputStream(temp);
byte buf[] = new byte[128];
do {
int numread = stream.read(buf);
if (numread <= 0)
break;
out.write(buf, 0, numread);
} while (true);
try {
stream.close();
} catch (IOException ex) {
Log.e(TAG, "error: " + ex.getMessage(), ex);
}
return tempPath;
}
}
}

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