Display image as a byte array: doesn't work - android

My issue is: I have a byte array which must be display with ImageView. This is my code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ImageView imageView = (ImageView)findViewById(R.id.show_image);
byte[] arrayBytes = ...; // It's initialized
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSample = 4;
imageView.setImageBitmap(BitmapFactory.decodeByteArray(arrayBytes, 0, arrayBytes.length, options));
}
The code of activity_main.xml is:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="#+id/show_image"
android:contentDescription="#string/Imagen"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"/>
</RelativeLayout>
But it doesn't work: no image has been displayed! What's I'm doing wrong?
To get byte array[], I read a double[][] array 2D from a file. To get byte value for each element of the matrix I used:
byte[] byteArray = new byte[SIZE];
int k = 0;
for(...i) {
for(...j) {
byteArray[k] = Double.valueOf(matrix[i][j]).byteValue();
k++;
}
}
Thanks in advance

Related

imageview not showing, wieght and height 0

Hello and thank you for taking the time to read this. I am a beginner in Android though I have experience in C# and C++. I am currently generating a qr with a button that is supposed to turn an invisible imageview visible. here is my xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".ChargeActivity">
<include layout="#layout/toolbar" />
<EditText
android:id="#+id/currency_amount"
android:layout_width="200dp"
android:layout_height="40dp"
android:layout_centerHorizontal="true"
android:layout_marginTop="272dp"
android:inputType="numberDecimal"
android:hint="Ingrese el monto"
app:layout_anchor="#+id/include"
app:layout_anchorGravity="center" />
<Spinner
android:id="#+id/spinner"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_alignParentTop="true"
android:layout_alignParentEnd="true"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="-143dp"
android:layout_marginEnd="-12dp"
android:layout_marginBottom="3dp" />
<Button
android:id="#+id/generateqr_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:gravity="center"
android:onClick="onClick"
android:text="Generar QR"
app:layout_anchor="#+id/include"
app:layout_anchorGravity="center" />
<ListView
android:id="#+id/transactions"
android:layout_width="match_parent"
android:layout_height="300dp"
android:layout_alignParentStart="true"
android:layout_alignParentBottom="true"
android:layout_marginBottom="19dp" />
<ImageView
android:id="#+id/qr_image"
android:layout_width="300dp"
android:layout_height="300dp"
android:layout_centerInParent="true"
/>
</RelativeLayout>
and here is my java
public class ChargeActivity extends AppCompatActivity {
public static final String ARG_USER = "USER";
String user = "";
private Bitmap bitmap;
private ImageView qrImage;
private String inputValue;
private EditText amount;
private ListView transactions;
private Spinner spinner;
private static final String[] currencies = {"Bolivars", "Petros", "Dollars"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_charge);
user = getIntent().getStringExtra(ARG_USER);
qrImage = findViewById(R.id.qr_image);
qrImage.setVisibility(View.GONE);
Toolbar toolbar = findViewById(R.id.toolbar);
toolbar.setTitle(user);
setSupportActionBar(toolbar);
// Get a support ActionBar corresponding to this toolbar
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
setContentView(R.layout.activity_charge);
//Spinner Setup
spinner = (Spinner) findViewById(R.id.spinner);
final ArrayAdapter<String> adapter = new ArrayAdapter<String>(ChargeActivity.this,
android.R.layout.simple_spinner_item, currencies);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
//ListView Setup
transactions = findViewById(R.id.transactions);
ArrayList<String> transaction_list = new ArrayList<String>();
transaction_list.add("bolaeyunke te ha enviado 1920 petros");
transaction_list.add("bolaeyunke te ha enviado 1932232320 bolivares");
transaction_list.add("bolaeyunke te ha enviado 1923230 dolares");
transaction_list.add("El Comandante te ha enviado 120 petros");
ArrayAdapter transaction_adapter = new ArrayAdapter(ChargeActivity.this, android.R.layout.simple_list_item_1, transaction_list);
transactions.setAdapter(transaction_adapter);
//Generate QR button setup
Button generateQRButton = findViewById(R.id.generateqr_button);
generateQRButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
amount = findViewById(R.id.currency_amount);
String montos = amount.getText().toString();
inputValue = user + ";" + adapter.getItem(spinner.getSelectedItemPosition()).toString()+";"+amount.getText().toString();
//setting up for qr display
WindowManager manager = (WindowManager) getSystemService(WINDOW_SERVICE);
Display display = manager.getDefaultDisplay();
Point point = new Point();
display.getSize(point);
int width = point.x;
int height = point.y;
int smallerDimension = width < height ? width : height;
smallerDimension = smallerDimension * 3 / 4;
QRGEncoder qrgEncoder = new QRGEncoder(inputValue, null, QRGContents.Type.TEXT, smallerDimension);
qrgEncoder.setColorBlack(Color.RED);
qrgEncoder.setColorWhite(Color.BLUE);
try {
// Getting QR-Code as Bitmap
bitmap = qrgEncoder.getBitmap();
// Setting Bitmap to ImageView
qrImage.setImageBitmap(Bitmap.createScaledBitmap(bitmap, 120, 120, false));
qrImage.setVisibility(View.VISIBLE);
//Still need to implement an escape from showing the qr image
} catch (Exception e) {
e.getMessage();
}
}
});
}
My imageview not only stays invisible, but when I debug, I see that the width and height are 0 for the imageview. I get no errors but it just does not show. I added the bitmap resizing after reading through some questions and thinking that that was the problem.

