I have a Fragment from where I am uploading images from gallery or taking photo from camera but while running the app "App has stopped" message is coming in Android emulator and app is not opening. This is my FragmentEncode class. Is this not the right way to Upload image from Gallery or Camera in Fragments? If not then what's the right way?
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.graphics.Bitmap;
import android.media.MediaScannerConnection;
import android.provider.MediaStore;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Calendar;
import com.stegano.strenggeheim.R;
public class FragmentEncode extends Fragment {
private ImageView imageview;
private static final String IMAGE_DIRECTORY = "/encoded_image";
private static final int GALLERY = 1, CAMERA = 2;
Uri myPicture = null;
Button buttonLoadImage;
Context context = getContext();
public FragmentEncode() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
buttonLoadImage = buttonLoadImage.findViewById(R.id.buttonLoadImage);
imageview = imageview.findViewById(R.id.imageToEncode);
buttonLoadImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showPictureDialog();
}
});
}
private void showPictureDialog(){
AlertDialog.Builder pictureDialog = new AlertDialog.Builder(context);
pictureDialog.setTitle("Select Action");
String[] pictureDialogItems = {
"Select photo from gallery",
"Capture photo from camera" };
pictureDialog.setItems(pictureDialogItems,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case 0:
choosePhotoFromGallary();
break;
case 1:
takePhotoFromCamera();
break;
}
}
});
pictureDialog.show();
}
public void choosePhotoFromGallary() {
Intent galleryIntent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent, GALLERY);
}
private void takePhotoFromCamera() {
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, CAMERA);
}
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_encode, container, false);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == getActivity().RESULT_CANCELED) {
return;
}
if (requestCode == GALLERY) {
if (data != null) {
Uri contentURI = data.getData();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(context.getContentResolver(), contentURI);
String path = saveImage(bitmap);
Toast.makeText(context, "Image Saved!", Toast.LENGTH_SHORT).show();
imageview.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(context, "Failed!", Toast.LENGTH_SHORT).show();
}
}
} else if (requestCode == CAMERA) {
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
imageview.setImageBitmap(thumbnail);
saveImage(thumbnail);
Toast.makeText(context, "Image Saved!", Toast.LENGTH_SHORT).show();
}
}
public String saveImage(Bitmap myBitmap) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
myBitmap.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
File wallpaperDirectory = new File(
Environment.getExternalStorageDirectory() + IMAGE_DIRECTORY);
// have the object build the directory structure, if needed.
if (!wallpaperDirectory.exists()) {
wallpaperDirectory.mkdirs();
}
try {
File f = new File(wallpaperDirectory, Calendar.getInstance()
.getTimeInMillis() + ".jpg");
f.createNewFile();
FileOutputStream fo = new FileOutputStream(f);
fo.write(bytes.toByteArray());
MediaScannerConnection.scanFile(context,
new String[]{f.getPath()},
new String[]{"image/jpeg"}, null);
fo.close();
return f.getAbsolutePath();
} catch (IOException e1) {
e1.printStackTrace();
}
return "";
}
}
try
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
}
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_encode, container, false);
buttonLoadImage = buttonLoadImage.findViewById(R.id.buttonLoadImage);
imageview = imageview.findViewById(R.id.imageToEncode);
buttonLoadImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showPictureDialog();
}
});
return view;
}
and below
Context context = getContext();
put
View view;
Related
When I run an AlertDialog asking the user to get a photo from the camera or the gallery the program doesn't seem to wait for the results and continues to execute. This causes the result to not get saved properly into the Image View field. Ignore the unused variables as I am not done coding this activity yet. I am new to this so any other criticism is appreciated.
package ca.android.whitehead.mycardswallet;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.Objects;
public class AddEditCardActivity extends AppCompatActivity implements View.OnClickListener {
private EditText etCardName;
private ImageView ivCardFront, ivCardBack, ivBarcode;
private Button btnCardFront, btnCardBack, btnBarcode;
private Bitmap image;
private static final int SELECT_PHOTO = 1;
private static final int CAPTUR_PHOTO = 2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_edit_card);
etCardName = findViewById(R.id.etCardName);
ivCardFront = findViewById(R.id.ivCardFront);
ivCardBack = findViewById(R.id.ivCardBack);
ivBarcode = findViewById(R.id.ivBarcode);
btnCardFront = findViewById(R.id.btnCardFront);
btnCardBack = findViewById(R.id.btnCardBack);
btnBarcode = findViewById(R.id.btnBarcode);
btnCardFront.setOnClickListener(this);
btnCardBack.setOnClickListener(this);
}
#Override
public void onClick(View v)
{
switch (v.getId()){
case R.id.btnCardFront:
getImage();
if (image != null)
{
ivCardFront.setImageBitmap(image);
}
break;
case R.id.btnCardBack:
getImage();
if (image != null)
{
ivCardBack.setImageBitmap(image);
}
break;
}
}
public void getImage()
{
AlertDialog.Builder builder = new AlertDialog.Builder(AddEditCardActivity.this);
builder.setTitle("Pick from gallery or take new picture");
Toast.makeText(this, "In Get Image", Toast.LENGTH_SHORT).show();
builder.setItems(R.array.uploadImage, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent;
switch (which) {
case 0:
intent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, SELECT_PHOTO);
break;
case 1:
intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, CAPTUR_PHOTO);
break;
}
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent resultData) {
if (requestCode == SELECT_PHOTO && resultCode == RESULT_OK) {
if (resultData != null) {
// this is the image selected by the user
Uri imageUri = resultData.getData();
if (imageUri != null) {
try {
InputStream inputStream = getContentResolver().openInputStream(imageUri);
image = BitmapFactory.decodeStream(inputStream);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
}
if (requestCode == CAPTUR_PHOTO && resultCode == RESULT_OK) {
if (resultData != null) {
// this is the image selected by the user
image = (Bitmap)Objects.requireNonNull(resultData.getExtras()).get("data");
}
}
}
}
I ended up taking CommonsWare advice.
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.Objects;
public class AddEditCardActivity extends AppCompatActivity implements View.OnClickListener {
private EditText etCardName;
private ImageView ivCardFront, ivCardBack, ivBarcode;
private Button btnCardFront, btnCardBack, btnBarcode;
private Bitmap image;
private static final int SELECT_PHOTO = 100;
private static final int CAPTURE_PHOTO = 200;
private static final int FRONT_IMAGE = 1;
private static final int BACK_IMAGE = 2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_edit_card);
etCardName = findViewById(R.id.etCardName);
ivCardFront = findViewById(R.id.ivCardFront);
ivCardBack = findViewById(R.id.ivCardBack);
ivBarcode = findViewById(R.id.ivBarcode);
btnCardFront = findViewById(R.id.btnCardFront);
btnCardBack = findViewById(R.id.btnCardBack);
btnBarcode = findViewById(R.id.btnBarcode);
btnCardFront.setOnClickListener(this);
btnCardBack.setOnClickListener(this);
}
#Override
public void onClick(View v)
{
switch (v.getId()){
case R.id.btnCardFront:
getImage(1);
break;
case R.id.btnCardBack:
getImage(2);
break;
}
}
public void getImage(final int image)
{
AlertDialog.Builder builder = new AlertDialog.Builder(AddEditCardActivity.this);
builder.setTitle("Pick from gallery or take new picture");
Toast.makeText(this, "In Get Image", Toast.LENGTH_SHORT).show();
builder.setItems(R.array.uploadImage, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent;
switch (which) {
case 0:
intent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, SELECT_PHOTO + image);
break;
case 1:
intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, CAPTURE_PHOTO + image);
break;
}
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
private void setBitmap(Uri imageUri, ImageView imageView)
{
if (imageUri != null) {
try {
InputStream inputStream = getContentResolver().openInputStream(imageUri);
imageView.setImageBitmap(BitmapFactory.decodeStream(inputStream));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent resultData) {
if(resultCode == RESULT_OK) {
if (requestCode == (SELECT_PHOTO + FRONT_IMAGE)) {
if (resultData != null) {
setBitmap(resultData.getData(), ivCardFront);
}
}
else if (requestCode == (SELECT_PHOTO + BACK_IMAGE)) {
if (resultData != null) {
setBitmap(resultData.getData(), ivCardBack);
}
}
else if (requestCode == CAPTURE_PHOTO + FRONT_IMAGE) {
if (resultData != null) {
// this is the image selected by the user
ivCardFront.setImageBitmap((Bitmap)Objects.requireNonNull(resultData.getExtras()).get("data"));
}
}
else if (requestCode == CAPTURE_PHOTO + BACK_IMAGE) {
if (resultData != null) {
// this is the image selected by the user
ivCardBack.setImageBitmap((Bitmap)Objects.requireNonNull(resultData.getExtras()).get("data"));
}
}
}
}
}
I want put edittext from first activity to new secondactivity view text.
What to do when I have an erro like this displayed in android monitor :
com.example.xx.DrawerAddAd.seeAdd(DrawerAddAd.java:129)
com.example.xx.DrawerAddAd.access$100(DrawerAddAd.java:40)
com.example.xx.DrawerAddAd$2.onClick(DrawerAddAd.java:116)
also:
Render problem:
Couldn't resolve resource #id/visible
Tip: Try to refresh the layout.
DrawerAddAd class code:
package com.example.xx.drawer;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Camera;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.design.widget.TextInputEditText;
import android.support.design.widget.TextInputLayout;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.Spinner;
import com.example.xx.R;
import com.example.xxx.model.POJO.view.ProductDetails;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import butterknife.BindView;
public class DrawerAddAd extends AppCompatActivity {
public static ArrayList<String> fragments = new ArrayList<>();
private final int REQUEST_CODE = 1;
private ImageButton camera_imageButton;
private Spinner spinner_category;
private Button button_seeAd_product;
private Button button_add_product;
#BindView(R.id.title_Ad_editText)
EditText titleAd_editText;
#BindView(R.id.text_Ad_editText)
EditText textAd_editText;
#BindView(R.id.price_editText)
EditText price_editText;
#BindView(R.id.checkBox_season)
CheckBox checkBox_season;
#BindView(R.id.checkBox_year)
CheckBox checkBox_year;
#BindView(R.id.checkBox_detail)
CheckBox checkBox_detail;
#BindView(R.id.checkBox_wholesale)
CheckBox checkBox_whoLesale;
private int REQUEST_CAMERA = 1, SELECT_FILE = 1;
private Button btnSelect;
private ImageView Image;
private String userChosenTask;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_drawer_add_ad);
final TextInputLayout title_ad_layout = (TextInputLayout) findViewById(R.id.add_title_ad_layout);
final TextInputLayout text_ad_layout = (TextInputLayout) findViewById(R.id.add_text_ad_layout);
final TextInputEditText title_Ad_editText = (TextInputEditText) findViewById(R.id.title_Ad_editText);
final TextInputEditText text_Ad_editText = (TextInputEditText) findViewById(R.id.text_Ad_editText);
setTextWatcher(title_Ad_editText, title_ad_layout);
setTextWatcher(text_Ad_editText, text_ad_layout);
spinner_category = (Spinner) findViewById(R.id.spinner_category);
button_seeAd_product = (Button) findViewById(R.id.button_seeAd_product);
button_add_product = (Button) findViewById(R.id.button_ad_product);
camera_imageButton = (ImageButton) findViewById(R.id.camera_imageButton);
camera_imageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
selectImage();
}
});
button_seeAd_product.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
boolean error = false;
if (TextUtils.isEmpty(title_Ad_editText.getText().toString())) {
title_ad_layout.setError(getString(R.string.empty_field));
error = true;
}
if (TextUtils.isEmpty(text_Ad_editText.getText().toString())) {
text_ad_layout.setError(getString(R.string.empty_field));
error = true;
}
if (!error) {
seeAdd();
}
}
});
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.fragments, R.layout.support_simple_spinner_dropdown_item);
adapter.setDropDownViewResource(R.layout.support_simple_spinner_dropdown_item);
spinner_category.setAdapter(adapter);
}
private void seeAdd() {
Intent intent = new Intent(getApplicationContext(), ProductDetails.class);
intent.putExtra("title",titleAd_editText.getText().toString());
intent.putExtra("text", textAd_editText.getText().toString());
// ImageView imageView =
// String title = titleAd_editText.getText().toString();
// String text = textAd_editText.getText().toString();
// String price = price_editText.getText().toString();
//
//
// intent.putExtra("titleAdd", title);
// intent.putExtra("textAdd", text);
// intent.putExtra("price", price);
startActivity(intent);
}
private void onCheckboxClicked(View view) {
boolean checked = ((CheckBox) view).isChecked();
switch (view.getId()) {
case R.id.checkBox_season:
if (checked) {
} else {
}
break;
case R.id.checkBox_year:
if (checked) {
} else {
}
break;
case R.id.checkBox_detail:
if (checked) {
} else {
}
break;
case R.id.checkBox_wholesale:
if (checked) {
} else {
}
break;
}
}
private void setTextWatcher(final TextInputEditText editText, final TextInputLayout inputLayout) {
editText.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
if (inputLayout.isErrorEnabled()) {
inputLayout.setErrorEnabled(false);
}
}
#Override
public void afterTextChanged(Editable editable) {
}
});
}
private void selectImage() {
final CharSequence[] items = {"Zrób zdjęcie", "Wybierz z katalogu", "Anuluj"};
AlertDialog.Builder builder = new AlertDialog.Builder(DrawerAddAd.this);
builder.setTitle("Dodaj zdjęcie");
builder.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
boolean result = Utility.checkPermission(DrawerAddAd.this);
if (items[item].equals("Zrób zdjęcie")) {
userChosenTask = "Zrób zdjęcie";
if (result)
cameraIntent();
} else if (items[item].equals("Wybierz z katalogu")) {
userChosenTask = "Wybierz z katalogu";
if (result)
galleryIntent();
} else if (items[item].equals("Anuluj")) {
dialog.dismiss();
}
}
});
builder.show();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == SELECT_FILE)
onSelectFromGalleryResult(data);
else if (requestCode == REQUEST_CAMERA)
onCaptureImageResult(data);
}
}
private void cameraIntent() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, REQUEST_CAMERA);
}
private void galleryIntent() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Wybierz plik"), SELECT_FILE);
}
private void onSelectFromGalleryResult(Intent data) {
Bitmap bm = null;
if (data != null) {
try {
bm = MediaStore.Images.Media.getBitmap(getApplicationContext().getContentResolver(), data.getData());
} catch (IOException e) {
e.printStackTrace();
}
}
Image.setImageBitmap(bm);
}
private void onCaptureImageResult(Intent data) {
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
File destination = new File(Environment.getExternalStorageDirectory(),
System.currentTimeMillis() + ".jpg");
FileOutputStream fo;
try {
destination.createNewFile();
fo = new FileOutputStream(destination);
fo.write(bytes.toByteArray());
fo.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Image.setImageBitmap(thumbnail);
}
}
ProductDetails class code:
package com.example.xxx.model.POJO.view;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.TextView;
import com.example.xxx.R;
public class ProductDetails extends AppCompatActivity {
private TextView title, text, price, date;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_product_details);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
title = (TextView) findViewById(R.id.title_textView);
text = (TextView) findViewById(R.id.text_textView);
Intent intent = getIntent();
// Bundle bundle = getIntent().getExtras();
String title_textView = intent.getStringExtra("titleAdd");
String text_textView = intent.getStringExtra("textAdd");
title.setText(title_textView);
text.setText(text_textView);
// price = (TextView) findViewById(R.id.price_textView);
// date = (TextView) findViewById(R.id.date_textView);
// String titleAdd = bundle.getString("titleAdd");
// String textAdd = bundle.getString("textAdd");
// String price = bundle.getString("price");
// title.setText(titleAdd);
// text.setText(textAdd);
// price.setText(price);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
}
I don't know what to do ...
Thanks, Slawek.
it means title_Ad_editText is null.
Check your xml file and title_Ad_editText variable.
couple things I could see, redo this:
private void seeAdd() {
Intent intent = new Intent(getApplicationContext(), ProductDetails.class);
intent.putExtra("title",titleAd_editText.getText().toString());
intent.putExtra("text", textAd_editText.getText().toString());
to this:
private void seeAdd() {
Intent intent = new Intent(DrawerAddAd.this, ProductDetails.class);
intent.putExtra("title",titleAd_editText.getText().toString());
intent.putExtra("text", textAd_editText.getText().toString());
then in your intent, you need to call the extra exactly as set, change this:
Intent intent = getIntent();
// Bundle bundle = getIntent().getExtras();
String title_textView = intent.getStringExtra("titleAdd");
String text_textView = intent.getStringExtra("textAdd");
to this:
Intent intent = getIntent();
// Bundle bundle = getIntent().getExtras();
String title_textView = intent.getStringExtra("title");
String text_textView = intent.getStringExtra("text");
I have three Activity objects.
I want to transfer picture from FirstActivity To SecondActivity by passing in AlarmREceiver
This is my code of FirstActivity
package com.testcamera.hassanechafai.testcamera;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.provider.MediaStore.MediaColumns;
import android.support.v7.app.ActionBarActivity;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import java.io.File;
import java.util.Calendar;
import java.util.Date;
public class FirstActivity extends ActionBarActivity {
private String selectedImagePath = "";
final private int PICK_IMAGE = 1;
final private int CAPTURE_IMAGE = 2;
ImageView imgView;
private String imgPath;
Intent myIntent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
imgView = (ImageView) findViewById(R.id.ImageView);
Button butCamera = (Button) findViewById(R.id.Button1);
butCamera.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
final Intent intent = new Intent(
MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT,
setImageUri());
startActivityForResult(intent, CAPTURE_IMAGE);
}
});
Button butGallery = (Button) findViewById(R.id.Button2);
butGallery.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(
Intent.createChooser(intent, ""),
PICK_IMAGE);
}
});
final EditText save = (EditText) findViewById(R.id.EditText1);
Button myBtn = (Button) findViewById(R.id.Save);
myBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int time = Integer.parseInt(save.getText().toString());
if (time > 0) {
myIntent = new Intent(getBaseContext(), AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getBaseContext(), 0, myIntent, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.add(Calendar.SECOND, time);
alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
Toast.makeText(getApplicationContext(), "Starting Activity in: " + time + " seconds", Toast.LENGTH_SHORT).show();
finish();
}
}
});
}
public Uri setImageUri() {
// Store image in dcim
File file = new File(Environment.getExternalStorageDirectory()
+ "/DCIM/", "image" + new Date().getTime() + ".png");
Uri imgUri = Uri.fromFile(file);
this.imgPath = file.getAbsolutePath();
return imgUri;
}
public String getImagePath() {
return imgPath;
}
#Override
protected void onActivityResult(int requestCode, int resultCode,
Intent data) {
if (resultCode != Activity.RESULT_CANCELED) {
if (requestCode == PICK_IMAGE) {
selectedImagePath = getAbsolutePath(data.getData());
imgView.setImageBitmap(decodeFile(selectedImagePath));
} else if (requestCode == CAPTURE_IMAGE) {
selectedImagePath = getImagePath();
imgView.setImageBitmap(decodeFile(selectedImagePath));
Intent intent = new Intent(this, CallActivity.class);
intent.putExtra("BitmapImage", selectedImagePath);
} else {
super.onActivityResult(requestCode, resultCode,
data);
}
}
}
#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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public Bitmap decodeFile(String path) {
try {
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeFile(path, o);
// The new size we want to scale to
final int REQUIRED_SIZE = 70;
// Find the correct scale value. It should be the power of
// 2.
int scale = 1;
while (o.outWidth / scale / 2 >= REQUIRED_SIZE
&& o.outHeight / scale / 2 >= REQUIRED_SIZE)
scale *= 2;
// Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
return BitmapFactory.decodeFile(path, o2);
} catch (Throwable e) {
e.printStackTrace();
}
return null;
}
public String getAbsolutePath(Uri uri) {
String[] projection = { MediaColumns.DATA };
#SuppressWarnings("deprecation")
Cursor cursor = managedQuery(uri, projection, null, null, null);
if (cursor != null) {
int column_index = cursor
.getColumnIndexOrThrow(MediaColumns.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} else
return null;
}
}
This code of AlarmReceiver
package com.testcamera.hassanechafai.testcamera;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;
public class AlarmReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "Alarm time reached", Toast.LENGTH_SHORT).show();
Intent i = new Intent();
i.setClassName("com.testcamera.hassanechafai.testcamera", "com.testcamera.hassanechafai.testcamera.CallActivity");
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
}
}
This code of SecondAcitivy (I call it CallActivity)
package com.testcamera.hassanechafai.testcamera;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ImageView;
public class CallActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_call);
ImageView image = (ImageView)findViewById(R.id.ImageView);
}
I need to transfer photo from FirstActivity To SecondAcitivy by passing in AlarmActivity can someone help me ?
in your myBtn onClick you forgot to add myIntent.putExtra("theKeyUsed","yourConvertedStringUri");
then in your Receiver class you are missing that too.
IN your CallAcitvity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_call);
String path = getIntent().getStringExtra("theKeyUsed"); // in your case "BitmapImage"
ImageView image = (ImageView)findViewById(R.id.ImageView);
// now set image using the path
}
In general pass your uri.toString() as a string extra with your intent to the preferred activity and retrieve..
feel free to delete the question if you find your solution
I need to take photo and send in MainActivity and send it to thirdActivity
this is the code of MainActivity
PS : I opened Main activity From ThirdActivity
package com.fakecamera.hassanechafai.fakacamera;
import java.io.File;
import com.fakecamera.hassanechafai.fakacamera.R;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.hardware.Camera;
import android.hardware.Camera.CameraInfo;
import android.hardware.Camera.PictureCallback;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.Display;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import com.fakecamera.hassanechafai.fakacamera.CameraPreview;
import com.fakecamera.hassanechafai.fakacamera.MyAlertDialogs;
import com.fakecamera.hassanechafai.fakacamera.NoCameraPresentDialog;
public class MainActivity extends Activity {
private Camera mCamera;
private CameraPreview mCameraPreview;
public static Display display;
#SuppressLint("NewApi")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
display = ((WindowManager) getSystemService(Context.WINDOW_SERVICE))
.getDefaultDisplay();
mCamera = this.getCameraInstance();
if (mCamera == null) {
NoCameraPresentDialog noCamera = new NoCameraPresentDialog(
MainActivity.this);
noCamera.showDialog();
} else {
mCameraPreview = new CameraPreview(this, mCamera);
FrameLayout preview = (FrameLayout) findViewById(R.id.camera_preview);
preview.addView(mCameraPreview);
ImageButton captureButton = (ImageButton) findViewById(R.id.button_capture);
captureButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mCamera.takePicture(null, null, mPicture);
// mCamera.startPreview();
}
});
}
}
private Camera getCameraInstance() {
Camera camera = null;
Log.d("No of cameras", Camera.getNumberOfCameras() + "");
for (int camNo = 0; camNo < Camera.getNumberOfCameras(); camNo++) {
CameraInfo camInfo = new CameraInfo();
Camera.getCameraInfo(camNo, camInfo);
if (camInfo.facing == (Camera.CameraInfo.CAMERA_FACING_FRONT)) {
camera = Camera.open(camNo);
}
}
return camera;
}
PictureCallback mPicture = new PictureCallback() {
#Override
public void onPictureTaken(byte[] data, Camera camera) {
File pictureFile = getOutputMediaFile();
if (pictureFile == null) {
return;
}
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
fos.write(data);
fos.close();
notifyImageCapture(pictureFile.getPath());
} catch (FileNotFoundException e) {
} catch (IOException e) {
}
}
};
public void notifyImageCapture(String filepath) {
Intent i = new Intent(this, ThirdActivity.class);
i.putExtra("path", "" + filepath);
startActivityForResult(i, 100);
}
public static File getOutputMediaFile() {
File mediaStorageDir = new File(
Environment.getExternalStorageDirectory(), "Photos");
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d("Photos", "failed to create directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
.format(new Date());
File mediaFile;
mediaFile = new File(mediaStorageDir.getPath() + File.separator
+ "IMG_" + timeStamp + ".jpg");
Log.i("Mediapath", "" + mediaFile.getPath());
return mediaFile;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
if (requestCode == 100) {
this.finish();
startActivity(new Intent(this, MainActivity.class));
}
super.onActivityResult(requestCode, resultCode, data);
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK)) {
MyAlertDialogs dialogs = new MyAlertDialogs(MainActivity.this);
dialogs.getRateMyAppDialog();
}
return super.onKeyDown(keyCode, event);
}
}
this is my code of thirdActivity
package com.fakecamera.hassanechafai.fakacamera;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.content.Intent;
import android.os.Handler;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.graphics.Bitmap;
import com.fakecamera.hassanechafai.fakacamera.LoadImageBitmap;
public class ThirdActivity extends ActionBarActivity {
private ImageView imageToEdit;
private Bitmap orignalBitmap;
private String CLICKED_IMAGE_FILE_PATH;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_third);
ImageButton takeimage = (ImageButton)findViewById(R.id.imageButton3);
takeimage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(ThirdActivity.this,
MainActivity.class);
startActivity(intent);
}
});
imageToEdit = (ImageView) this.findViewById(R.id.item_click_image);
final EditText edittext = (EditText)findViewById(R.id.editText);
Button button = (Button)findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int time = Integer.parseInt(edittext.getText().toString());
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Intent startActivity = new Intent(ThirdActivity.this, FullscreenActivity.class);
startActivity(startActivity);
finish();
}
}, time * 1000);
}
});
CLICKED_IMAGE_FILE_PATH = getIntent().getStringExtra("path");
this.setUpImage(CLICKED_IMAGE_FILE_PATH);
}
public void setUpImage(String path) {
LoadImageBitmap imageLoader = new LoadImageBitmap();
orignalBitmap = imageLoader.displayFullImage(path);
if(CameraPreview.isPortrait){
orignalBitmap = ImageEffects.rotate(imageLoader.displayFullImage(path));
}else{
orignalBitmap=imageLoader.displayFullImage(path);
}
imageToEdit.setImageBitmap(orignalBitmap);
}
#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_third, 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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
I have any error but when I trying to take a photo I get this message :
Unfortunately ,FirstCamera has stopped
what is my problem ?
You should call startActivityForResult from ThirdActivity and then set the photo as result in your MainActivity. For this you will need to make sure your photo model implements Parcelable.
You can then call setResult(RESULT_OK, Photo) in MainActivity and you will get the photo back in ThirdActivity in the method onActivityResult
If your photo is too large, you should convert it to bytes array to put it to Intent
I followed all steps when dealing with Mat including adding it to AsyncTask when calling but still the same error which is native method not found org.opencv.core.mat.n_mat
Here's the code:
package com.example.myfirstapp;
import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import org.json.JSONException;
import org.json.JSONObject;
import org.opencv.android.BaseLoaderCallback;
import org.opencv.android.LoaderCallbackInterface;
import org.opencv.android.OpenCVLoader;
import org.opencv.android.Utils;
import org.opencv.core.Mat;
import com.example.myfirstapp.RegisterMarkerMain.ProcessImage;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.util.Base64;
import android.util.Log;
import android.view.ContextMenu;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;
public class CreateApp extends ListActivity {
boolean duplicate = false;
String userID = "";
Intent manage;
String image = "";
Intent refresh;
CandidatesListAdapter adapter;
ProcessImage process;
Mat mRgba;
private BaseLoaderCallback mLoaderCallback = new BaseLoaderCallback(this) {
#Override
public void onManagerConnected(int status) {
Log.i("loading libs", "OpenCV loading status " + status);
switch (status) {
case LoaderCallbackInterface.SUCCESS: {
Log.i("loading libs", "OpenCV loaded successfully");
// Load native library after(!) OpenCV initialization
System.loadLibrary("native_sample");
}
break;
default: {
super.onManagerConnected(status);
}
break;
}
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_app);
manage = new Intent(this, ManageApps.class);
concurrentTasks();
Bundle extras = getIntent().getExtras();
if (extras != null) {
userID = extras.getString("user_id");
Toast.makeText(CreateApp.this, "User id " + userID,
Toast.LENGTH_LONG).show();
}
final Spinner spinner = (Spinner) findViewById(R.id.categories_spinner);
refresh = new Intent(this, ManageApps.class);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
this, R.array.categories_array,
android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView,
View selectedItemView, int position, long id) {
// your code here
String category = spinner.getSelectedItem().toString();
Toast.makeText(CreateApp.this,
"Category " + category + " selected",
Toast.LENGTH_SHORT).show();
TextView tv = (TextView) findViewById(R.id.question_title);
tv.setText(category);
}
#Override
public void onNothingSelected(AdapterView<?> parentView) {
// your code here
}
});
ImageView iv = (ImageView) findViewById(R.id.application_logo);
registerForContextMenu(iv);
iv.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View arg0) {
// TODO Auto-generated method stub
return false;
}
});
iv.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(CreateApp.this, "Long click to add image",
Toast.LENGTH_LONG).show();
}
});
Button submit = (Button) findViewById(R.id.submit);
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
EditText et = (EditText) findViewById(R.id.application_name_edit);
if (et.getText().toString().equals(null)
|| et.getText().toString().equals("")) {
Toast.makeText(CreateApp.this,
"App Name can not be empty.", Toast.LENGTH_SHORT)
.show();
} else {
if (spinner.getSelectedItem().toString().equals("Select")
|| spinner.getSelectedItem().toString().equals("")) {
Toast.makeText(CreateApp.this,
"Cateory must be selected.", Toast.LENGTH_SHORT)
.show();
} else {
new AsyncAppDuplicates().execute();
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (duplicate == true) {
System.out
.println("Duplicate flag for App Creation inside if "
+ duplicate);
AlertDialog.Builder builder = new AlertDialog.Builder(
CreateApp.this);
builder.setTitle("Warning");
builder.setMessage("An application already exists with this name."
+ "\n" + "Please choose a different name.");
builder.setNegativeButton("Ok",
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface dialog, int id) {
// if this button is clicked, just
// close
// the dialog box and do nothing
dialog.cancel();
}
});
builder.show();
} else {
concurrentCreate();
Toast.makeText(CreateApp.this,
"Created Successfully", Toast.LENGTH_SHORT)
.show();
System.out.println("Done");
// EditText app = (EditText)
// findViewById(R.id.application_name_edit);
}
}
}
}
});
}
#SuppressLint("NewApi")
private void concurrentTasks() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
new AsyncGetCategories()
.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
System.out.println("getting categories");
} else {
new AsyncGetCategories().execute();
}
}
#SuppressLint("NewApi")
private void concurrentCreate() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
new AsyncCreateApplication()
.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
System.out.println("Creating app");
} else {
new AsyncCreateApplication().execute();
}
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK)) {
finish();
manage.putExtra("user_id", userID);
startActivity(manage);
}
return super.onKeyDown(keyCode, event);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.create_app, menu);
return true;
}
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
getMenuInflater().inflate(R.menu.contextmenu, menu);
menu.setHeaderTitle("Select an Option");
}
#Override
public boolean onContextItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_take:
Toast.makeText(CreateApp.this, "Opening the Camera",
Toast.LENGTH_SHORT).show();
Intent camera = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(camera, 0);
return true;
case R.id.menu_choose:
Toast.makeText(CreateApp.this, "Opening the Gallery",
Toast.LENGTH_SHORT).show();
Intent gallery = new Intent();
gallery.setType("image/*");
gallery.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(
Intent.createChooser(gallery, "Select Picture"), 1);
return true;
}
return super.onContextItemSelected(item);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
ImageView iv = new ImageView(this);
switch (requestCode) {
case 0:
if (resultCode == RESULT_OK) {
// Uri selectedImage = data.getData();
Toast.makeText(this, "Adding Photo From Camera",
Toast.LENGTH_LONG).show();
iv = (ImageView) findViewById(R.id.application_logo);
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
iv.setImageBitmap(thumbnail);
Intent r = new Intent(this, RegisterMarkerMain.class);
//startActivity(r);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.PNG, 100, baos);
byte[] b = baos.toByteArray();
image = Base64.encodeToString(b, Base64.DEFAULT);
//r.putExtra("BitmapImage", image);
//startActivityForResult(r, 13);
Toast.makeText(this, "Marker Valid", Toast.LENGTH_LONG).show();
adapter = new CandidatesListAdapter(this);
setListAdapter(adapter);
process = new ProcessImage(this, thumbnail);
process.execute();
//call the main layout from xml
//RelativeLayout mainLayout = (RelativeLayout)findViewById(R.id.create_layout_id);
//create a view to inflate the layout_item (the xml with the textView created before)
//View view = getLayoutInflater().inflate(R.layout.layout_item, mainLayout,false);
//add the view to the main layout
// mainLayout.addView(view);
}
break;
case 1:
if (resultCode == RESULT_OK) {
Toast.makeText(this, "Adding Photo From Gallery",
Toast.LENGTH_LONG).show();
Uri targetUri = data.getData();
iv = (ImageView) findViewById(R.id.application_logo);
Bitmap thumbnail = null;
try {
thumbnail = BitmapFactory.decodeStream(getContentResolver()
.openInputStream(targetUri));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
iv.setImageBitmap(thumbnail);
ByteArrayOutputStream baos=new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.JPEG,100, baos);
byte [] b=baos.toByteArray();;
try{
System.gc();
image=Base64.encodeToString(b, Base64.DEFAULT);
}catch(Exception e){
e.printStackTrace();
}catch(OutOfMemoryError e){
baos=new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.JPEG,50, baos);
b=baos.toByteArray();
image=Base64.encodeToString(b, Base64.DEFAULT);
Log.e("EWN", "Out of memory error catched");
}
Toast.makeText(this, "Marker Valid", Toast.LENGTH_LONG).show();
}
break;
}
}
public void managePrivacy(View v) {
Intent privacyIntent = new Intent(this, ManagePrivactActivity.class);
startActivity(privacyIntent);
}
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
Marker o = (Marker) this.getListAdapter().getItem(position);
Toast.makeText(this, "strength " + o.descriptor.rows(),
Toast.LENGTH_SHORT).show();
// TODO: both Image and descriptor should be sent to server combined
// with location and other info.
// Descriptor of image is n rows * 64 numbers
}
public native void loadCand(long nativeObjAddr, long descriptoradd, int i);
public native int findMarkersNative(long imgAdd);
public class ProcessImage extends AsyncTask<Void, Void, ArrayList<Marker>> {
private Context mContext;
Bitmap bmp;
public ProcessImage(Context context, Bitmap bmp) {
mContext = context;
mRgba = new Mat();
this.bmp = bmp;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
getListView().setVisibility(View.GONE);
//loading.setVisibility(View.VISIBLE);
Utils.bitmapToMat(bmp, mRgba);
}
#Override
protected void onPostExecute(ArrayList<Marker> result) {
getListView().setVisibility(View.VISIBLE);
//loading.setVisibility(View.GONE);
adapter.updateData(result);
// display
Utils.matToBitmap(mRgba, bmp);
//imageView.setImageBitmap(bmp);
super.onPostExecute(result);
}
#Override
protected ArrayList<Marker> doInBackground(Void... params) {
ArrayList<Marker> imagesCand = new ArrayList<Marker>();
// process
int candCount = findMarkersNative(mRgba.getNativeObjAddr());
for (int i = 0; i < candCount; i++) {
Mat cand = new Mat();
Mat descriptor = new Mat();
loadCand(cand.getNativeObjAddr(),
descriptor.getNativeObjAddr(), i);
if (descriptor.rows() > 0) {
Bitmap bmp3 = Bitmap.createBitmap(cand.cols(), cand.rows(),
Bitmap.Config.ARGB_8888);
Utils.matToBitmap(cand, bmp3);
imagesCand.add(new Marker(bmp3, descriptor));
}
}
return imagesCand;
}
}
private class AsyncCreateApplication extends AsyncTask<String, Void, Void> {
#Override
protected Void doInBackground(String... arg0) {
EditText et = (EditText) findViewById(R.id.application_name_edit);
String s = et.getText().toString();
TextView tv = (TextView) findViewById(R.id.question_title);
String c = tv.getText().toString();
System.out.println("Category yafanan " + c);
ServerAPI.createApplication(s, c, userID, image);
System.out.println("in Background");
return null;
}
protected void onPostExecute(Void result) {
EditText et = (EditText) findViewById(R.id.application_name_edit);
refresh.putExtra("app_name", et.getText().toString());
System.out.println("App created " + et.getText().toString());
refresh.putExtra("user_id", userID);
setResult(RESULT_OK, refresh);
// startActivity(edit);
startActivity(refresh);
}
}
private class AsyncGetCategories extends AsyncTask<Void, Void, Void> {
ArrayList<String> al = null;
ArrayAdapter<String> dataAdapter;
Spinner category = (Spinner) findViewById(R.id.categories_spinner);
#Override
protected Void doInBackground(Void... params) {
System.out.println("do in background");
al = ServerAPI.getCategories();
System.out.println("ArrayList fetched");
return null;
}
#Override
protected void onPostExecute(Void result) {
dataAdapter = new ArrayAdapter<String>(CreateApp.this,
android.R.layout.simple_spinner_item,
new ArrayList<String>());
dataAdapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
category.setAdapter(dataAdapter);
dataAdapter.add("Select");
for (int i = 0; i < al.size(); i++) {
dataAdapter.add(al.get(i));
// System.out.println(al.remove(i));
}
return;
}
}
private class AsyncAppDuplicates extends AsyncTask<String, Void, Void> {
#Override
protected Void doInBackground(String... arg0) {
EditText et = (EditText) findViewById(R.id.application_name_edit);
String name = et.getText().toString();
String s = ServerAPI.checkAppDuplicates(name, userID);
System.out.println("Checked and " + s);
if (s.equals("Already there")) {
duplicate = true;
} else {
duplicate = false;
}
return null;
}
}
}
I've googled so much but I can't figure out what's wrong.
Any help would be really appreciated.
I solved it writing the following lines where you declare everything for the activity, before onCreate:
static {
if (!OpenCVLoader.initDebug()) {
// Handle initialization error
}
}
confirm your native_sample.so file has been contained in your libs-->armeabi folder, and usually, the native lib should be loaded in a static code block outside of the activity's life circle methods.