Unexplained Android Intent Behaviour - java

im adding a camera scanning facility to a project of mine. Im using the following github https://github.com/jhansireddy/AndroidScannerDemo project
im attempting to call it from within an onclicklistener which is set within an adaptor i wrote
here is my onclicklistener
imgCamera.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Intent intent = new Intent(context, ScanActivity.class);
// ((Activity) context).startActivity(intent);
Intent intent =new Intent(context, ScanAdaptor.class);
}
}
i want it to call a class i wrote which uses startactivityforresult :
public class ScanAdaptor extends Activity {
private Context context;
private static final int REQUEST_CODE = 99;
String ba1;
public String URL = "http:";
#Override
public void onCreate(Bundle savedInstanceState) {
int REQUEST_CODE = 99;
int preference = ScanConstants.OPEN_CAMERA;
Intent intent = new Intent(this, ScanActivity.class);
intent.putExtra(ScanConstants.OPEN_INTENT_PREFERENCE, preference);
startActivityForResult(intent, REQUEST_CODE);
context = this;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE && resultCode == Activity.RESULT_OK) {
Uri uri = data.getExtras().getParcelable(ScanConstants.SCANNED_RESULT);
Bitmap bitmap = null;
try {
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
getContentResolver().delete(uri, null, null);
// scannedImageView.setImageBitmap(bitmap);
upload(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
private Bitmap convertByteArrayToBitmap(byte[] data) {
return BitmapFactory.decodeByteArray(data, 0, data.length);
}
private void upload(Bitmap bm) {
// Image location URL
ByteArrayOutputStream bao = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 90, bao);
byte[] ba = bao.toByteArray();
int flag = 0;
ba1 = Base64.encodeToString(ba, flag);
Log.e("base64", "-----" + ba1);
// Upload image to server
new uploadToServer().execute();
}
public class uploadToServer extends AsyncTask<Void, Void, String> {
private ProgressDialog pd = new ProgressDialog(((Activity) context));
protected void onPreExecute() {
super.onPreExecute();
pd.setMessage("Wait image uploading!");
pd.show();
}
#Override
protected String doInBackground(Void... params) {
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("base64", ba1));
nameValuePairs.add(new BasicNameValuePair("ImageName", System.currentTimeMillis() + ".jpg"));
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(URL);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
String st = EntityUtils.toString(response.getEntity());
Log.v("log_tag", "In the try Loop" + st);
} catch (Exception e) {
Log.v("log_tag", "Error in http connection " + e.toString());
}
return "Success";
}
protected void onPostExecute(String result) {
super.onPostExecute(result);
pd.hide();
pd.dismiss();
Intent myIntent = new Intent(((Activity) context), MainActivity.class);
myIntent.putExtra("dir", "BS"); //Optional parameters
((Activity) context).startActivity(myIntent);
}
}
}
when this is the config nothing happens when you press the button.
its driving me mad, please help

Your onClick method doesn't launch the activity, it just creates the intent. Try this:
imgCamera.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(context, ScanAdaptor.class);
((Activity) context).startActivity(intent);
}
}

Related

How to write code to automatically open a new activity, from the result of an API?

