using puelocesar / android-lib-magick - android

I am a beginner in Android. I want a sample app which uses this library: https://github.com/puelocesar/android-lib-magick. I tried to use https://github.com/lilac/Android-ImageMagick before - I made lots of changes to make it work but the result I got was not satisfactory.
I just want to know which class to call for a particular thing.
These are the effects i am getting using https://github.com/lilac/Android-ImageMagick
blur, charcoal and no effect looks exactly same. when i select edge it shows blur image.
and the noise effects appear but they look like red and green dots are drawn manually on that image.
below is the code which runs application.
it searches for images in sd card with hard coded name and extention. it gets all the ibages but i am unable to understand wha it does with those images because it shows only one image on screen.
also dont know test.txt is created. this code is present in library as AndroidMagickActivity
i did some changes in android.mk file after searching for long time and now its running but the output is not that good.
please anybody help me to improve results of lilac library or help me to understand how to use https://github.com/puelocesar/android-lib-magick
i am beginner and i don't know how to use NDK and how to create JNI and .so files
package magick;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.magick.R;
import magick.util.DisplayImageMetaData;
import magick.util.MagickBitmap;
import android.util.Log;
import android.view.*;
public class AndroidMagickActivity extends Activity {
static final int PROGRESS_DIALOG = 0;
ProgressDialog progressDialog = null;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// InputStream stream = getResources().openRawResource(R.raw.app_notes);
try {
final MagickImage img = new MagickImage(new ImageInfo("/sdcard/1.jpg"));
/*
* ImageView iv = new ImageView(this);
* iv.setImageBitmap(MagickBitmap.ToBitmap(img));
* setContentView(iv);
*/
// setContentView(R.layout.main);
Spinner s = (Spinner) findViewById(R.id.spinner);
ArrayAdapter adapter = ArrayAdapter.createFromResource(this,R.array.effects, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
s.setAdapter(adapter);
s.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id) {
ProgressThread t = new ProgressThread(img, pos);
//runOnUiThread(t);
t.run();
}
public void onNothingSelected(AdapterView<?> parent) {
// Do nothing.
}
});
ImageView iv = (ImageView) findViewById(R.id.imageView);
iv.setImageBitmap(MagickBitmap.ToBitmap(img));
} catch (MagickApiException e) {
e.printStackTrace();
} catch (MagickException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
/*
* TextView tv = new TextView(this);
* tv.setText(DisplayImageMetaData.displayMagickImage(img));
* setContentView(tv);
*/
int count = 2;
MagickImage images[] = new MagickImage[count];
for (int i = 0; i < count; i++) {
String path = "/sdcard/" + String.valueOf(i + 1) + ".jpg";
try {
images[i] = new MagickImage(new ImageInfo(path));
} catch (MagickException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try {
MagickImage image = new MagickImage(images);
image.setImageFormat("gif");
String fn = Environment.getExternalStorageDirectory() + "/Pictures/test.gif";
image.setFileName(fn);
ImageInfo info = new ImageInfo(fn);
info.setMagick("gif");
//image.writeImage(info);
byte blob[] = image.imageToBlob(info);
FileOutputStream fos = new FileOutputStream(fn);
fos.write(blob);
fos.close();
FileOutputStream testOS = new FileOutputStream("/mnt/sdcard/test.txt");
testOS.write("abc".getBytes());
testOS.close();
} catch (MagickException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
protected Dialog onCreateDialog(int id, Bundle bundle) {
switch (id) {
case PROGRESS_DIALOG:
/*
* ProgressDialog dialog =
* ProgressDialog.show(AndroidMagickActivity.this, "",
* "Loading. Please wait...", true);
*/
progressDialog = new ProgressDialog(AndroidMagickActivity.this);
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.setMessage("Loading...");
return progressDialog;
// return dialog;
default:
return null;
}
}
/** Nested class that performs progress calculations (counting) */
private class ProgressThread extends Thread {
MagickImage img;
int pos;
ProgressThread(MagickImage image, int pos) {
this.img = image;
this.pos = pos;
}
public void run() {
int effect = 0;
AndroidMagickActivity.this.showDialog(PROGRESS_DIALOG);
switch (pos) {
case 1:
effect = NoiseType.UndefinedNoise;
break;
case 2:
effect = NoiseType.UniformNoise;
break;
case 3:
effect = NoiseType.GaussianNoise;
break;
case 4:
effect = NoiseType.MultiplicativeGaussianNoise;
break;
case 5:
effect = NoiseType.ImpulseNoise;
break;
case 6:
effect = NoiseType.LaplacianNoise;
break;
case 7:
effect = NoiseType.PoissonNoise;
break;
}
Bitmap bitmap = null;
try {
ImageView iv = (ImageView) findViewById(R.id.imageView);
MagickImage image = null;
if (pos < 8)
image = img.addNoiseImage(effect);
else if (pos == 9)
image = img.blurImage(5, 1);
else if (pos == 10)
image = img.charcoalImage(5, 1);
else if (pos == 11)
image = img.edgeImage(0);
if (image != null) {
bitmap = MagickBitmap.ToBitmap(image);
iv.setImageBitmap(bitmap);
}
// bitmap.recycle(); we can't do that.
AndroidMagickActivity.this.dismissDialog(PROGRESS_DIALOG);
} catch (MagickException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}

Related

App crashing due to two differnet Async Tasks?

So I have been working on this code for a while now trying to implement Google Visions into my prior app that displays an image from pixabay then tells me the tags of the photo.I had both the google vision app and pixabay app work just fine on their own. In this new version it should give me tags and the labels found by Google Visions but, whenever I activate the UP command on the sensors it crashes.
Here is my code:
import android.annotation.TargetApi;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.media.MediaPlayer;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Vibrator;
import android.speech.tts.TextToSpeech;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ImageView;
import android.widget.TextView;
import com.google.api.client.extensions.android.http.AndroidHttp;
import com.google.api.client.googleapis.json.GoogleJsonResponseException;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.services.vision.v1.Vision;
import com.google.api.services.vision.v1.VisionRequest;
import com.google.api.services.vision.v1.VisionRequestInitializer;
import com.google.api.services.vision.v1.model.AnnotateImageRequest;
import com.google.api.services.vision.v1.model.BatchAnnotateImagesRequest;
import com.google.api.services.vision.v1.model.BatchAnnotateImagesResponse;
import com.google.api.services.vision.v1.model.EntityAnnotation;
import com.google.api.services.vision.v1.model.Feature;
import com.google.api.services.vision.v1.model.Image;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import static edu.ggc.lutz.recipe.pixabaysamplerwalkthrough.R.id.tvLabels;
import static edu.ggc.lutz.recipe.pixabaysamplerwalkthrough.R.id.tvTags;
public class MainActivity extends AppCompatActivity implements SensorEventListener {
public static final String PIXABAY = "Pixabay";
private ImageView imageView;
private static PixabayQueryResult result;
private String tags;
long numberOfHits;
long selected;
float[] gravity = new float[3];
float[] accel = new float[3];
private static final float ALPHA = 0.80f; // weighing factor used by the low pass filter
private static final String TAG = "OMNI";
private static final float VERTICAL_TOL = 0.3f;
private SensorManager manager;
private long lastUpdate;
private MediaPlayer popPlayer;
private MediaPlayer backgroundPlayer;
private TextToSpeech tts;
private TextView[] tvGravity;
private TextView[] tvAcceleration;
private boolean isDown = false;
private boolean isUp = false;
private static final String CLOUD_VISION_API_KEY = "AIzaSyCt35MZjvD_3ynTbYmeUuBFyMbYrjXUmzs";
private static final String ANDROID_CERT_HEADER = "X-Android-Cert";
private static final String ANDROID_PACKAGE_HEADER = "X-Android-Package";
private static final String TAGgoogle = MainActivity.class.getSimpleName();
private TextView pixtags;
private TextView googlelab;
private String urlString;
private Bitmap bitmapT;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
pixtags= (TextView) findViewById(tvTags);
googlelab= (TextView) findViewById(tvLabels);
/* FloatingActionButton fab = (FloatingActionButton) findViewById(fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
PixabayFetchTask task = new PixabayFetchTask();
String service = "https://pixabay.com/api/";
String key = "5535853-23bc4a5e307cd5d1a5e16ebcc";
String query_params = "&editor_choice=true&safesearch=true&image_type=photo";
String urlString = service + "?key=" + key + query_params;
task.execute(urlString);
}
});*/
imageView= (ImageView) findViewById(R.id.imageView);
tts = new TextToSpeech(this, new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
int result1=0;
if(status == TextToSpeech.SUCCESS) {
result1 = tts.setLanguage(Locale.US);
}
if( result1 == TextToSpeech.LANG_MISSING_DATA || result1== TextToSpeech.LANG_NOT_SUPPORTED){
Log.e("TTS", "This Language is not supported");
}
else
{
Log.e("TTS", "Inizalization Failed");
}
}
});
//////////////////////////
manager = (SensorManager) getSystemService(SENSOR_SERVICE);
lastUpdate = System.currentTimeMillis();
backgroundPlayer = MediaPlayer.create(this, R.raw.mistsoftime4tmono);
//////////////////////////
//callCloudVision("https://pixabay.com/get/eb36b90f2df1053ed95c4518b7494395e67fe7d604b0154892f2c67da7eabc_640.jpg");
}
///////////////////////////////
#Override
protected void onResume() {
super.onResume();
manager.registerListener(this, manager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
SensorManager.SENSOR_DELAY_UI);
backgroundPlayer.start();
}
//////////////////////////////
#Override
protected void onPause() {
super.onPause();
manager.unregisterListener(this);
backgroundPlayer.pause();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
Intent intent = new Intent(this, About.class);
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
startActivity(intent);
return true;
}
return super.onOptionsItemSelected(item);
}
public static long getRandomLong(long minimum, long maximum)
{
return (long) (Math.random()* (maximum- minimum))+ minimum;
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
#Override
public void onSensorChanged(SensorEvent event) {
gravity[0] = lowPass(event.values[0], gravity[0]);
gravity[1] = lowPass(event.values[1], gravity[1]);
gravity[2] = lowPass(event.values[2], gravity[2]);
accel[0] = highPass(event.values[0], accel[0]);
accel[1] = highPass(event.values[1], accel[1]);
accel[2] = highPass(event.values[2], accel[2]);
long actualTime = System.currentTimeMillis();
if (actualTime - lastUpdate > 100) {
if (inRange(gravity[2], -9.81f, VERTICAL_TOL)) {
Log.i(TAG, "Down");
if (!isDown) {
Vibrator v = (Vibrator) this.getApplicationContext().getSystemService(Context.VIBRATOR_SERVICE);
v.vibrate(500);
PixabayFetchTask task = new PixabayFetchTask();
String service = "https://pixabay.com/api/";
String key = "5535853-23bc4a5e307cd5d1a5e16ebcc";
String query_params = "&editor_choice=true&safesearch=true&image_type=photo";
urlString = service + "?key=" + key + query_params;
task.execute(urlString);
backgroundPlayer.setVolume(0.1f, 0.1f);
tts.speak("The device is pointing down", TextToSpeech.QUEUE_FLUSH, null);
backgroundPlayer.setVolume(1.0f, 1.0f);
isDown = true;
isUp = false;
}
} else if (inRange(gravity[2], 9.81f, VERTICAL_TOL)) {
if (!isUp) {
try {
callCloudVision(urlString);
} catch (IOException e) {
e.printStackTrace();
}
backgroundPlayer.setVolume(0.1f, 0.1f);
Log.i(TAG, "Up");
tags= (String) result.getTags((int)selected);
pixtags.setText("Tags: "+tags, null);
/* Snackbar.make(imageView, tags, Snackbar.LENGTH_LONG)
.setAction("Action", null).show();*/
tts.speak(tags.toString(), TextToSpeech.QUEUE_ADD, null);
//tts.speak("up", TextToSpeech.QUEUE_FLUSH, null);
backgroundPlayer.setVolume(1.0f, 1.0f);
isUp = true;
isDown = false;
}
} else {
Log.i(TAG, "In between");
//isDown = false; // Rubbish!
//isUp = false;
}
lastUpdate = actualTime;
}
}
private boolean inRange(float value, float target, float tol) {
return value >= target-tol && value <= target+tol;
}
// de-emphasize transient forces
private float lowPass(float current, float gravity) {
return current * (1-ALPHA) + gravity * ALPHA; // ALPHA indicates the influence of past observations
}
// de-emphasize constant forces
private float highPass(float current, float gravity) {
return current - gravity;
}
class PixabayFetchTask extends AsyncTask<String, Void, PixabayQueryResult> {
/**
* Override this method to perform a computation on a background thread. The
* specified parameters are the parameters passed to {#link #execute}
* by the caller of this task.
* <p>
* This method can call {#link #publishProgress} to publish updates
* on the UI thread.
*
* #param params The parameters of the task.
* #return A result, defined by the subclass of this task.
* #see #onPreExecute()
* #see #onPostExecute
* #see #publishProgress
*/
#Override
protected PixabayQueryResult doInBackground(String... params) {
Log.v(PIXABAY,"String[0] =" + params[0]);
if(result==null || result.isExpired()) {
try {
String line;
URL u = new URL(params[0]);
HttpURLConnection conn = (HttpURLConnection) u.openConnection();
InputStream in = new BufferedInputStream(conn.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder json = new StringBuilder();
while ((line = reader.readLine()) != null) json.append(line);
result = new PixabayQueryResult(json.toString());
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
}
/**
* <p>Runs on the UI thread after {#link #doInBackground}. The
* specified result is the value returned by {#link #doInBackground}.</p>
* <p>
* <p>This method won't be invoked if the task was cancelled.</p>
*
* #param bitmap The result of the operation computed by {#link #doInBackground}.
* #see #onPreExecute
* #see #doInBackground
* #see #onCancelled(Object)
*/
#Override
protected void onPostExecute(PixabayQueryResult result) {
super.onPostExecute(result);
numberOfHits= result.size();
selected = getRandomLong(0, numberOfHits);
Bitmap bitmap= result.getBitmap((int)selected);
imageView.setImageBitmap(bitmap);
/* try {
callCloudVision(urlString);
} catch (IOException e) {
e.printStackTrace();
}*/
}
}
private void callCloudVision(final String loc) throws IOException {
// Switch text to loading
googlelab.setText(R.string.loading_message);
// Do the real work in an async task, because we need to use the network anyway
new AsyncTask<Object, Bitmap, String>() {
#Override
protected String doInBackground(Object... params) {
try {
HttpTransport httpTransport = AndroidHttp.newCompatibleTransport();
JsonFactory jsonFactory = GsonFactory.getDefaultInstance();
VisionRequestInitializer requestInitializer =
new VisionRequestInitializer(CLOUD_VISION_API_KEY) {
/**
* We override this so we can inject important identifying fields into the HTTP
* headers. This enables use of a restricted cloud platform API key.
*/
#Override
protected void initializeVisionRequest(VisionRequest<?> visionRequest)
throws IOException {
super.initializeVisionRequest(visionRequest);
String packageName = getPackageName();
visionRequest.getRequestHeaders().set(ANDROID_PACKAGE_HEADER, packageName);
String sig = PackageManagerUtils.getSignature(getPackageManager(), packageName);
visionRequest.getRequestHeaders().set(ANDROID_CERT_HEADER, sig);
}
};
Vision.Builder builder = new Vision.Builder(httpTransport, jsonFactory, null);
builder.setVisionRequestInitializer(requestInitializer);
Vision vision = builder.build();
BatchAnnotateImagesRequest batchAnnotateImagesRequest =
new BatchAnnotateImagesRequest();
batchAnnotateImagesRequest.setRequests(new ArrayList<AnnotateImageRequest>() {{
AnnotateImageRequest annotateImageRequest = new AnnotateImageRequest();
Bitmap bitmap = null;
try {
InputStream stream = new URL(loc).openStream();
bitmap = BitmapFactory.decodeStream(stream);
publishProgress(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
// Add the image
Image base64EncodedImage = new Image();
// Convert the bitmap to a JPEG
// Just in case it's a format that Android understands but Cloud Vision
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, byteArrayOutputStream);
byte[] imageBytes = byteArrayOutputStream.toByteArray();
// Base64 encode the JPEG
base64EncodedImage.encodeContent(imageBytes);
annotateImageRequest.setImage(base64EncodedImage);
// add the features we want
annotateImageRequest.setFeatures(new ArrayList<Feature>() {{
Feature labelDetection = new Feature();
labelDetection.setType("LABEL_DETECTION");
labelDetection.setMaxResults(10);
add(labelDetection);
}});
// Add the list of one thing to the request
add(annotateImageRequest);
}});
Vision.Images.Annotate annotateRequest =
vision.images().annotate(batchAnnotateImagesRequest);
// Due to a bug: requests to Vision API containing large images fail when GZipped.
annotateRequest.setDisableGZipContent(true);
Log.d(TAGgoogle, "created Cloud Vision request object, sending request");
BatchAnnotateImagesResponse response = annotateRequest.execute();
return convertResponseToString(response);
} catch (GoogleJsonResponseException e) {
Log.d(TAGgoogle, "failed to make API request because " + e.getContent());
} catch (IOException e) {
Log.d(TAGgoogle, "failed to make API request because of other IOException " +
e.getMessage());
}
return "Cloud Vision API request failed. Check logs for details.";
}
/**
* Runs on the UI thread after {#link #publishProgress} is invoked.
* The specified values are the values passed to {#link #publishProgress}.
*
* #param bitmaps The values indicating progress.
* #see #publishProgress
* #see #doInBackground
*/
#Override
protected void onProgressUpdate(Bitmap... bitmaps) {
super.onProgressUpdate(bitmaps);
imageView.setImageBitmap(bitmaps[0]);
}
protected void onPostExecute(String result) {
googlelab.setText(result);
}
}.execute();
}
private String convertResponseToString(BatchAnnotateImagesResponse response) {
String message = "Labels:\n\n";
List<EntityAnnotation> labels = response.getResponses().get(0).getLabelAnnotations();
if (labels != null) {
for (EntityAnnotation label : labels) {
message += String.format(Locale.US, "%.3f: %s", label.getScore(), label.getDescription());
message += "\n";
}
} else {
message += "nothing";
}
return message;
}
}
Here is the it gives me error:
E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #3
Process: edu.ggc.lutz.recipe.pixabaysamplerwalkthrough, PID: 21223 java.lang.RuntimeException: An error occurred while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:309)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:354)
at java.util.concurrent.FutureTask.setException(FutureTask.java:223)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
at java.lang.Thread.run(Thread.java:818)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.graphics.Bitmap.compress(android.graphics.Bitmap$CompressFormat, int, java.io.OutputStream)' on a null object reference
at edu.ggc.lutz.recipe.pixabaysamplerwalkthrough.MainActivity$2$2.<init>(MainActivity.java:419)
at edu.ggc.lutz.recipe.pixabaysamplerwalkthrough.MainActivity$2.doInBackground(MainActivity.java:400)
at edu.ggc.lutz.recipe.pixabaysamplerwalkthrough.MainActivity$2.doInBackground(MainActivity.java:366)
at android.os.AsyncTask$2.call(AsyncTask.java:295) at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234) 
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
  at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588) 
at java.lang.Thread.run(Thread.java:818)
There is another error that says something about the text to speech but I think that is the result of this error.
I believe it has something to do with running two different Async tasks at the same time overloading it or that fact a null value it getting passed in causing the error.

Show image on screen from ftp server

I almost build my android application, but i have some troubles. My app use a ftp connection to upload photos on a server and display on screen this photos. With "upload part" i have no problems, but when i choose a photo and i want to display it on screen, I encounter some problems. Seems like my image is blurred or fragmented. I think that is from redimensioning, but in this way i tried many algorithms ...unsuccessful
Please tell me how can I display on screen an image from this ftp server, image displayed at good quality without "blurred or fragmented" part, thank you
This is my "show image" class...
import java.io.BufferedInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.widget.ImageView;
#SuppressLint("NewApi")
public class FaceDetection extends Activity {
public String o;
public ImageView viu;
public Bitmap bit;
public Bitmap myBitmap;
File file;
InputStream a=null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.poza);
a=NextActivity.aa;
viu=(ImageView)findViewById(R.id.imageView1);
o=getIntent().getStringExtra("CaleOptiune");
setData(o);
initData();
bit=getBit();
viu.setImageBitmap(bit);
}
public Bitmap getBit(){
BitmapFactory.Options BitmapFactoryOptionsbfo = new BitmapFactory.Options();
BitmapFactoryOptionsbfo.inPreferredConfig = Bitmap.Config.RGB_565;
myBitmap = BitmapFactory.decodeResource(getResources(),
R.drawable.index, BitmapFactoryOptionsbfo);
if(a!=null){Log.e("asdasdsadsadas","Streamul este incarcat");}else{Log.e("asdasdsadsadas","E nullllllll");}
myBitmap = BitmapFactory.decodeStream(new BufferedInputStream(a));
return myBitmap;
}
public void initData(){
File file=new File(o);
try {
Log.e("Fisierul curent este",""+Logare.ftpClient.getWorkingDirectory());
} catch (IOException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
Log.e("File","Fisier creat din calea "+o);
Log.e("File name",""+file.getName());
try {
a = Logare.ftpClient.ftpClient.retrieveFileStream(file.getName());
Logare.ftpClient.ftpClient.completePendingCommand();
} catch (Exception e1) {
Log.e("asdasdsadsadas","Nu s-a instantiat InputSteamul");
}
}
public void setData(String o) {
this.o = o;
}
}
Decoding and showing images seems to be OK. You could improve it by Loading Large Bitmaps Efficiently.
I'm not sure, but I think your problem should be this issue: https://code.google.com/p/android/issues/detail?id=6066
Try to create class:
public class FlushedInputStream extends FilterInputStream {
public FlushedInputStream(InputStream inputStream) {
super(inputStream);
}
#Override
public long skip(long n) throws IOException {
long totalBytesSkipped = 0L;
while (totalBytesSkipped < n) {
long bytesSkipped = in.skip(n - totalBytesSkipped);
if (bytesSkipped == 0L) {
int by_te = read();
if (by_te < 0) {
break; // we reached EOF
} else {
bytesSkipped = 1; // we read one byte
}
}
totalBytesSkipped += bytesSkipped;
}
return totalBytesSkipped;
}
}
and use:
bm = BitmapFactory.decodeStream(new FlushedInputStream(entity.getContent()));

Youtube upload videos programmatically

i have for the passed 4 days tried to upload to youtube videos but i have failed please help me .
package com.example.testyoutube;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import com.google.gdata.client.youtube.YouTubeService;
import com.google.gdata.data.media.MediaFileSource;
import com.google.gdata.data.media.mediarss.MediaCategory;
import com.google.gdata.data.media.mediarss.MediaDescription;
import com.google.gdata.data.media.mediarss.MediaKeywords;
import com.google.gdata.data.media.mediarss.MediaTitle;
import com.google.gdata.data.youtube.VideoEntry;
import com.google.gdata.data.youtube.YouTubeMediaGroup;
import com.google.gdata.data.youtube.YouTubeNamespace;
import com.google.gdata.util.AuthenticationException;
import com.google.gdata.util.ServiceException;
public class MainActivity extends Activity {
private Button button;
private YouTubeService service;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.button);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
submitVideo("/storage/emulated/0/Pictures/Hello Camera/VID_20140523_204750.mp4",
"i have done it ", "Yooooooooo , it works", "fun");
}
});
}
public void submitVideo(String vName, String vTitle, String vDesc, String vCate) {
String developer_key = "api key"; // Registered developer key
String clientID = "gmailaccount"; // Server's Youtube account
String password = "passwordofgmailaccount"; // Server's Youtube password
service = new YouTubeService(clientID, developer_key); // YouTube Object, we take action by this.
try {
service.setUserCredentials(clientID,password);
} catch (AuthenticationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
File videoFile = new File( vName ); // The video local file prepare to upload
String VIDEO_UPLOAD_FEED = "http://uploads.gdata.youtube.com/feeds/api/users/default/uploads";
String mediaType = "video/*"; // Serach .flv MIME type may found more
String vKey1 = vCate; // Use same category and keyword
VideoEntry newEntry = new VideoEntry(); // YouTube video object type, they will return this after uploaded
YouTubeMediaGroup mg = newEntry.getOrCreateMediaGroup(); // Collect all of the video information
mg.addCategory(new MediaCategory(YouTubeNamespace.CATEGORY_SCHEME, vCate));
mg.setTitle(new MediaTitle());
mg.getTitle().setPlainTextContent(vTitle);
mg.setDescription(new MediaDescription());
mg.getDescription().setPlainTextContent(vDesc);
mg.setKeywords(new MediaKeywords());
mg.getKeywords().addKeyword(vKey1);
MediaFileSource ms = new MediaFileSource(videoFile, mediaType);
newEntry.setMediaSource(ms);
VideoEntry ve = null;
try {
ve = service.insert(new URL(VIDEO_UPLOAD_FEED), newEntry);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ServiceException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(ve == null){
System.out.println("Submit to youtube fail.");
return ;
}
}
}
it says that this "service = new YouTubeService(clientID, developer_key);" has error but it does not explain why , please help (or suggest another code please)
U can ddo it using Intent
ContentValues content = new ContentValues(4);
content.put(Video.VideoColumns.DATE_ADDED,
System.currentTimeMillis() / 1000);
content.put(Video.Media.MIME_TYPE, "video/mp4");
content.put(MediaStore.Video.Media.DATA, "video_path");
ContentResolver resolver = getBaseContext().getContentResolver();
Uri uri = resolver.insert(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, content);
Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT,"Title");
sharingIntent.putExtra(android.content.Intent.EXTRA_STREAM,uri);
startActivity(Intent.createChooser(sharingIntent,"share:"));

