Why Bitmap.getConfig() returns null? - java

I have some XML-Layout generated ImageView and i want to copy the image i click in a LinearLayout below.
I had assign the follow event to all the ImageView's onClick events:
public void onClick(View v) {
// Take layout where i want to put my copy-image
LinearLayout savingLayout = (LinearLayout)findViewById(R.id.linearSaved);
//Create a new image
ImageView savedImage = new ImageView(savingLayout.getContext());
//Take the bitmap from the object i clicked
Bitmap b = ((BitmapDrawable)((ImageView)v).getDrawable()).getBitmap();
//Take the config of the bitmap. IT RETURNS NULL
Bitmap.Config cfg= b.getConfig();
//Copy the Bitmap and assign it to the new ImageView... IT CRASH (cfg == null)
Bitmap b2 = b.copy(cfg, true);
savedImage.setImageBitmap(b2);
savingLayout.addView(savedImage);
}
So why b.getConfig() returns null? There is a workaround?
Thanks

Use Bitmap.Config.ARGB_8888 instead of b.getConfig() as a workaround.

Related

How to add Custom color Effect on My Custom camera in android

I want to create my custom camera with supports different color
effects for taking images ... I want to custom color effect on my
camera . i put some effect that is Built_In in device but i have no
idea that how i apply other effect like AFTER SNOW FALLING EFFECT
from here and so many other Color Effects.
Please Give me some hints or any link that is helpful for me
My code for effect is
((ImageView)findViewById(R.id.e1)).setOnClickListener(onButtonClick);
private View.OnClickListener onButtonClick = new View.OnClickListener() {
#Override
public void onClick(View v) {
switch(v.getId())
{
case R.id.e1: MonoEffect();
break;}
}
};
private void MonoEffect()
{
Camera.Parameters parameters =mCamera.getParameters();
parameters.setColorEffect(android.hardware.Camera.Parameters.EFFECT_MONO);
mCamera.setParameters(parameters);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
cameraPreviewLayout = (FrameLayout) findViewById(R.id.camera_preview);
//this code is holding an realtime overlay
RelativeLayout layout = (RelativeLayout) findViewById(R.id.preview);
FrameLayout fr = new FrameLayout(this);
fr.setBackgroundResource(R.drawable.snow);
ImageView b1 = new ImageView(this);
b1.setBackgroundResource(R.drawable.snow);
fr.addView(b1);
layout.addView(fr);
/*one solution could be,you if you want a real-time effect on your camera layout,you can add an overlay on the preview as given up.snow is a png format picture with transparent background */ after that... add both the camera output and ta transparent snoweffect as..
Bitmap cameraBitmap =BitmapFactory.decodeByteArray(data, 0, data.length);
Bitmap overlayBitmap = BitmapFactory.decodeResource(getResources(),R.drawable.snow);
Bitmap cameraScaledBitmap = Bitmap.createScaledBitmap(cameraBitmap, 1200, 1600, true);
int wid = cameraScaledBitmap.getWidth();
int hgt = cameraScaledBitmap.getHeight();
Bitmap newImage = Bitmap.createBitmap(wid,hgt, Bitmap.Config.ARGB_8888);
Bitmap overlayScaledBitmap = Bitmap.createScaledBitmap(overlayBitmap, wid, hgt, true);
Canvas canvas = new Canvas(newImage);
canvas.drawBitmap(cameraBitmap , 0, 0, null);
canvas.drawBitmap(overlayScaledBitmap , 0, 0, null);
now you have got your final bitmap as named overlayScaledBitmap.now save it.dont tension about 1200,1600.i just scaled both the camera output bitmap and the snow transparent png as same size.i am currently working on the same project as you qustioned.i would like to take any suggetion from you. https://www.facebook.com/mohammad.mukul.37

Use java in Android Studio to place button to RIGHT_OF another widget

I am creating a button dynamically in Android Studio in a class that extends Fragment. I have my button created (btn) and a text that I want to go under that button (appName), but now I want to place the button next to another button that already exists (lets call it btn_2). I am having trouble finding out how to place one widget next to another using Java, and not xml. Here is what I have so far:
public void createButton (BitmapDrawable bitmapdrawable, String applicationName){
LayoutInflater inflater=null;
ViewGroup container = null;
// Get Layout home_fragment
View rootView = inflater.inflate(R.layout.home_fragment, container, false);
RelativeLayout rLayout = (RelativeLayout) rootView.findViewById(R.id.home_fragment);
// create image button with background as bitmapdrawable
ImageButton btn = new ImageButton(getActivity());
btn.setImageDrawable(bitmapdrawable);
// create textview with applicationName
TextView appName = new TextView(getActivity());
appName.setText(applicationName);
// place new button next to existing button
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.RIGHT_OF);
btn.setLayoutParams(params);
// place text under newly created button
// Put button and text in layout
rLayout.addView(btn);
rLayout.addView(appName);
}
Where I am running into errors is:
params.addRule(RelativeLayout.RIGHT_OF);
How do I pass through the ID of the EXISTING button (btn_2), that I want my new button (btn) to be placed next to?
Then, I want to fill in this empty gap
// place text under newly created button
of how to place my newly created textview (appName) under my newly created btn and under my existing btn_2. (Maybe this will be more straight forward after I figure out how to place one button next to the other.)
Here is my MainActivity. My image and string that I am passing to HomeFragment createButton method are being sent to MainActivity through a socket from another device:
// main activity (FragmentActivity provides fragment compatibility pre-HC)
public class MainActivity extends FragmentActivity implements MenuFragment.OnMenufragListener {
private Thread repeatTaskThread;
private byte[] byteArray;
// called when the activity is first created
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Listening for last installed app to create button
RepeatTask();
}
#Override
public void onMenufrag(Fragment s) {
// get body fragment (native method is getFragmentManager)
HomeFragment fragment = (HomeFragment) getSupportFragmentManager().findFragmentById(R.id.home_fragment);
// if fragment is not null and in layout, set text, else launch BodyActivity
if ((fragment!=null)&&fragment.isInLayout()) {
fragment.getView();
} else {
Intent intent = new Intent(this,HomeFragment.class);
startActivity(intent);
}
}
private void RepeatTask()
{
repeatTaskThread = new Thread()
{
public void run()
{
while (true)
{
try {
System.out.println("TRY_1");
Socket socket = new Socket("192.168.0.26", 5050);
// Get data sent through socket
DataInputStream DIS = new DataInputStream(socket.getInputStream());
System.out.println("DataInputStream Started");
// read data that got sent
String applicationName = DIS.readUTF();
// read array data for bitmap
//Drawable icon = getPackageManager().getApplicationIcon(packagename);
//System.out.println("icon" + icon);
int len = DIS.readInt();
byte[] data = new byte[len];
DIS.readFully(data, 0, data.length);
// Convert data to jpeg first then to bitmap (cant convert byte array directly to bitmap)
YuvImage yuvimage=new YuvImage(data, ImageFormat.NV21, 100, 100, null);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
yuvimage.compressToJpeg(new Rect(0, 0, 100, 100), 80, baos);
byte[] jdata = baos.toByteArray();
// Convert to Bitmap
Bitmap bmp = BitmapFactory.decodeByteArray(jdata, 0, jdata.length);
// Image to png in file directory
// STREAM IMAGE DATA TO FILE
// This is how I know I am correctly getting my png image (no errors here)
// convert bitmap to drawable
Drawable d = new BitmapDrawable(getResources(), bmp);
// convert drawable to bitmapdrawable
BitmapDrawable bitmapdrawable = (BitmapDrawable)d;
Log.d("tag_name", "BITMAP Drawable" + bitmapdrawable);
// Create file to stream bitmpadrawable
FileOutputStream fosIcon = openFileOutput(applicationName + ".png", Context.MODE_PRIVATE);
// compress bitmapdrawable into png and write to file that was just created
bitmapdrawable.getBitmap().compress(Bitmap.CompressFormat.PNG, 100, fosIcon);
InputStream inputStream = openFileInput(applicationName + ".png");
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
// GET FILE DIRECTORY
File imageFile = new File(getFilesDir(), applicationName + ".png");
HomeFragment createbutton = new HomeFragment();
createbutton.createButton(bitmapdrawable, applicationName);
Log.d("tag_name", "Entered Home Fragment");
socket.close();
} catch (Exception e) {
System.out.println("Exception is "+e.toString());
}
try
{
// Sleep for 5 seconds
Thread.sleep(5000);
}
catch (Exception e)
{
e.printStackTrace();
}
}
};
};
repeatTaskThread.start();
}
}
Here is my xml for HomeFragment:
<?xml version="1.0" encoding="utf-8"?>
<HorizontalScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_horizontal"
android:layout_margin="5dp"
android:id="#+id/home_fragment"
>
</RelativeLayout>
</HorizontalScrollView>
You have to specify the view id to make your view right of . Try -
TextView appName = new TextView(getActivity());
int id = 1001;
appName.setId(id);
params.addRule(RelativeLayout.RIGHT_OF, id);