I am very new to this. This is my first app, so I don't know all of the terms, or even how to explain it properly. But I am creating an affective app in Android Studio using Microsoft Cognitive API to test images to see what emotion the individuals in them display (happy, sad, neutral) then displaying the result as a text output.
I am wondering how to write code so that if the resulting text is 'neutral', the user is automatically sent to the activity_body activity, or else if the result is 'happiness', the user is automatically sent to the activity_mind activity. [](https://i.stack.imgur.com/m5ZpU.png)
package com.example.breastiesapp;
import...
public class MainActivity extends AppCompatActivity {
public Button button;
private ImageView imageView;
private TextView resultText;
private static final int REQUEST_CAMERA_CODE = 300;
private static final int REQUEST_PERMISSION_CODE = 200;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = findViewById(R.id.imageView);
resultText = findViewById(R.id.resultText);
/**
* this takes the user to the body activity
*/
button = (Button) findViewById(R.id.bodyBTN);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, BodyActivity.class);
startActivity(intent);
}
});
/**
* this takes the user to the Mind activity
*/
button = (Button) findViewById(R.id.mindBTN);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, MindActivity.class);
startActivity(intent);
}
});
}
public void getImage(View view) {
if(checkPermission()) {
Intent choosePhotoIntent = new Intent(Intent.ACTION_GET_CONTENT);
choosePhotoIntent.setType("image/*");
launchGalleryImageGetter.launch(choosePhotoIntent);
}
else {
requestPermission();
}
}
ActivityResultLauncher<Intent> launchGalleryImageGetter
= registerForActivityResult(
new ActivityResultContracts
.StartActivityForResult(),
result -> {
if (result.getResultCode()
== Activity.RESULT_OK) {
Intent data = result.getData();
if (data != null
&& data.getData() != null) {
Uri selectedImageUri = data.getData();
Bitmap selectedImageBitmap;
try {
selectedImageBitmap
= MediaStore.Images.Media.getBitmap(
this.getContentResolver(),
selectedImageUri);
imageView.setImageBitmap(selectedImageBitmap);
}
catch (IOException e) {
e.printStackTrace();
}
}
}
});
ActivityResultLauncher<Intent> launchCameraGetter
= registerForActivityResult(
new ActivityResultContracts
.StartActivityForResult(),
result -> {
if (result.getResultCode()
== Activity.RESULT_OK) {
Intent data = result.getData();
if (data != null
&& data.getData() != null) {
Bitmap takenImageBitmap;
takenImageBitmap
= (Bitmap) data.getExtras().get("data");
imageView.setImageBitmap(takenImageBitmap);
}
}
});
public void getEmotion(View view) {
final String TAG = "getEmotion";
Log.i(TAG, "example printing to logcat from getEmotion()");
GetEmotionCall emotionCall = new GetEmotionCall(imageView);
emotionCall.execute();
}
private void requestPermission() {
ActivityCompat.requestPermissions(MainActivity.this,new String[]{Manifest.permission.READ_EXTERNAL_STORAGE,Manifest.permission.CAMERA}, REQUEST_PERMISSION_CODE);
}
private boolean checkPermission() {
int result = ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.READ_EXTERNAL_STORAGE);
int result2 = ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.CAMERA);
return result == PackageManager.PERMISSION_GRANTED && result2 == PackageManager.PERMISSION_GRANTED;
}
public void getCameraImage(View view) {
if(checkPermission()) {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
//startActivityForResult(takePictureIntent, REQUEST_CAMERA_CODE);
launchCameraGetter.launch(takePictureIntent);
}
}
else {
requestPermission();
}
}
private class GetEmotionCall extends AsyncTask<Void, Void, String> {
private final ImageView img;
GetEmotionCall(ImageView img) {
this.img = img;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
resultText.setText("Getting results...");
}
#Override
protected String doInBackground(Void... params) {
// set up a http client for making the API call
HttpClient httpclient = HttpClients.createDefault();
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
try {
// this URI comes from the API itself and can be modified to change what is requested
org.apache.hc.core5.net.URIBuilder builder = new URIBuilder("https://canadacentral.api.cognitive.microsoft.com/face/v1.0/detect?returnFaceId=false&returnFaceLandmarks=false&returnFaceAttributes=emotion,age,gender,headPose,smile,facialHair,glasses,hair,makeup&recognitionModel=recognition_01&returnRecognitionModel=false&detectionModel=detection_01");
//URIBuilder builder = new URIBuilder("https://canadacentral.api.cognitive.microsoft.com/face/v1.0/detect?returnFaceId=true&returnFaceLandmarks=false&returnFaceAttributes=emotion,age,gender,headPose,smile,facialHair,glasses,hair,makeup&recognitionModel=recognition_01&returnRecognitionModel=false&detectionModel=detection");
URI uri = builder.build();
// make a new POST request since we need to send our image to the API server
org.apache.hc.client5.http.classic.methods.HttpPost request = new HttpPost(uri);
// required type for uploading a file
request.setHeader("Content-Type", "application/octet-stream");
// enter your subscription key here
request.setHeader("Ocp-Apim-Subscription-Key", "0d3836e987594b01856f42d");
// Request body. setEntity method converts the image to base64
request.setEntity(new ByteArrayEntity(toBase64(img), ContentType.APPLICATION_OCTET_STREAM));
// getting a response and assigning it to the string res
ClassicHttpResponse response = (ClassicHttpResponse) httpclient.execute(request);
Log.i("doInBackground", response.toString());
HttpEntity entity = response.getEntity();
String res = EntityUtils.toString(entity);
Log.i("doInBackground",res);
return res;
}
catch (Exception e){
return "null";
}
}
#Override
protected void onPostExecute(String result) {
JSONArray jsonArray = null;
try {
jsonArray = new JSONArray(result);
String emotions = "";
for(int i = 0;i<jsonArray.length();i++) {
JSONObject jsonParentObject = new JSONObject(jsonArray.get(i).toString());
JSONObject jsonObject = jsonParentObject.getJSONObject("faceAttributes");
JSONObject scores = jsonObject.getJSONObject("emotion");
double max = 0;
String emotion = "";
for (int j = 0; j < scores.names().length(); j++) {
if (scores.getDouble(scores.names().getString(j)) > max) {
max = scores.getDouble(scores.names().getString(j));
emotion = scores.names().getString(j);
}
}
emotions += emotion + "\n";
}
resultText.setText(emotions);
} catch (JSONException e) {
resultText.setText("No emotion detected. Try again later");
}
}
}
public byte[] toBase64(ImageView imgPreview) {
Bitmap bm = ((BitmapDrawable) imgPreview.getDrawable()).getBitmap();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 100, baos); //bm is the bitmap object
return baos.toByteArray();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CAMERA_CODE && resultCode == RESULT_OK) {
Bitmap photo = (Bitmap) data.getExtras().get("data");
imageView.setImageBitmap(photo);
}
}
}
Put the if conditions in you try block when emotions are retrived and then based on conditions you can navigate to other activities
try {
jsonArray = new JSONArray(result);
String emotions = "";
for(int i = 0;i<jsonArray.length();i++) {
JSONObject jsonParentObject = new JSONObject(jsonArray.get(i).toString());
JSONObject jsonObject = jsonParentObject.getJSONObject("faceAttributes");
JSONObject scores = jsonObject.getJSONObject("emotion");
double max = 0;
String emotion = "";
for (int j = 0; j < scores.names().length(); j++) {
if (scores.getDouble(scores.names().getString(j)) > max) {
max = scores.getDouble(scores.names().getString(j));
emotion = scores.names().getString(j);
}
}
emotions += emotion + "\n";
}
resultText.setText(emotions);
if(emotions=="neutral"){
Intent intent = new Intent(MainActivity.this,activity_body.class);
startActivity(intent);
}
else if(emotions=="happiness") {
Intent intent = new Intent(MainActivity.this,activity_mind.class);
startActivity(intent);
}
}
catch (JSONException e) {
resultText.setText("No emotion detected. Try again later");
}