How to programmatically take screenshot of an android application without notification and navigation bars

I am using the below code for taking screenshot in my application.
View rootView = findViewById(android.R.id.content).getRootView();
rootView.setDrawingCacheEnabled(true);
rootView.buildDrawingCache(true);
Bitmap bitmap = rootView.getDrawingCache();
But I am getting an image with two black portion in the top and bottom by the notification and navigation bars. I need to remove those black areas. I need not to replace those area with the notification and navigation bars. But i need the toolbar.
take the drawing cache of the root Layout as below:
//onCreate
setContentView(R.layout.activity_main);
layout = (RelativeLayout) findViewById(R.id.activity_main);
layout.setDrawingCacheEnabled(true);
And to get bitmap, the usual way,
Bitmap bitmap = layout.getDrawingCache();
activity_main:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<android.support.v7.widget.Toolbar
android:id="#+id/toolBar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:background="#color/colorPrimary" />
<!--other content-->
</RelativeLayout>
Use Below Method:
public static Bitmap loadBitmapFromView(Context context, View v) {
DisplayMetrics dm = context.getResources().getDisplayMetrics();
v.measure(View.MeasureSpec.makeMeasureSpec(dm.widthPixels, View.MeasureSpec.EXACTLY),
View.MeasureSpec.makeMeasureSpec(dm.heightPixels, View.MeasureSpec.EXACTLY));
v.layout(0, 0, v.getMeasuredWidth(), v.getMeasuredHeight());
Bitmap returnedBitmap = Bitmap.createBitmap(v.getMeasuredWidth(),
v.getMeasuredHeight(), Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(returnedBitmap);
v.draw(c);
return returnedBitmap;
}
Pass your parent view inside the argument.
Take this to another Linear Layout
<LinearLayout
android:id="#+id/linear"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/munch"
android:id="#+id/munchscreen"/>
<ImageView
android:layout_width="200dp"
android:layout_height="200dp"
android:id="#+id/screenshots"
android:contentDescription="#string/app_name"
/>
</LinearLayout>
Now find Id for this Linear Layout on oncreate() method making it global variable
LinearLayout ll;
ll = (LinearLayout)findViewById(R.id.linear);
now capture this screen:
ll.setDrawingCacheEnabled(true);
ll.buildDrawingCache(true);
Bitmap cs = Bitmap.createBitmap(ll.getDrawingCache());
ll.setDrawingCacheEnabled(false);
Now set this bitmap to your ImageView.
Following is the XML layout file where I have added a button, textview and an imageview in a linear layout. And I have also added onClick attribute in the button.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_screenshoat"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.ncrypted.myapplication.Screenshoat">
<Button
android:id="#+id/btnScreenshot"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Taake screen shot"/>
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/imageView"/>
</LinearLayout>
This is android activity file where I have added some java code to take screenshot and import android.graphics.Bitmap;, java.io.ByteArrayOutputStream;, java.io.File; etc.
public class Screenshoat extends AppCompatActivity {
Button btnScreenshot;
Bitmap mbitmap;
ImageView imageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_screenshoat);
btnScreenshot = (Button) findViewById(R.id.btnScreenshot);
imageView = (ImageView) findViewById(R.id.imageView);
btnScreenshot.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mbitmap = getBitmapOFRootView(v);
imageView.setImageBitmap(mbitmap);
createImage(mbitmap);
Toast.makeText(Screenshoat.this, "Screen shoat created", Toast.LENGTH_SHORT).show();
}
});
}
public Bitmap getBitmapOFRootView(View v) {
View rootview = v.getRootView();
rootview.setDrawingCacheEnabled(true);
Bitmap bitmap1 = rootview.getDrawingCache();
return bitmap1;
}
public void createImage(Bitmap bmp) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 40, bytes);
File file = new File(Environment.getExternalStorageDirectory() +
"/capturedscreenandroid.jpg");
try {
file.createNewFile();
FileOutputStream outputStream = new FileOutputStream(file);
outputStream.write(bytes.toByteArray());
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Add Permission to read and write external storage
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

ImageView size is changed when changing the image

I have the problem that I have a layout with an ImageView. With AsyncTask I load an image from the web. It is a panorama picture. If I start up the Fragment, the image I load with src="#drawable/pano" is shown perfectly. It has full height and I can scroll through the panorama.
As soon as the new image is loaded into the ImageView the imageview rescales so that the height is:
Before the AsyncTask (Image is loaded from drawables...):
And this is after the AsyncTask loaded the image:
Here is my xml file:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<HorizontalScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_centerInParent="true"
android:overScrollMode="never"
android:scrollbars="none" >
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="match_parent" >
<ImageView
android:id="#+id/img1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentTop="true"
android:adjustViewBounds="true"
android:scaleType="fitCenter"
android:src="#drawable/pano" />
</RelativeLayout>
</HorizontalScrollView>
AsyncTask Code:
public class DownloadPanorama extends
AsyncTask<ImageView, Void, Bitmap> {
ImageView imageView;
Bitmap bm;
public DownloadPanorama(ImageView mChart) {
imageView = mChart;
}
#Override
protected Bitmap doInBackground(ImageView... imageViews) {
return download_Image((String) imageView.getTag());
}
#Override
protected void onPostExecute(Bitmap result) {
imageView.setImageBitmap(result);
}
private Bitmap download_Image(String url) {
Bitmap bm = null;
try {
URL aURL = new URL(url);
URLConnection conn = aURL.openConnection();
conn.connect();
InputStream is = conn.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
bm = BitmapFactory.decodeStream(bis);
bis.close();
is.close();
return bm;
}
}
Also happens when not using AsyncTask and only using raw setImageBitmap... So I don't know if I have to change the scaleType in my xml file or if I need to set it again after loading a new image?
I would try changing:
android:layout_height="wrap_content"
to
android:layout_height="fill_parent"
in your ImageView.
If that doesn't work, you might be able to scale your bitmap:
myBitmap = Bitmap.createScaledBitmap(myBitmap, width, height,true);
EDIT
It sounds like from your comments and updated question that you know the size you would like the image to be (1200x400). You have two things you can do to get this size. The first, and recommended, is to replace the line
bm = BitmapFactory.decodeStream(bis);
with
BitmapFactory.Options options = new BitmapFactory.Options();
options.outWidth=1200;
options.outHeight=400;
bm = BitmapFactory.decodeStream(bis, new Rect(0,0,0,0), options);
The other option is to change your View bounds. In your comments above, it sounds like the bounds might change, so you would have to repeat this each time you loaded a new image of different size:
RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) imageView.getLayoutParams();
params.width = 1200;
params.height = 400;
imageView.setLayoutParams(params);
You need to change
android:adjustViewBounds="true"
to
android:adjustViewBounds="false"

button with image is not responding to onclick listener when scrolling

I am a android beginner, I have added images dynamically inside the linear layout, which will scroll from right to left. The problem is that the images are moving / scrolling properly but when I click on it the on-click listener is not called.
Actually when moving the images the image button is moving but the onclick position is not changed according to the image scrolling.
public class ImageLayoutsActivity extends Activity {
int ImageInt, fromXDelta, toXDelta;
int PosInt, myHarizantalLayoutInt, aDisplayInt, aDisplayDiv = 0;
AnimationSet myAnimation = new AnimationSet(true);
LinearLayout myHarizantalLayout;
HorizontalScrollView myHorizontalScroll;
View myView;
Intent myIntent;
private Button clickedButton = null;
public int currentimageindex = 0;
TranslateAnimation myTranslateAnimation = null;
private String[] imgArr = { "icn01", "icn02" };
private String[] URLArray = { "http://www.google.co.in/",
"http://in.yahoo.com/?p=us" };
LinearLayout.LayoutParams Parems;
Display aDisplay;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
View aView = LayoutInflater.from(GroupActivity.myGroup).inflate(
R.layout.horizantal, null);
setContentView(aView);
GroupActivity.myGroup.setTitle("---CII---");
aDisplay = getWindowManager().getDefaultDisplay();
aDisplayInt = aDisplay.getWidth();
aDisplayDiv = aDisplayInt / 5;
Log.i("value##########################", String.valueOf(aDisplayDiv));
Log.i("aDisplayInt##########################",
String.valueOf(aDisplayInt));
// define xml layout here
myHarizantalLayout = (LinearLayout) findViewById(R.id.horiztonal_outer_layout_id);
myHorizontalScroll = (HorizontalScrollView) findViewById(R.id.horiztonal_scrollview_id);
// Button aBtnOne = (Button) findViewById(R.id.BtnOneId);
// Hide HorizantalLayout scroll bar
myHorizontalScroll.setHorizontalScrollBarEnabled(false);
myHorizontalScroll.isSmoothScrollingEnabled();
myHarizantalLayout.measure(aDisplay.getWidth(), aDisplay.getHeight());
Log.v("EmailActivity#########", myHarizantalLayout.getMeasuredHeight()
+ ", " + myHarizantalLayout.getMeasuredWidth());
int aLayoutInt = myHarizantalLayout.getMeasuredWidth();
Log.i("aLayoutInt###########", String.valueOf(aLayoutInt));
// Add images in for loop
for (int i = 0; i < imgArr.length; i++) {
// int aVal=myHarizantalLayout.getChildCount();
Log.i("ImageInt############################", "=====Inside the loop======");
// create button instance
final Button aImgBtn = new Button(this);
// myButton.setOnClickListener(null);
// add background image resource files
ImageInt = getResources().getIdentifier(imgArr[i], "drawable",
getPackageName());
Log.i("ImageInt############################", "ImageInt");
// add integer image values to drawable control
Drawable aDrawable = this.getResources().getDrawable(ImageInt);
Log.i("aDrawable$$$$$$$$$$$$$$$$$$$$$$$$$", "aDrawable");
// add drawable file to button instance
aImgBtn.setBackgroundDrawable(aDrawable);
aImgBtn.measure(aDisplay.getHeight(), aDisplay.getWidth());
Log.i("aButton#############################", "aButton");
Parems = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
Parems.setMargins(10, 0, 5, 0);
Log.i("Parems%%%%%%%%%%%%%%%%%%%%%%%%%%", "Parems");
// int aParemIn = Parems.width;
// Log.i("aparemIn$$$$$$$$$$$$", String.valueOf(aParemIn));
myHarizantalLayout.measure(aDisplay.getHeight(),
aDisplay.getWidth());
int myHarizantalLayoutInt = myHarizantalLayout.getMeasuredWidth();
Log.i("myHarizantalLayoutInt$$$$$$$$$$$$",
String.valueOf(myHarizantalLayoutInt));
myTranslateAnimation = new TranslateAnimation(aDisplayInt - 300,
-myHarizantalLayoutInt - aDisplayDiv, 0, 0);
myTranslateAnimation.setDuration(20000);
myTranslateAnimation.setRepeatCount(-1);
myTranslateAnimation.setRepeatMode(1);
myAnimation.addAnimation(myTranslateAnimation);
Log.i("myAnimation###########################", "myAnimation");
aImgBtn.setLayoutParams(Parems);
myHarizantalLayout.addView(aImgBtn);
Log.i("myHarizantalLayout&&&&&&&&&&&&&&&&&&&&&&&&&",
"myHarizantalLayout");
// add animation to HarizantalLayout
myHarizantalLayout.startAnimation(myTranslateAnimation);
// Call webview based on image button click event
aImgBtn.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
Log.i("view$$$$$$$$$$$$#############", "---btn clicked -----");
int aVal = myHarizantalLayout.indexOfChild(view);
Log.i("indexOfChild*************************",
"indexOfChild");
if (view == aImgBtn) {
Log.i("aButton%%%%%%%%%%%%%%%%%%%%%%%%", "aButton");
aImgBtn.setId(aVal);
String aUrlStr = URLArray[aVal];
Log.i("aUrlStr$$$$$$$$$$$$#############", aUrlStr);
}
// Log.i("aUrlStr$$$$$$$$$$$$#############", aUrlStr);
// Pass values to webview activity
}
}
}
xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent" android:layout_height="fill_parent"
android:gravity="bottom" android:background="#00f">
<LinearLayout android:layout_below="#+id/RelativeLayout"
android:layout_width="fill_parent" android:layout_height="fill_parent"
android:orientation="horizontal" android:gravity="bottom">
<ImageView android:id="#+id/barImageId"
android:layout_width="150dp" android:layout_height="58dp"
android:background="#drawable/cii" android:layout_alignParentRight="true" />
<HorizontalScrollView android:layout_width="fill_parent"
android:layout_height="58dp" android:id="#+id/horiztonal_scrollview_id"
android:fadingEdge="none" android:background="#000" >
<LinearLayout android:id="#+id/horiztonal_outer_layout_id"
android:fadingEdge="none" android:layout_height="fill_parent" android:gravity="center_vertical"
android:layout_width="fill_parent" android:background="#f00">
</LinearLayout>
</HorizontalScrollView>
</LinearLayout>
</RelativeLayout>
Try to Use Pager instead of HorizontalScrollView,
This link may be helpful https://github.com/nostra13/Android-Universal-Image-Loader

