So i was trying to resize images with using android graphics bitmap. There is no error in code but when i build the project it throws out "System.NotSupportedException: Don't know about Android.Graphics.Bitmap" exception.
I tried ticking Common Language Runtime Exceptions and rebuilding the project both didnt work.
Here is my code
[Activity(MainLauncher = false, Theme = "#style/MyTheme")]
public class Duzenle_Activity : ActionBarActivity
{
public static ListView liw;
Intent intent = new Intent();
public Dialog dialog;
public static int toplam_hesap_tutucu;
public static Duzenle_Adapter adapt;
public static TextView toplam;
private BackgroundWorker bw = new BackgroundWorker();
public static int toplam_hesap = 0;
public List<Sepet> gecici_sepet;
List<Yemek_Liste> yemek_ = new List<Yemek_Liste>();
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
SetContentView(Resource.Layout.menu_duzenle);
var toolbar = FindViewById<Toolbar>(Resource.Id.toolbar);
SetSupportActionBar(toolbar);
SupportActionBar.Title = "Duzenle";
yemek_ = MainActivity.db.selectItem();
liw = FindViewById<ListView>(Resource.Id.listv_duzenle);
adapt = new Duzenle_Adapter(this, Resource.Layout.duzenle_model, yemek_,this);
liw.Adapter = adapt;
var toolbarBottom = FindViewById<Toolbar>(Resource.Id.toolbar_bottom_duzenle);
toolbarBottom.InflateMenu(Resource.Menu.ekle_action);
toolbarBottom.MenuItemClick += (sender, e) =>
{
if (e.Item.TitleFormatted.ToString() == "Ekle")
{
var transaction = FragmentManager.BeginTransaction();
var dialogFragment = new Dialog_Ekle(this);
dialogFragment.Show(transaction, "dialog_fragment");
}
};
}
protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
{
base.OnActivityResult(requestCode, resultCode, data);
if (resultCode == Result.Ok)
{
Duzenle_Adapter adapter = ((Duzenle_Adapter)liw.Adapter);
Bitmap mBitmap = null;
mBitmap = Android.Provider.MediaStore.Images.Media.GetBitmap(ContentResolver, data.Data);
Bitmap originalImage = BitmapFactory.DecodeByteArray(mBitmap.ToArray<Byte>(), 0, mBitmap.ByteCount);
Bitmap resizedImage = Bitmap.CreateScaledBitmap(originalImage, 25, 25, false);
adapter.al_getir().adresler = resizedImage;
adapter.NotifyDataSetChanged();
Console.WriteLine("ADRES1" + " " + data.Data);
}
}
public void tikla()
{
var imageIntent = new Intent();
imageIntent.SetType("image/*");
imageIntent.SetAction(Intent.ActionGetContent);
StartActivityForResult(
Intent.CreateChooser(imageIntent, "Select photo"), 0);
}
}
And i get the image from gallery as uri.
Edit : Why is it throwing this exception when there is no error in code. Its actually strange. It cant be about the android.graphics library right?
Edit 2 : I save these bitmaps to database and then display it in listview
Bitmap a = sepet[position].adres;
tut.img.SetImageBitmap(a);
Based on what I got earlier from you please try this:
protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
{
base.OnActivityResult(requestCode, resultCode, data);
if (resultCode == Result.Ok)
{
Duzenle_Adapter adapter = ((Duzenle_Adapter)listView1.Adapter);
//adapter.SelectedYemek.ImageUri = data.Data;
var mBitmap = Android.Provider.MediaStore.Images.Media.GetBitmap(ContentResolver, data.Data);
adapter.SelectedYemek.ImageBitmap = Bitmap.CreateScaledBitmap(mBitmap, 80, 80, false);
adapter.NotifyDataSetChanged();
}
}
Related
Good morning, I'm creating activity which take picture then store it in file. But I had this error :
BitmapFactory: Unable to decode stream: java.io.FileNotFoundException: .jpg (No such file or directory)
Also I want to know how to store this picutre file into my room db I have a class "Photo".
Thank you.
Here is my code:
takepictureActivity
public class PrendrePhoto extends AppCompatActivity {
private ImageView imageView;
private EditText titrImg2;
private Button take;
private String pathPic;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_prendre_photo);
imageView = (ImageView) findViewById(R.id.imageTaken);
titrImg2 = findViewById(R.id.titreImg2);
take = findViewById(R.id.take);
take.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
takePicture();
}
});
}
private void takePicture() {
Intent takepic = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takepic.resolveActivity(getPackageManager()) != null) {
File pic = null;
pic = creerPhotoFile();
if (pic != null) {
pathPic = pic.getPath();
System.out.println("pic créer");
System.out.println(pathPic);
startActivityForResult(takepic, 1);
}else {
System.out.println("pic null");
}
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent
data)
{
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == 1) {
Bitmap photo = BitmapFactory.decodeFile(pathPic);
imageView.setImageBitmap(photo);
}
}
//Hna je dois crée filePhoto
}
private File creerPhotoFile() {
ZonedDateTime now = ZonedDateTime.now();
String d = ("" + now.getDayOfMonth() + "/" + now.getMonthValue() +
"/" + now.getYear());
String heure = "" + now.getHour() + " : " + now.getMinute();
String titre = titrImg2.getText().toString();
File temp = new File("temp");
temp.mkdirs();
System.out.println(temp.getPath());
File image = null;
/* try {
image = File.createTempFile(titre, ".jpg",temp);//Even with this
it didn't work
} catch (IOException e) {
e.printStackTrace();
}*/
image = new File(titre + ".jpg");
return image;
}
}
Photo.java
#Entity
public class Photo implements Serializable
{
#PrimaryKey(autoGenerate = true)
private int idP;
private String titre;
private String path ;//this path to get to help to display this picture
private String dateHeure ;
public Photo(String titre, String dateHeure) {
this.titre = titre;
this.dateHeure = dateHeure;
}
}
Even after doing all the logic of creating a unique file path you are using
String titre = titrImg2.getText().toString();
Which is (as per the name suggest) image title, which is coming form UI.
image = new File(titre + ".jpg");
return image;
I think you need to look into this.
As far as saving images in room goes, it is not recommended. But if you have to do it then you can use BLOB.
Images are usually stored as a BLOB and room does provide this
datatype. BLOB Documentation
Implementation can be done like:
#ColumnInfo(typeAffinity = ColumnInfo.BLOB)
private byte[] image;
}
This is my code and when i run the code then output will be "**you haven't picked images"**
sdk which i use currently in this app
android {
compileSdkVersion 28
defaultConfig {
applicationId "com.example.letsget.humanitysavior"
minSdkVersion 21
targetSdkVersion 28
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
Here is the manifests permissions
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.RECORD_AUDIO" />
Here is the fragment code
public class NewPostPublicFragment extends Fragment {
public NewPostPublicFragment() {
// Required empty public constructor
}
private int PICK_IMAGE_MULTIPLE = 3;
String imageEncoded;
List<String> imagesEncodedList;
private GridView gvGallery;
private NewPostImagesAdapter galleryAdapter;
CarouselView carouselView;
private ArrayList<Uri> mArrayUri;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_new_post_public, container, false);
gvGallery = view.findViewById(R.id.gridview);
ImageView selectimgicon = view.findViewById(R.id.selectimgicon);
ImageView selectvideoicon = view.findViewById(R.id.selectvideoicon);
ImageView selectcameraicon = view.findViewById(R.id.selectcameraicon);
carouselView = view.findViewById(R.id.carouselview);
final TextInputEditText postcategories = view.findViewById(R.id.postcategories);
//carouselView.setPageCount(mThumbIds.length);
//carouselView.setImageListener(imageListener);
//for image selection
selectimgicon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//LOGIC FOR PROFILE PICTURE
selectImagesFromGallery();
}
});
postcategories.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final CharSequence[] items = { "Book", "Cloth", "Electronic", "Furniture", "Bag", "Social Post", "Other" };
AlertDialog.Builder postCategoryBuilder = new AlertDialog.Builder(v.getContext(),AlertDialog.THEME_HOLO_LIGHT);
postCategoryBuilder.setTitle("Select Post Category");
postCategoryBuilder.setIcon(R.mipmap.categoryicon);
postCategoryBuilder.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// the user clicked on colors[which]
postcategories.setText(items[which]);
}
});
postCategoryBuilder.show();
}
});
return view;
}
ImageListener imageListener = new ImageListener() {
#Override
public void setImageForPosition(int position, ImageView imageView) {
//imageView.setImageResource(mThumbIds[position]);
imageView.setImageURI(mArrayUri.get(position));
}
};
private void selectImagesFromGallery() {
Intent intent = new Intent();
intent.setType("image/*");
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Image"), PICK_IMAGE_MULTIPLE);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try {
Log.v(TAG, "requestCode=" + requestCode + ", resultCode = "+ resultCode + ", data = " + data);
// When an Image is picked
if (requestCode == PICK_IMAGE_MULTIPLE && resultCode == RESULT_OK && data != null) {
// Get the Image from data
String[] filePathColumn = { MediaStore.Images.Media.DATA };
imagesEncodedList = new ArrayList<String>();
if(data.getData()!=null){
Uri mImageUri = data.getData();
// Get the cursor
Cursor cursor = getActivity().getContentResolver().query(mImageUri,
filePathColumn, null, null, null);
// Move to first row
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
imageEncoded = cursor.getString(columnIndex);
cursor.close();
ArrayList<Uri> mArrayUri = new ArrayList<Uri>();
mArrayUri.add(mImageUri);
galleryAdapter = new NewPostImagesAdapter(getActivity().getApplicationContext(),mArrayUri);
gvGallery.setAdapter(galleryAdapter);
gvGallery.setVerticalSpacing(gvGallery.getHorizontalSpacing());
ViewGroup.MarginLayoutParams mlp = (ViewGroup.MarginLayoutParams) gvGallery
.getLayoutParams();
mlp.setMargins(0, gvGallery.getHorizontalSpacing(), 0, 0);
carouselView.setPageCount(mArrayUri.size());
carouselView.setImageListener(imageListener);
} else {
if (data.getClipData() != null) {
ClipData mClipData = data.getClipData();
ArrayList<Uri> mArrayUri = new ArrayList<Uri>();
for (int i = 0; i < mClipData.getItemCount(); i++) {
ClipData.Item item = mClipData.getItemAt(i);
Uri uri = item.getUri();
mArrayUri.add(uri);
// Get the cursor
Cursor cursor = getActivity().getContentResolver().query(uri, filePathColumn, null, null, null);
// Move to first row
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
imageEncoded = cursor.getString(columnIndex);
imagesEncodedList.add(imageEncoded);
cursor.close();
galleryAdapter = new NewPostImagesAdapter(getActivity().getApplicationContext(),mArrayUri);
gvGallery.setAdapter(galleryAdapter);
gvGallery.setVerticalSpacing(gvGallery.getHorizontalSpacing());
ViewGroup.MarginLayoutParams mlp = (ViewGroup.MarginLayoutParams) gvGallery
.getLayoutParams();
mlp.setMargins(0, gvGallery.getHorizontalSpacing(), 0, 0);
}
Log.v("LOG_TAG", "Selected Images" + mArrayUri.size());
}
}
} else {
Toast.makeText(getContext(), "You haven't picked Image",
Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
Toast.makeText(getContext(), "Something went wrong", Toast.LENGTH_LONG)
.show();
}
}
}
when I run this app and tap on image button then it open the gallery and select the images after that when i press the done button then it's not display images it just display toast message you haven't picked images
Check these Steps:
Give permission to use camera in AndroidManifest.xml
Use this code to get image properly
String RequestCode=123;
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == RequestCode && resultCode== RESULT.OK){
//Here get your image code
}
}
Also Check Toast in your OnActivityResult() method and check if condition is true or false. Probably your if condition is false that's why image is not received from gallery.
Hello I am getting this strange error in my app. The first time the application starts it runs however when I store a photo from the camera the app crashes and shows this log. The app takes photo from the camera or gallery and saves them in the database and displays the photo in a custom gridview.
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.notepad.isidorosioannou.notepad/com.example.notepad.isidorosioannou.notepad.CameraMainActivity}: android.database.sqlite.SQLiteException: unknown error (Sqlite code 0): Native could not create new byte[], (OS error - 0:Success)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2444)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2504)
at android.app.ActivityThread.access$900(ActivityThread.java:165)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1368)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:150)
at android.app.ActivityThread.main(ActivityThread.java:5546)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:794)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:684)
Caused by: android.database.sqlite.SQLiteException: unknown error (Sqlite code 0): Native could not create new byte[], (OS error - 0:Success)
at android.database.CursorWindow.nativeGetBlob(Native Method)
at android.database.CursorWindow.getBlob(CursorWindow.java:403)
at android.database.AbstractWindowedCursor.getBlob(AbstractWindowedCursor.java:45)
at com.example.notepad.isidorosioannou.notepad.DatabaseAdapt.cursorToImage(DatabaseAdapt.java:179)
at com.example.notepad.isidorosioannou.notepad.DatabaseAdapt.loadAllImages(DatabaseAdapt.java:162)
at com.example.notepad.isidorosioannou.notepad.CameraMainActivity.onCreate(CameraMainActivity.java:48)
Here is part of the code from my db Helper and actually the methods that i get the error in the log.
public static final String CAMERANOTE_CREATE = "create table " + CAMERANOTE_TABLE + " ( "
+ CAMERA_ID + " integer primary key autoincrement, "
+ CAMERA_TITLE + " text not null, "
+ CAMERA_DESC + " text not null, "
+ CAMERA_PATH + " blob);";
public long createCamera(DataImage image){
ContentValues contentValues = new ContentValues();
contentValues.put(CAMERA_TITLE,image.getTitle());
contentValues.put(CAMERA_DESC,image.getDesc());
contentValues.put(CAMERA_PATH,image.getPath());
long insert= sqlDB.insert(CAMERANOTE_TABLE,null,contentValues);
return insert;
public ArrayList<DataImage> loadAllImages(){
ArrayList<DataImage> imageList= new ArrayList<>();
Cursor cursor = sqlDB.query(CAMERANOTE_TABLE,new String[]{CAMERA_ID,CAMERA_TITLE,CAMERA_DESC,CAMERA_PATH},null,null,null,null,null);
cursor.moveToFirst();
while (!cursor.isAfterLast()){
DataImage image = cursorToImage(cursor);
imageList.add(image);
}
cursor.close();
return imageList;
}
public Cursor loadAllTasks (){
Cursor cursor = sqlDB.query(TODOLIST_TABLE,new String[]{TODO_ID,TODO_TEXT,TODO_CHECKED},null,null,null,null,null);
return cursor;
}
private DataImage cursorToImage(Cursor cursor){
int id = cursor.getInt(cursor.getColumnIndex(DatabaseAdapt.CAMERA_ID));
String text = cursor.getString(cursor.getColumnIndex(DatabaseAdapt.CAMERA_TITLE));
String desc = cursor.getString(cursor.getColumnIndex(DatabaseAdapt.CAMERA_DESC));
byte [] path = cursor.getBlob(cursor.getColumnIndex(DatabaseAdapt.CAMERA_PATH));
DataImage image= new DataImage(id,text,desc,path);
return image;
}
}
Here is my main activity:
public class CameraMainActivity extends AppCompatActivity implements View.OnClickListener {
private ImageView buttonImage;
private GridView gridView;
private ArrayList<DataImage> imageList;
public DatabaseAdapt dbAdapter;
private CameraAdapter cameraAdapter;
private AlertDialog alertBuilder;
private Uri imageUri;
private Bitmap bitMap;
private byte [] byteArray;
private static final int REQUEST_CAMERA_CODE = 1;
private static final int REQUEST_GALLERY_CODE=2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_camera_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar3);
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
buttonImage = (ImageView)findViewById(R.id.cameraOptionButton);
buttonImage.setOnClickListener(this);
gridView = (GridView) findViewById(R.id.gridviewPhoto);
dbAdapter = new DatabaseAdapt(getApplicationContext());
dbAdapter.open();
imageList = new ArrayList<>();
imageList = dbAdapter.loadAllImages();
cameraAdapter = new CameraAdapter(this,imageList);
gridView.setAdapter(cameraAdapter);
createAlertWindow();
}
public void onDestroy(){
super.onDestroy();
dbAdapter.close();
}
#Override
public void onClick(View v) {
if (v.getId()==R.id.cameraOptionButton){
alertBuilder.show();
}
}
private void createAlertWindow(){
AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
alertDialog.setTitle(R.string.alert_title)
.setItems(R.array.alert_dialog, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if(which==0){
activateCamera();
}
else{
chooseFromGallery();
}
}
});
alertBuilder = alertDialog.create();
}
private void activateCamera(){
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent,REQUEST_CAMERA_CODE);
}
private void chooseFromGallery(){
Intent galleryIntent = new Intent(Intent.ACTION_PICK);
galleryIntent.setType("image/*");
startActivityForResult(galleryIntent,REQUEST_GALLERY_CODE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == REQUEST_CAMERA_CODE && resultCode == RESULT_OK && data !=null){
Bundle extra = data.getExtras();
bitMap = extra.getParcelable("data");
byteArray = convertToByte(bitMap);
}
else if(requestCode==REQUEST_GALLERY_CODE && resultCode == RESULT_OK && data !=null){
imageUri = data.getData();
bitMap = decodeUri(imageUri,400);
byteArray=convertToByte(bitMap);
}
Intent intent = new Intent(this,CameraSaveActivity.class);
intent.putExtra("byteImage",byteArray);
startActivity(intent);
}
private Bitmap decodeUri(Uri image,int size){
try {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds=true;
BitmapFactory.decodeStream(getContentResolver().openInputStream(image),null,options);
int width = options.outWidth;
int height = options.outHeight;
int scale = 1;
while (true){
if(width/2<size || height/2<size){
break;
}
width /=2;
height /=2;
scale *=2;
}
BitmapFactory.Options options2 = new BitmapFactory.Options();
options2.inSampleSize=scale;
return BitmapFactory.decodeStream(getContentResolver().openInputStream(image),null,options2);
}catch (Exception e){
e.printStackTrace();
}
return null;
}
private byte[] convertToByte(Bitmap bitmap){
ByteArrayOutputStream b = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG,100,b );
return b.toByteArray();
}
}
and here is my second activity where I just preview the image and save it.
public class CameraSaveActivity extends AppCompatActivity implements View.OnClickListener {
private EditText cameraSaveTitle , cameraSaveDesc;
private ImageView cameraPreview;
private Button saveButton;
private byte [] byteArray;
private DatabaseAdapt adapt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_camera_save);
cameraSaveTitle = (EditText)findViewById(R.id.cameraEditTitle);
cameraSaveDesc = (EditText)findViewById(R.id.cameraEditDesc);
cameraPreview = (ImageView)findViewById(R.id.cameraPreview);
saveButton = (Button)findViewById(R.id.saveCameraButton);
Intent intent = getIntent();
byteArray = intent.getByteArrayExtra("byteImage");
ByteArrayInputStream imageStream = new ByteArrayInputStream(byteArray);
cameraPreview.setImageBitmap(BitmapFactory.decodeStream(imageStream));
adapt = new DatabaseAdapt(this);
adapt.open();
saveButton.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if(v.getId()==R.id.saveCameraButton){
String text1 = cameraSaveTitle.getText().toString();
String text2 = cameraSaveDesc.getText().toString();
DataImage image = new DataImage(text1,text2,byteArray);
adapt.createCamera(image);
finish();
}
}
public void onDestroy(){
super.onDestroy();
adapt.close();
}
}
Can someone please help. I searched but I could not find a solution
Your problem is that you are storing path in CAMERA_PATH, which is string and trying to get a Blob. There is a type mismatch and thats why the error is thrown.
You need to insert a blob in the CAMERA_PATH before you try retrieving a blob from there.
I'm trying to encode a String in QR Code wusing ZXING library. this is the lines of code corresponding to this :
Button btn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = (Button)findViewById(R.id.button1);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent("com.google.zxing.client.android.ENCODE");
intent.addCategory(Intent.CATEGORY_DEFAULT);
intent.putExtra("ENCODE_TYPE", "TEXT_TYPE");
intent.putExtra("ENCODE_DATA","HELLO WORLD");
startActivityForResult(intent, 0);
}
});
}
After clicking on the button i have a "force close"
After looking in some websites, we say that it works just with these lines. unfortunately, it isnt for me.
PLEASE Can you give some advices to make it working. OR if you have other way to integrate a QRCode generator to my ANDROID App it will be great too.
Enzo, this is another way to get it working, try this:
private void encode(String uniqueID) {
// TODO Auto-generated method stub
BarcodeFormat barcodeFormat = BarcodeFormat.QR_CODE;
int width0 = 500;
int height0 = 500;
int colorBack = 0xFF000000;
int colorFront = 0xFFFFFFFF;
QRCodeWriter writer = new QRCodeWriter();
try
{
EnumMap<EncodeHintType, Object> hint = new EnumMap<EncodeHintType, Object>(EncodeHintType.class);
hint.put(EncodeHintType.CHARACTER_SET, "UTF-8");
BitMatrix bitMatrix = writer.encode(uniqueID, barcodeFormat, width0, height0, hint);
int width = bitMatrix.getWidth();
int height = bitMatrix.getHeight();
int[] pixels = new int[width * height];
for (int y = 0; y < height; y++)
{
int offset = y * width;
for (int x = 0; x < width; x++)
{
pixels[offset + x] = bitMatrix.get(x, y) ? colorBack : colorFront;
}
}
Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
ImageView imageview = (ImageView)findViewById(R.id.qrCode);
imageview.setImageBitmap(bitmap);
} catch (WriterException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
This line:
Intent intent = new Intent("com.google.zxing.client.android.ENCODE");
identifies the Activity you are calling with the Intent. In order for it to work that Activity must exist on the device. If you haven't implemented the Activity inside your project (that is, there is no class ENCODE inside your com.google.zxing.client.android package) then you will be calling an external application from yours. If there are no applications on the device/emulator that respond to the broadcast for com.google.zxing.client.android.ENCODE then you are not going to get anywhere with this solution.
You either need to install an application that will respond to com.google.zxing.client.android.ENCODE or find another way to do it.
It is possible to generate the barcode yourself using zxing libraries within your application. Have a look at the project here at Google Code for some downloads. This will remove your dependancy on an external application existing, providing a more thorough solution.
Rather than Zxing library you are also able to get the string from QRCode by using intents as below :
try {
Intent intent = new Intent("com.google.zxing.client.android.SCAN");
intent.putExtra("SCAN_MODE", "QR_CODE_MODE"); // "PRODUCT_MODE for bar codes
startActivityForResult(intent, 0);
} catch (Exception e) {
Uri marketUri = Uri.parse("market://details?id=com.google.zxing.client.android");
Intent marketIntent = new Intent(Intent.ACTION_VIEW,marketUri);
startActivity(marketIntent);
}
And on activity result as below :
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 0) {
if (resultCode == RESULT_OK) {
String contents = data.getStringExtra("SCAN_RESULT");
Log.v("MESSAGE: ", contents);
Intent in = new Intent(MainActivity2.this,MainActivity3.class);
Bundle b3= new Bundle();
b3.putString("content",contents);
in.putExtras(b3);
startActivity(in);
}
}
}
It may be helpful for you.
Thank You.
simple program: 2 buttons (previous/next) and a textview to show text.
by intent I created an Index (inside a method)
private void index(){
Intent i = new Intent(this, Index.class);
startActivityForResult(i, 1);
}
Index.class (with 3 buttons):
button1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String result = "1";
Intent returnIntent = new Intent();
returnIntent.putExtra("result",result);
setResult(RESULT_OK,returnIntent);
finish();
}
});
Main.class
String value = "1";
final String prog1[] = new String[16];
final String prog2[] = new String[105];
final String prog3[] = new String[66];
int a;
int b;
int c=3;
int array1start = 0; int array1end = 15;
int array2start = 0; int array2end = 105;
int array3start = 0; int array3end = 65;
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
if (value.equals("1")){
a = array1start;
b = array1end;
prog=prog1;
}
else if (value.equals("2")){
a = array2start;
b = array2end;
prog=prog2;
textView1.setText(""+prog[a]);
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
if(resultCode == RESULT_OK){
String result=data.getStringExtra("result");
value=result;
Toast toast2=Toast.makeText(this,"value: "+value,Toast.LENGTH_LONG);
toast2.show();
}
if (resultCode == RESULT_CANCELED) {
//Write your code on no result return
}}
}//onAcrivityResult
at this point, choosen choice in index class should be change a result string to "value" string in main class
private void index(){
Intent i = new Intent(this, Index.class);
startActivityForResult(i, 1);
}
my textview take data from array1 or array2 by index class
so, I dont' understand how update textview (because index value is correct).
thanks for the help
Put you code into function onActivityResult
if (value.equals("1")){
a = array1start;
b = array1end;
prog=prog1;
}
else if (value.equals("2")){
a = array2start;
b = array2end;
prog=prog2;
textView1.setText(""+prog[a]);