HTTP post from Android app to web service in Python Flask

I need to send a Base64 string from Android application to a Python web service using HTTP post.
I want to receive the string and return it on the webpage but the problem is that I can't receive the string.
On Android side, I chose a file from storage and encoded it in base64 string. Then, I used Volley to make the HTTP post request.
On the other side, I used Flask to build up the web service.
This is the MainActivity of my Android application:
public class MainActivity extends AppCompatActivity {
Button button1;
Intent intent;
TextView text;
private static final int READ_REQUEST_CODE = 42;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button1 = findViewById(R.id.button1);
text = findViewById(R.id.text);
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.setType("application/vnd.android.package-archive");
startActivityForResult(intent, READ_REQUEST_CODE);
}
});
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == READ_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
Uri uri = null;
uri = data.getData();
//Toast.makeText(MainActivity.this, uri.toString(), Toast.LENGTH_LONG).show();
try {
final String conv = readTextFromUri(uri);
//text.setText(conv);
////////REQUEST////////
RequestQueue queue = Volley.newRequestQueue(this);
String url = "http://10.0.2.2:5000";
StringRequest postRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>()
{
#Override
public void onResponse(String response) {
// response
text.setText("Response is: "+ response.substring(0,500));
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error) {
// error
text.setText("That didn't work!");
}
}
) {
#Override
protected Map<String, String> getParams()
{
Map<String, String> params = new HashMap<String, String>();
params.put("conv", conv);
return params;
}
};
queue.add(postRequest);
////////END_REQUEST////////
}
catch (IOException e) {
}
}
}
////////ENCODE/////////
private String readTextFromUri(Uri uri) throws IOException {
InputStream inputStream = getContentResolver().openInputStream(uri);
byte[] buffer = new byte[8192];
int bytesRead;
ByteArrayOutputStream output = new ByteArrayOutputStream();
Base64OutputStream output64 = new Base64OutputStream(output, Base64.DEFAULT);
try {
while ((bytesRead = inputStream.read(buffer)) != -1) {
output64.write(buffer, 0, bytesRead);
}
} catch (IOException e) {
e.printStackTrace();
}
output64.close();
String attachedFile = output.toString();
return attachedFile;
}
////////THE END OF ENCODE////////
}
While, this is my Web Service in Python:
from flask import Flask, request
app = Flask(__name__)
#app.route('/', methods=['GET','POST'])
def call_cortex():
if request.method == 'POST':
fileb64 = request.form['conv']
return fileb64
else:
return 'Errore!'
At the moment, results are:
Android application shows
Response is + (part of base64 string)
Web Service shows "Errore!" that is
Method Not Allowed