Synchronize Dialog Boxes

I have a broadcast receiver that on boot of the phone runs a pending intent. The pending intent opens a dialog box to alert the user.
I noticed that if there are several dialog boxes who's time has passed, they all fire off at once. Which leads to only the first dialog box displayed. When you click on the 'dismiss' button the it dismisses all the dialog boxes.
Is there a way to for each box to be displayed one at a time and not jam up like this?
I read up on using 'synchronize' but it seems to be only used in networking. Can you let me know what would be the best approach to resolving this issue?
My code:
package com.google.android.gcm.demo.app.Alerts;
import java.io.IOException;
import com.google.android.gcm.demo.app.DemoActivity;
import com.google.android.gcm.demo.app.PreferenceConnector;
import com.google.android.gcm.demo.app.R;
import com.google.android.gcm.demo.app.TabBarExample;
import com.google.android.gcm.demo.app.sqllite.DatabaseSqlite;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.AssetFileDescriptor;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Vibrator;
public class AlertDialogActivity extends Activity {
MediaPlayer player = new MediaPlayer();
Bundle bundle;
Vibrator vibrate;
DatabaseSqlite entry = new DatabaseSqlite(AlertDialogActivity.this);
int vibrateState;
int soundState;
AlertDialog.Builder builder;
Intent intent;
int idInteger;
int alertDismissed = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
bundle = getIntent().getExtras();
String name = bundle.getString("name");
String id = bundle.getString("id");
idInteger = Integer.parseInt(id);
intent = new Intent(AlertDialogActivity.this, TabBarExample.class);
sound();
vibrate();
entry.open();
entry.updateAlertDismissedState(idInteger, alertDismissed);
String text = entry.getMinutesForOneShot(idInteger);
entry.close();
String textForDisplay = "In " + text + " Minutes";
builder = new AlertDialog.Builder(this);
builder.setMessage(textForDisplay)
.setTitle(name)
.setCancelable(false)
.setNegativeButton("Dismiss",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
soundState = PreferenceConnector.readInteger(
AlertDialogActivity.this,
PreferenceConnector.SOUND_ON_OFF, 0);
if (soundState == 0) {
player.pause();
player.release();
}
vibrateState = PreferenceConnector.readInteger(
AlertDialogActivity.this,
PreferenceConnector.VIBRATE_ON_OFF, 0);
if (vibrateState == 0) {
vibrate.cancel();
}
startActivity(intent);
}
});
AlertDialog alert = builder.create();
alert.show();
}
#Override
protected void onDestroy() {
super.onDestroy();
}
private void sound() {
soundState = PreferenceConnector.readInteger(AlertDialogActivity.this,
PreferenceConnector.SOUND_ON_OFF, 0);
if (soundState == 0) {
// play sound
AssetFileDescriptor afd = this.getResources().openRawResourceFd(
R.raw.alarm_clock);
try {
player.setDataSource(afd.getFileDescriptor(),
afd.getStartOffset(), afd.getLength());
afd.close();
player.setAudioStreamType(AudioManager.STREAM_ALARM);
player.setLooping(true);
player.prepare();
player.start();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {
}
}
private void vibrate() {
vibrateState = PreferenceConnector
.readInteger(AlertDialogActivity.this,
PreferenceConnector.VIBRATE_ON_OFF, 0);
if (vibrateState == 0) {
// Get instance of Vibrator from current Context
vibrate = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
// Start immediately
// Vibrate for 200 milliseconds
// Sleep for 500 milliseconds
long[] pattern = { 0, 200, 500 };
// The "0" means to repeat the pattern starting at the beginning
// CUIDADO: If you start at the wrong index (e.g., 1) then your
// pattern will be off --
// You will vibrate for your pause times and pause for your vibrate
// times !
vibrate.vibrate(pattern, 0);
} else {
}
}
}
In order to resolve this issue, I compared the current date to when the alert fired off. If the alert passed I, I put it in an arrary list. Then I used a intent to send the list to another activity. In that activity, I used a another for loop to process the dialog boxes one at a time.

Getting force close error in android when using threading

In my application i want to do bluetooth chat. I'm facing a problem in threading. In my application my android phone will work as server which has a blocking statement
socket=mServerSocket.accept();
for this purpose i've created a child thread so that it will run separately. But before finishing this child thread main thread goes down giving Force Close and if i use the .join() method it hangs up my UI.
What is the solution to run both threads parallel?
this is my code
main Activity
package com.my.bluechat_2_1;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class BlueChat extends Activity {
/** Called when the activity is first created. */
private BlueHandler btHandler=null;
private BluetoothAdapter btAdapter = null;
private Context context=this;
TextView chatWindow=null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
chatWindow=(TextView)findViewById(R.id.textView1);
doStart();
}
private void doStart(){
Button btnStart=(Button)findViewById(R.id.button1);
btnStart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// Get local Bluetooth adapter
btAdapter = BluetoothAdapter.getDefaultAdapter();
// If the adapter is null, then Bluetooth is not supported
if(btAdapter == null)
{
Toast.makeText(context, "Device does not support Bluetooth", Toast.LENGTH_LONG).show();
}
if (!btAdapter.isEnabled()) {
Intent discoverableIntent = new
Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
startActivity(discoverableIntent);
}
chatWindow.append("Waiting for connection...\n");
btHandler=new BlueHandler(context,chatWindow,btAdapter);
Thread acceptThread=new Thread(btHandler);
acceptThread.start();
}
});
}
}
BlueHandler
package com.my.bluechat_2_1;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.UUID;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.content.Context;
import android.widget.TextView;
import android.widget.Toast;
public class BlueHandler implements Runnable{
// Name for the SDP record when creating server socket
private static final String SMARTCAM_BT_SERVICE_NAME = "SmartCam";
// Unique UUID for this application
private static final UUID SMARTCAM_BT_SERVICE_UUID = UUID.fromString("95b82690-4c94-11e1-b86c-0800200c9a66");
private BluetoothAdapter btAdapter = null;
private BluetoothServerSocket btServerSocket = null;
private BluetoothSocket btSocket = null;
private InputStream btInputStream=null;
private Context contextObj=null;
private TextView textView;
public BlueHandler(Context contextObj,TextView textView,BluetoothAdapter btAdapter){
this.contextObj=contextObj;
this.btAdapter=btAdapter;
this.textView=textView;
try {
btServerSocket=this.btAdapter.listenUsingRfcommWithServiceRecord(SMARTCAM_BT_SERVICE_NAME, SMARTCAM_BT_SERVICE_UUID);
} catch (IOException e) {
// TODO Auto-generated catch block
Toast.makeText(this.contextObj, "Service not created", Toast.LENGTH_LONG);
}
}
#Override
public void run() {
// TODO Auto-generated method stub
textView.append("Inside child thread.\n");
textView.append(btServerSocket+"\n");
while (true) {
try {
btSocket = btServerSocket.accept();
} catch (IOException e) {
break;
}
// If a connection was accepted
if (btSocket != null) {
// Do work to manage the connection (in a separate thread)
try {
btServerSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
break;
}
}
textView.append("Connected.\n");
try {
btInputStream=btSocket.getInputStream();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
byte[] buffer = new byte[1024]; // buffer store for the stream
String s;
int bytes; // bytes returned from read()
// Keep listening to the InputStream until an exception occurs
while (true) {
try {
// Read from the InputStream
bytes=btInputStream.read(buffer);
s= new String(buffer);
// Send the obtained bytes to the UI Activity
textView.append("received ::" +s+"\n");
} catch (IOException e) {
break;
}
}
}
}
You're probably getting a crash because you're accessing a textView on the worker thread. You'll need to use TextView.post(Runnable) to make that not happen.
In reality you should be using a bindable Service to do this kind of work. You can post back to the UI via broadcast intents or callback methods, That way you don't have to worry about rotation bugs.
Are you performing a long operation in the constructor of your children thread? Each long operation must be done in the run() method.

Categories

Resources