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
Related
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");
}
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.
How should I implement retrofit into this code to send an image to the server instead of using Volley? I'm a little confused as I'm a bit new to Java/Android. I would like some guidance on how to achieve this using Retrofit as Volley doesnt seem to be working.
I'm basically sending a base64 string of an image to my server along with the image name and a few other things later on. I also need to retrieve the response from my server and display it on my app. Volley seemed to do that easily, not sure about Retrofit.
Thanks in advance
public class MainActivity extends AppCompatActivity {
private ImageButton ImageButton;
private String encoded_string, image_name;
private Bitmap bitmap;
private File file;
private Uri file_uri;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ImageButton = (ImageButton) findViewById(R.id.camera);
ImageButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
getFileUri();
i.putExtra(MediaStore.EXTRA_OUTPUT,file_uri);
startActivityForResult(i,10);
}
});
}
private void getFileUri() {
image_name = "testing123.jpeg";
file = new File(Environment.getExternalStorageDirectory().getAbsoluteFile(), image_name);
file_uri = Uri.fromFile(file);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == 10 && resultCode == RESULT_OK){
new Encode_image().execute();
}
}
private class Encode_image extends AsyncTask<Void,Void,Void> {
#Override
protected Void doInBackground(Void... voids){
bitmap = BitmapFactory.decodeFile(file_uri.getPath());
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG,100,stream);
byte[] array = stream.toByteArray();
encoded_string = Base64.encodeToString(array,0);
return null;
}
#Override
protected void onPostExecute(Void aVoid){
makeRequest();
}
}
private void makeRequest() {
final TextView mTextView = (TextView) findViewById(R.id.text);
RequestQueue requestQueue = Volley.newRequestQueue(this);
String URL = "http://128.199.77.211/server/connection.php";
StringRequest request = new StringRequest(Request.Method.POST, URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
mTextView.setText(response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
mTextView.setText("That didn't work!");
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
HashMap<String, String> map = new HashMap<>();
map.put("encoded_string", encoded_string);
map.put("image_name", image_name);
return map;
}
};
requestQueue.add(request);
}
}
Using Retrofit 2, you need to use either OkHttp’s RequestBody or MultipartBody.Part classes and encapsulate your file into a request body. Let’s have a look at the interface definition for file uploads.
public interface FileUploadService {
#Multipart
#POST("upload")
Call<ResponseBody> upload(#Part("description") RequestBody description,
#Part MultipartBody.Part file);
}
in Java file
private void uploadFile(Uri fileUri) {
// create upload service client
FileUploadService service =
ServiceGenerator.createService(FileUploadService.class);
// https://github.com/iPaulPro/aFileChooser/blob/master/aFileChooser/src/com/ipaulpro/afilechooser/utils/FileUtils.java
// use the FileUtils to get the actual file by uri
File file = FileUtils.getFile(this, fileUri);
// create RequestBody instance from file
RequestBody requestFile =
RequestBody.create(MediaType.parse("multipart/form-data"), file);
// MultipartBody.Part is used to send also the actual file name
MultipartBody.Part body =
MultipartBody.Part.createFormData("picture", file.getName(), requestFile);
// add another part within the multipart request
String descriptionString = "hello, this is description speaking";
RequestBody description =
RequestBody.create(
MediaType.parse("multipart/form-data"), descriptionString);
// finally, execute the request
Call<ResponseBody> call = service.upload(description, body);
call.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call,
Response<ResponseBody> response) {
Log.v("Upload", "success");
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Log.e("Upload error:", t.getMessage());
}
});
}
Create MultipartBody.Part object from your image.
File imageIdCard = new File(image_path);
RequestBody requestFile = RequestBody.create(MediaType.parse("image/*"), imageIdCard);
MultipartBody.Part bodyImage = MultipartBody.Part.createFormData("image_id", imageIdCard.getName(), requestFile);
and upload it
#Multipart
#POST("url")
Call<JsonObect> getResponse(#Part MultipartBody.Part image);
I'm fetching user's profile picture from facebook and I want to send it to ProfileActivity.java so that it can be displayed on user profile.
The problem is that the image is not getting sent from SignUpScreen.java to ProfileActivity.java. Though I am able to send name & email from one to another.
Here's SignUpScreen.java file's code:
public class SignUpScreen extends AppCompatActivity {
Button facebookLoginButton;
CircleImageView mProfileImage;
TextView mUsername, mEmailID;
Profile mFbProfile;
ParseUser user;
Bitmap bmp = null;
public String name, email, userID;
public static final List<String> mPermissions = new ArrayList<String>() {{
add("public_profile");
add("email");
}};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content_sign_up_screen);
TextView textView = (TextView) findViewById(R.id.h);
Typeface typeface = Typeface.createFromAsset(getBaseContext().getAssets(), "fonts/Pac.ttf");
textView.setTypeface(typeface);
mProfileImage = (CircleImageView) findViewById(R.id.user_profile_image);
mUsername = (TextView) findViewById(R.id.userName);
mEmailID = (TextView) findViewById(R.id.aboutUser);
mFbProfile = Profile.getCurrentProfile();
//mUsername.setVisibility(View.INVISIBLE);
//mEmailID.setVisibility(View.INVISIBLE);
facebookLoginButton = (Button) findViewById(R.id.facebook_login_button);
facebookLoginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ParseFacebookUtils.logInWithReadPermissionsInBackground(SignUpScreen.this, mPermissions, new LogInCallback() {
#Override
public void done(ParseUser user, ParseException err) {
if (user == null) {
Log.d("MyApp", "Uh oh. The user cancelled the Facebook login.");
} else if (user.isNew()) {
Log.d("MyApp", "User signed up and logged in through Facebook!");
getUserDetailsFromFacebook();
final Handler handler3 = new Handler();
handler3.postDelayed(new Runnable() {
#Override
public void run() {
saveNewUser();
}
}, 5000);
} else {
Log.d("MyApp", "User logged in through Facebook!");
}
}
});
}
});
}
public void saveNewUser() {
user = new ParseUser();
user.setUsername(name);
user.setEmail(email);
user.setPassword("hidden");
user.signUpInBackground(new SignUpCallback() {
#Override
public void done(ParseException e) {
if (e == null) {
Toast.makeText(SignUpScreen.this, "SignUp Succesful", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(SignUpScreen.this, "SignUp Unsuccesful", Toast.LENGTH_LONG).show();
Log.d("error when signingup", e.toString());
}
}
});
}
private void getUserDetailsFromFacebook() {
final GraphRequest request = GraphRequest.newMeRequest(AccessToken.getCurrentAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(
JSONObject object,
GraphResponse response) {
// Application code
//Log.d("response", "response" + object.toString());
Intent profileIntent = new Intent(SignUpScreen.this, ProfileActivity.class);
Bundle b = new Bundle();
try {
name = response.getJSONObject().getString("name");
mUsername.setText(name);
email = response.getJSONObject().getString("email");
mEmailID.setText(email);
userID = response.getJSONObject().getString("id");
new ProfilePicAsync().execute(userID);
b.putString("userName", name);
b.putString("userEmail", email);
profileIntent.putExtras(b);
profileIntent.putExtra("user_pic", bmp);
startActivity(profileIntent);
} catch (JSONException e) {
e.printStackTrace();
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "name, email, id");
request.setParameters(parameters);
request.executeAsync();
}
class ProfilePicAsync extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... params) {
String imageURL;
String id = userID;
imageURL = "https://graph.facebook.com/"+ id +"/picture?type=large";
try {
bmp = BitmapFactory.decodeStream((InputStream)new URL(imageURL).getContent());
} catch (Exception e) {
e.printStackTrace();
Log.d("Loading picture failed", e.toString());
}
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
mProfileImage.setImageBitmap(bmp);
}
}
}
Here's ProfileActivity.java file's code:
public class ProfileActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Bundle bundle = getIntent().getExtras();
CircleImageView mProfileImage = (CircleImageView) findViewById(R.id.user_profile_image);
TextView mUsername = (TextView) findViewById(R.id.userName);
TextView mEmailID = (TextView) findViewById(R.id.aboutUser);
Bitmap bitmap = (Bitmap) getIntent().getParcelableExtra("user_pic");
mProfileImage.setImageBitmap(bitmap);
mUsername.setText(bundle.getString("userName"));
mEmailID.setText(bundle.getString("userEmail"));
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
}
Please let me know what is going wrong here.
In your getUserDetailsFromFacebook() method you have called new ProfilePicAsync().execute(userID) to get the image. But it seems that before you could fetch the image ,startActivity(profileIntent) probably gets called.
First be sure that you have fetched the image from facebook before you call startActivity(profileIntent).
EDIT
Add this to your getUserDetailsFromFacebook() ,
b.putString("userName", name);
b.putString("userEmail", email);
profileIntent.putExtras(b);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
profileIntent.putExtra("user_pic", byteArray);
startActivity(profileIntent);
Add this to your ProfileActivity.java ,
byte[] byteArray = getIntent().getByteArrayExtra("user_pic");
Bitmap bmp = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
mProfileImage.setImageBitmap(bmp);
This is not a right way to pass image from Activity to Activity within same application. You can easily send the path by intent and load it into other Activity.
To save a bitmap in Activity A, use
FileOutputStream out = null;
try {
out = new FileOutputStream(FILENAME); //FILENAME is your defined place to store image
bmp.compress(Bitmap.CompressFormat.PNG, 100, out);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (out != null) {
out.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
Now you have FILENAME global string which is accessible from Activity B.
Just load it where its needed.
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
Bitmap bitmap = BitmapFactory.decodeFile(FILENAME, options);
mProfileImage.setImageBitmap(bitmap);
it works for me.
OneActivity.java
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
Intent intent = new Intent(StartPage.this, SecondActivity.class);
Toast.makeText(StartPage.this, "You have setted this wallpaper for Monday", Toast.LENGTH_LONG).show();
intent.putExtra("pic", byteArray);
//intent.putExtra("resourseInt", bm);
startActivity(intent);
SecondActivity.Java
byte[] byteArray;
Bitmap bmp,
byteArray = getIntent().getByteArrayExtra("pic");
bmp1 = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
myWallpaperManager.setBitmap(bmp);
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);
}
}