Download pictures using a service

I'm trying to download pictures in the background of an app using Service (not IntentSevice)
Somehow, my code doesn't work.
I set permissions for Internet and Storage in the Manifest.
I'm thankful for any comments or answers (:
Here's my code:
For the Service and then for the MainActivity
i have already tried different links or httpURLConnection instead of the normal URL connection but that doesnt't work either.
when I run the app, it always shows my "error" toast. it doesn't even get to the Input Stream.
public class Download extends Service {
public static final String URL = "url";
public static final String FILENAME = "name";
public static final String FILEPATH = "path";
public static final String RESULT = "result";
public static final String NOTIFICATION = "notification";
public ImageView imageView1 ;
#Override
public IBinder onBind(Intent arg0){
// TODO Auto-generated method stub
return null;
}
public void onCreate(){
super.onCreate();
Toast.makeText(this,"Service is created",Toast.LENGTH_LONG).show();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId){
String urlPath = intent.getStringExtra(FILEPATH);
String fileName = intent.getStringExtra(FILENAME);
int result = Activity.RESULT_CANCELED;
try {
Toast.makeText(this, "Service started", Toast.LENGTH_LONG).show();
final URL fileUrl = new URL(urlPath);
HttpURLConnection urlConnection = (HttpURLConnection) fileUrl.openConnection();
final InputStream inputStream = new BufferedInputStream(urlConnection.getInputStream());
Toast.makeText(this, "connected", Toast.LENGTH_LONG).show();
//Toast.makeText(this, "connected", Toast.LENGTH_LONG).show();
File downloadordner = new File(Environment.getExternalStorageDirectory() + "/Pictures");
if (!downloadordner.exists()) {
downloadordner.mkdirs();
}
File downloadedfile = new File(downloadordner, "Bild1" + System.currentTimeMillis() + ".png");
OutputStream outputStream = new FileOutputStream(downloadedfile);
try {
byte[] buffer = new byte[1024];
int read;
while ((read = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, read);
}
result = Activity.RESULT_OK;
}finally{
outputStream.flush();
outputStream.close();
inputStream.close();
}
} catch (Exception e){
e.printStackTrace();
Toast.makeText(this,"Fehler",Toast.LENGTH_LONG).show();
}
publishResults(result);
return START_STICKY;
}
private void publishResults(int result){
Intent intent = new Intent(NOTIFICATION);
intent.putExtra(RESULT,result);
sendBroadcast(intent);
}
#Override
public void onDestroy(){
super.onDestroy();
Toast.makeText(this,"Service Stopped", Toast.LENGTH_LONG).show();
System.exit(0);
}
}
public class MainActivity extends AppCompatActivity {
Button btn1;
Button btn2;
ProgressBar progbar1;
public ImageView imageView1;
private TextView downloadStatus; //neu
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
downloadStatus = (TextView) findViewById(R.id.download_status);
progbar1 = (ProgressBar) findViewById(R.id.progbar1);
btn1 = (Button) findViewById(R.id.go);
btn2 = (Button) findViewById(R.id.kill);
imageView1 = (ImageView) findViewById(R.id.bild1);
btn1.setOnClickListener(onDownloadListener());
btn2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
stopService(new Intent(getBaseContext(), Download.class));
System.exit(0);
}
});
}
private View.OnClickListener onDownloadListener(){
return new View.OnClickListener() {
#SuppressLint("SetTextI18n")
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this,Download.class);
intent.putExtra(Download.FILENAME,"logo.png");
intent.putExtra(Download.FILEPATH,"https://de.wikipedia.org/wiki/Kleiner_Eisvogel#/media/File:Limenitis_camilla3.jpg");
startService(intent);
downloadStatus.setText("Downloading....");
Toast.makeText(MainActivity.this, "downloading", Toast.LENGTH_LONG).show();
}
};
}
private BroadcastReceiver receiver = new BroadcastReceiver() {
#SuppressLint("SetTextI18n")
#Override
public void onReceive(Context context, Intent intent) {
Bundle bundle = intent.getExtras();
if(bundle != null){
int resultCode = bundle.getInt(Download.RESULT);
if (resultCode == RESULT_OK){
Toast.makeText(MainActivity.this,"File downloaded",Toast.LENGTH_LONG).show();
downloadStatus.setText("Download completed");
}else{
Toast.makeText(MainActivity.this,"Error",Toast.LENGTH_LONG).show();
downloadStatus.setText("Download failed");
}
}
}
};
}
Service runs on the main thread so there is a network exception NO networking is allowed on the main thread.