Converting BitmapDrawable into an imageView

I have a particular scenario, I'm very close to finishing! Basically, I've got some decodeBase64 strings in a database that need to be used in a BitmapFactory and then drawn.
public static Bitmap decodeBase64(String input)
{
byte[] decodedByte = Base64.decode(input, 0);
return BitmapFactory.decodeByteArray(decodedByte, 0, decodedByte.length);
}
Here is my MainActivity.java:
// Initiate Database
DatabaseHandler db = new DatabaseHandler(this); // "this" refer to the context
// Grab current Car for use.
Car cars = db.getCurrentCar();
// Grab String from database and decode to Base64
//ByteConvert.decodeBase64(cars.get_image());
// Create Bitmap object from database source
BitmapFactory(ByteConvert.decodeBase64(cars.get_image());
// Draw image from string
Drawable draw = new BitmapDrawable(getResources(), BITMAPFACTORY GOES HERE);
// Set R.id.DRAWABLE to imageView
My question, is how do I turn this string I'm returning from decodeBase64 into a BitmapFactory and then Draw it?
I have done my best to try and fill out how I think it works.
Thanks
The Base64.decode method is returning a byte array, so you can use BitmapFactory's decodeByteArray method to build your bitmap, and set it on your ImageView.
Ex:
DatabaseHandler db = new DatabaseHandler(this);
Car cars = db.getCurrentCar();
byte[] imageData = Base64.decode(cars.get_image(), 0);
Bitmap bitmap = BitmapFactory.decodeByteArray(imageData, 0, imageData.length, new BitmapFactory.Options());
ImageView imageView = //find your image view;
imageView.setImageBitmap(bitmap);

How to set and get unique name/tag to dynamically added child android

I have dynamically added 53 images to ImageView of my layout. I want to set unique id to each image that I added and want to get that id on image click. I have added a tag to my imageview imageView.setTag(WirelessPin.arr_WirelessItems[i]); but onClick ProductURL = (String) imageView.getTag(); always return the tag of last image i.e image no 53. How can I resolve this issue?
Here is my code
for (int i = 0; i < WirelessPin.arr_WirelessItems.length; i++) {
url = new URL(WirelessPin.arr_WirelessItems[i].replaceAll("\\s+","%20"));
//ProductURL = WirelessPin.arr_WirelessItems[i];
Bitmap bmp = BitmapFactory.decodeStream(url
.openConnection().getInputStream());
LinearLayout layout = new LinearLayout(con);
layout.setLayoutParams(new LayoutParams(150, 110));
layout.setGravity(Gravity.CENTER);
imageView = new ImageView(con);
imageView.setLayoutParams(new LayoutParams(140, 84));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setImageBitmap(bmp);
imageView.setTag(WirelessPin.arr_WirelessItems[i]);
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//imageView.se
ProductURL = (String) imageView.getTag();
CollectDenominationsForWirelessPin obj = new CollectDenominationsForWirelessPin();
obj.WirelessPinDenominations(con, ProductURL, UserId);
}
});
layout.addView(imageView);
WirelessPin.sliderProducts.addView(layout);
}
In OnClick method, change your code to
ImageView iv = (ImageView)v;
ProductURL = (String) iv.getTag();
Try initialize ImageView inside for loop like below
for (int i = 0; i < WirelessPin.arr_WirelessItems.length; i++) {
// Other Stuff
ImageView imageView = new ImageView(con);// Declare and initialize here
imageView.setLayoutParams(new LayoutParams(140, 84));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setImageBitmap(bmp);
imageView.setTag(WirelessPin.arr_WirelessItems[i]);
//// Code

Android, How to pass the name of int variable to a popupwindow?

How can I pass the name of an int variable to a popupwindow when an image is clicked? I have set an int per image and I have a lot of images that I had set.
This is how I'm using the int in a textView on a PopupWindow.
public boolean onLongClick(View v) {
// v.setTag(v);
case R.id.hsv1iv1:
ImageView ivpopup = (ImageView) popupView.findViewById(R.id.pv1);
intcount1++; // I would like to pass this int name to the popup window.
break;
case R.id.hsv2iv1:
ImageView ivpopup = (ImageView) popupView.findViewById(R.id.pv1);
intcount2++; // I would like to pass this int name to the popup window.
break;
LayoutInflater layoutInflater
= (LayoutInflater)getBaseContext()
.getSystemService(LAYOUT_INFLATER_SERVICE);
View popupView = layoutInflater.inflate(R.layout.popup, null);
final PopupWindow popupWindow = new PopupWindow(
popupView,
LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT);
popupWindow.update(0, 0, 800, 500);
ColorDrawable dw = new ColorDrawable(-005500);
popupWindow.setBackgroundDrawable(dw);
tvpwlikectr = (TextView) popupView.findViewById(R.id.liketv);
Button pwlikebtn = (Button) popupView.findViewById(R.id.pwlikebtn);
Button btnDismiss = (Button)popupView.findViewById(R.id.cancel);
pwlikebtn.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
intcount1++;
tvpwlikectr.setText(Integer.toString(intcount1)); // this code doesn't work with the intcount1
}});
btnDismiss.setOnClickListener(new Button.OnClickListener(){
public void onClick(View v) {
popupWindow.dismiss();
popupWindow.setTouchable(true);
popupWindow.setFocusable(true);
popupWindow.setOutsideTouchable(true);
}
}
Could you explain how you are setting the INT per image? Copying and pasting the code on how you set an INT per image would be helpful, because it's unclear what you mean by you are setting an INT per image.
Also, are you interested in the value of the int variable or the name of the variable? Showing how you are settings lots of images with int per image would help clarify what you are trying to do.
-- adding answer after seeing the updated post with code --
I would create an object that has the name you are interested in (i.e. intcount1) and an int to keep the actual value. After that, you can associate each button/ImaveView with that object with the view.setTag method, and get the value via view.getTag method. Here's an example:
private class MyTag {
String mTagName;
int mCount;
MyTag(String tagName) {
mTagName = tagName;
mCount = 0;
}
}
// in your onCreate or initializaion code somewhere
ImageView view1 = (ImageView) popupView.findViewById(R.id.hsv1iv1);
MyTag imageTag = new MyTag("intcount1");
view1.setTag(imageTag);
ImageView view2 = (ImageView) popupView.findViewById(R.id.hsv1iv1);
// this will go wherever you handle the onLongClick
public boolean onLongClick(View v) {
Object tag = v.getTag();
if (tag instanceof MyTag) {
MyTag myTag = (MyTag) tag;
myTag.mCount++;
}
}
// I'm assuming you are setting the text from the actual clicked object
// so this will go wherever you are setting the text/handling the click
public void onClick(View v) {
Object tag = v.getTag();
if (tag instanceof MyTag) {
MyTag myTag = (MyTag) tag;
myTag.mCount++;
tvpwlikectr.setText(myTag.mTagName);
}
}
The bottom line is, creating an object with name/count value, associate each View with its own object using the view.setTag() function, and when you need to read the values, use the view.getTag() to get the object and read the mTagName (the "variable" name) and the mCount (the "variable" value).

Categories