android frame layout with horizontal scroll bar and ovelapped images

i want to create a Frame layout to place a number of images from database, which need to be a horizontal scrollable list. Image Views are creating dynamically based on database value. Images must be overlapped like the attachment . Here is my xml
<HorizontalScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="true"
android:layout_marginTop="20dp"
>
<FrameLayout
android:id="#+id/frmLayout"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:scrollbars="horizontal"
android:layout_weight="1"
>
</FrameLayout>
</HorizontalScrollView>
and Here is java
public void getAllImages(){
cursorImages = dbAdapter.fetchImages();
if (cursorImages.moveToFirst()) {
BitmapFactory.Options options=new BitmapFactory.Options();
options.inSampleSize = 2;
do {
String filename = cursorImages.getString(cursorImages
.getColumnIndex("filename"));
try {
InputStream ims = getAssets().open("images/" + filename);
Bitmap bm = BitmapFactory.decodeStream(ims,null,options);
Matrix mat = new Matrix();
mat.postRotate(30);
Bitmap bMapRotate = Bitmap.createBitmap(bm, 0, 0, bm.getWidth(), bm.getHeight(), mat, true);
ImageView im = new ImageView (this);
im.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
im.setImageBitmap(bMapRotate);
frmLayout.addView(im,new FrameLayout.LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT));
} catch (IOException ex) {
}
} while (cursorImages.moveToNext());
}
cursorImages.close();
}

Categories

Resources