prevent image encoding in java

I have code to upload image and text to the server, but my code encodes the image and in the server the image should be decoded.
I want to prevent image encoding. I've tried some ways but they're not working.
I don't know how to do this. Please help me.
Here is my code:
public class Share_food extends Activity {
ProgressDialog prgDialog;
String encodedString;
RequestParams params = new RequestParams();
String imgPath, fileName;
Bitmap bitmap;
private static int RESULT_LOAD_IMG = 1;
EditText ti,desc;
TextView tv;
String url="http://example.com/index.php";
#SuppressLint("CutPasteId")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.share_food);
prgDialog = new ProgressDialog(this);
prgDialog.setCancelable(false);
ti= (EditText)findViewById(R.id.title);
desc=(EditText)findViewById(R.id.share_desc22);
//getActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#3b5998")));
//getActionBar().setIcon( new ColorDrawable(getResources().getColor(android.R.color.transparent)));
//getActionBar().setTitle("");
}
public void loadImagefromGallery(View view) {
Intent galleryIntent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent, RESULT_LOAD_IMG);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try {
if (requestCode == RESULT_LOAD_IMG && resultCode == RESULT_OK
&& null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
imgPath = cursor.getString(columnIndex);
cursor.close();
ImageView imgView = (ImageView) findViewById(R.id.imgView);
imgView.setImageBitmap(BitmapFactory
.decodeFile(imgPath));
String fileNameSegments[] = imgPath.split("/");
fileName = fileNameSegments[fileNameSegments.length - 1];
params.put("filename", fileName);
} else {
Toast.makeText(this, "error",
Toast.LENGTH_LONG).show();
imgPath="2";
}
} catch (Exception e) {
Toast.makeText(this, "error...!", Toast.LENGTH_LONG)
.show();
}
}
public void uploadImage(View v) {
if (imgPath != null && !imgPath.isEmpty()) {
prgDialog.setMessage("process");
prgDialog.show();
encodeImagetoString();
} else {
prgDialog.setMessage("process");
prgDialog.show();
triggerImageUpload();
}
}
public void encodeImagetoString() {
new AsyncTask<Void, Void, String>() {
protected void onPreExecute() {
};
#Override
protected String doInBackground(Void... params) {
BitmapFactory.Options options = null;
options = new BitmapFactory.Options();
options.inSampleSize = 3;
bitmap = BitmapFactory.decodeFile(imgPath,
options);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 50, stream);
byte[] byte_arr = stream.toByteArray();
encodedString = Base64.encodeToString(byte_arr, 0);
return "";
}
#Override
protected void onPostExecute(String msg) {
prgDialog.setMessage("upload");
params.put("title", ti.getText().toString().trim());
//desc
//params.put("desc",desc.getText().toString().trim());
params.put("image", encodedString);
triggerImageUpload();
}
}.execute(null, null, null);
}
public void triggerImageUpload() {
params.put("title", ti.getText().toString().trim());
//desc
//params.put("desc", desc.getText().toString().trim());
makeHTTPCall();
}
public void makeHTTPCall() {
prgDialog.setMessage("connecting");
AsyncHttpClient client = new AsyncHttpClient();
client.post(url,
params, new AsyncHttpResponseHandler() {
#Override
public void onSuccess(String response) {
prgDialog.hide();
Toast.makeText(getApplicationContext(), "done",
Toast.LENGTH_LONG).show();
}
#Override
public void onFailure(int statusCode, Throwable error,
String content) {
prgDialog.hide();
if (statusCode == 404) {
Toast.makeText(getApplicationContext(),
"error",
Toast.LENGTH_LONG).show();
}
else if (statusCode == 500) {
Toast.makeText(getApplicationContext(),
"error",
Toast.LENGTH_LONG).show();
}
else {
Toast.makeText(
getApplicationContext(),
"error !!!"
+ statusCode, Toast.LENGTH_LONG)
.show();
}
}
});
}
#Override
protected void onDestroy() {
super.onDestroy();
if (prgDialog != null) {
prgDialog.dismiss();
}
}
}
you have to decode the string in receiving end and save the decoded one. post the code of receiving end too for more convenience.

Android Saved images are low quality

I'm taking pictures through the following code and saving to SD card, but the pictures that it produces are such low quality and really bitty even with 100% quality. Maybe bitmap.compress isn't the right way to go (or bitmap at all?!)
Heres my code:
public class TakePhoto extends Activity {
ImageView iv;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_take_photo);
iv = (ImageView) findViewById(R.id.imageView1);
Button b = (Button) findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, 0);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
Bitmap bm = (Bitmap) data.getExtras().get("data");
Random generator = new Random();
String randFileName = String.valueOf (generator.nextInt(965) + 32);
String both = "/mnt/extSdCard/DirectEnquiries/"+ randFileName + ".jpg";
File imageFile = new File(both);
writeBitmapToMemory(imageFile, bm);
iv.setImageBitmap(bm);
}
public void writeBitmapToMemory(File file, Bitmap bitmap) {
FileOutputStream fos;
try {
Log.e("Tom", "Starting take stream");
fos = new FileOutputStream(file);
Log.e("Tom", "Got stream");
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
Log.e("Tom", "Saved Image");
fos.close();
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
Please call the below function to capture image from camera.
private final static String FOLDER_NAME = "YourAppName/Image/";
private Uri selectedImageUri = null;
public void startCamera()
{
File photo = null;
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED))
{
photo = new File(android.os.Environment.getExternalStorageDirectory(), FOLDER_NAME+File.separator+timeStamp+".png");
}
else
{
photo = new File(getCacheDir(), FOLDER_NAME+File.separator+timeStamp+".png");
}
if (photo != null)
{
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photo));
selectedImageUri = Uri.fromFile(photo);
startActivityForResult(intent, CAPTURE_IMAGE_CALLBACK);
}
}
You can get image Uri in selectedImageUri variable . (Image is stored in Sdcard)
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
switch (requestCode)
{
case CAPTURE_IMAGE_CALLBACK:
break;
}
}
Have you tried setting quality in the intent?
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
startActivityForResult(intent, 0);

Categories