Android ImageSwitcher image to another activity - java

i was doing ImageSwitcher, it was working perfect tried to send ImageSwitcher Image to another activity.. ImageSwitcher works perfect but after clicking button for going to next activity, Error: Null Pointer Exception in (imageview) in Views.java
MainEvent.java
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageSwitcher;
import android.widget.ImageView;
import android.widget.ViewSwitcher;
import java.io.ByteArrayOutputStream;
public class MainEvent extends Activity {
private ImageSwitcher imageSwitcher;
Button btnNext,back,select,refresh;
ImageView imageView;
// Array of Image IDs to Show In ImageSwitcher
int imageIds[]={R.drawable.frame3,R.drawable.frame7,
R.drawable.curtain,R.drawable.potraitimage
};
int messageCount=imageIds.length;
// to keep current Index of ImageID array
int currentIndex=0;
Animation in,out;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_event);
// get The references
btnNext=(Button)findViewById(R.id.button2);
back=(Button)findViewById(R.id.button);
select=(Button)findViewById(R.id.select);
refresh=(Button)findViewById(R.id.refresh);
imageSwitcher = (ImageSwitcher) findViewById(R.id.imageSwitcher);
// Set the ViewFactory of the ImageSwitcher that will create
ImageView object when asked
imageSwitcher.setFactory(new ViewSwitcher.ViewFactory() {
public View makeView() {
// TODO Auto-generated method stub
// Create a new ImageView set it's properties
imageView = new ImageView(getApplicationContext());
imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
imageView.setImageResource(R.drawable.potraitimage);
return imageView;
}
});
// Declare the animations and initialize them
in = AnimationUtils.loadAnimation(this,android.R.anim.slide_in_left);
out = AnimationUtils.loadAnimation(this, android.R.anim.slide_out_right);
// set the animation type to imageSwitcher
imageSwitcher.setInAnimation(in);
imageSwitcher.setOutAnimation(out);
// ClickListener for NEXT button
// When clicked on Button ImageSwitcher will switch between Images
// The current Image will go OUT and next Image will come
in with specified animation
btnNext.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
imageView.setImageResource(0);
Log.d("index", String.valueOf(currentIndex));
currentIndex++;
Log.d("index", String.valueOf(currentIndex));
// If index reaches maximum reset it
if(currentIndex==messageCount)
currentIndex=0;
imageSwitcher.setImageResource(imageIds[currentIndex]);
}
});
back.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// set the animation type to imageSwitcher
// TODO Auto-generated method stub
Log.d("index", String.valueOf(currentIndex));
currentIndex--;
Log.d("index", String.valueOf(currentIndex));
// If index reaches maximum reset it
if (currentIndex < 0)
currentIndex = 2;
imageSwitcher.setImageResource(imageIds[currentIndex]);
}
});
select.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
imageView.setImageResource(imageIds[currentIndex]);
BitmapDrawable drawable = (BitmapDrawable) imageView.getDrawable();
Bitmap bitmap = drawable.getBitmap();
Intent in=new Intent(MainEvent.this,Camera.class);
/* in.putExtra("image",bitmap);*/
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
Bundle bu=new Bundle();
bu.putByteArray("ImageByte",byteArray );
in.putExtras(bu);
startActivity(in);
}
});
refresh.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onRestart();
}
});
}
#Override
protected void onRestart() {
// TODO Auto-generated method stub
super.onRestart();
Intent i = new Intent(MainEvent.this, MainEvent.class); //your class
startActivity(i);
finish();
}
}
Views.java
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.ImageView;
public class Views extends AppCompatActivity {
ImageView image;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_camera);
image = (ImageView) findViewById(R.id.image);
Bundle extras = getIntent().getExtras();
byte[] byteArray = extras.getByteArray("ImageByte");
/* Intent i=getIntent();*/
/* Bitmap bitmap=i.getExtras().getParcelable("image");
image.setImageBitmap(bitmap);*/
Bitmap bmp = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
image.setImageBitmap(bmp);//here null pointer exception
}
}
I don't know how to pass image from imageswitcher to next activity.. Please help me guys..

Instead of passing in the bytes of the image, can't you just pass in the index (int) it is on?
That would be more efficient.
(Extended answer from the chain below)
Share the array in both activities.
Simple way on static properties:
public class StaticModelManager {
public static int imageIds[];
}
Then get or set it anywhere in your application:
StaticModelManager.imageIds = {
R.drawable.frame3,
R.drawable.frame7,
R.drawable.curtain,
R.drawable.potraitimage
};
Use them:
StaticModelManager.imageIds[currentIndex];
Multiple activities or fragments can easily access this one instance. Just make sure to clean things up when not needed or it sits in memory.

Related

why is the below code force closes on using built in camera in android project?

package com.example.thenewjay;
import java.io.IOException;
import java.io.InputStream;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
public class Camera extends Activity implements View.OnClickListener {
ImageView iv;
Button but;
ImageButton ib;
final static int cameraData = 0;
Intent i;
Bitmap bmp;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
initialize();
InputStream is = getResources().openRawResource(R.drawable.ic_launcher);
bmp = BitmapFactory.decodeStream(is);
}
private void initialize() {
iv = (ImageView) findViewById(R.id.ivReturnedPic);
ib = (ImageButton) findViewById(R.id.ibTakePic);
but = (Button) findViewById(R.id.bSetWall);
but.setOnClickListener(this);
ib.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.bSetWall:
try {
getApplicationContext().setWallpaper(bmp);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
break;
case R.id.ibTakePic:
i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(i, 1);
break;
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
bmp = (Bitmap) extras.get("data");
iv.setImageBitmap(bmp);
}}
}
why is the below code force closes on using built in camera in android
project?
Because you are missing setContentView in onCreate before calling initialize().
You will need to set layout for current Activity before calling findViewById to access views from current screen xml.do it as in onCreate:
...
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_layout_name);
initialize();
....

Is it possible to share the image located in drawable folder on social platform in viewpager ? (One user says he is not sure, How about you )

I have created viewpager app that is suppose to display images located in the drawable folder. I read android official guide and changed my code ,but it is not working for me. Any help will be appreciated....The user should be able to share the image located in drawable folder ..they like on various platforms according to the app downloaded in their phones.. My question is it possible ?. If yes, please..please.. provide some code..
Following are my codes...
Mainactivity.java
import android.app.Activity;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ShareActionProvider;
public class MainActivity extends Activity {
MediaPlayer oursong;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
oursong = MediaPlayer.create(MainActivity.this, R.raw.a);
oursong.start ();
ViewPager viewPager = (ViewPager) findViewById(R.id.view_pager);
ImageAdapter adapter = new ImageAdapter(this);
viewPager.setAdapter(adapter);
}
private ShareActionProvider mShareActionProvider;
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate menu resource file.
getMenuInflater().inflate(R.menu.activity_main, menu);
// Locate MenuItem with ShareActionProvider
MenuItem item = menu.findItem(R.id.menu_item_share);
// Fetch and store ShareActionProvider
mShareActionProvider = (ShareActionProvider) item.getActionProvider();
// Return true to display menu
return true;
}
// Call to update the share intent
private void setShareIntent(Intent shareIntent) {
if (mShareActionProvider != null) {
mShareActionProvider.setShareIntent(shareIntent);
}
}
#Override
protected void onPause(){
super.onPause();
oursong.release();
}
}
imageadapter.java
import java.io.IOException;
import android.app.WallpaperManager;
import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
public class ImageAdapter extends PagerAdapter {
Context context;
private final int[] GalImages = new int[] {
R.drawable.one,
R.drawable.two,
R.drawable.three
};
ImageAdapter(Context context){
this.context=context;
}
#Override
public int getCount() {
return GalImages.length;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == ((ImageView) object);
}
#Override
public Object instantiateItem(ViewGroup container, final int position) {
ImageView imageView = new ImageView(context);
int padding = context.getResources().getDimensionPixelSize(R.dimen.padding_small);
imageView.setPadding(padding, padding, padding, padding);
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
imageView.setImageResource(GalImages[position]);
imageView.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
WallpaperManager myWallpaperManager = WallpaperManager.getInstance(context);
try {
myWallpaperManager.setResource(GalImages[position]);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
((ViewPager) container).addView(imageView, 0);
return imageView;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
((ViewPager) container).removeView((ImageView) object);
}
}
I am new to android programming so..please provide some explanation along with the code..if possible..thanks..
The user should be able to share the image they like on various
platforms according to the app downloaded in their phones
Yes, of course it is possible.
You have to use Intents to do that. I am not sure if one can send the images from the drawable folder, never tried that. However, if you want to let people share the images from the gallery or something:
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("image/*");
Uri uri = Uri.parse(pathToImage);
shareIntent.putExtra(Intent.EXTRA_STREAM, uri);
startActivity(Intent.createChooser(shareIntent),"Share Via...")
What this is doing is that it is representing the intention of your application that it wants to send an image.

How to set image as wall paper in viewpager app?

Edited code after following this link ...Set wallpaper from ViewPager .I developed simple viewpager app along with the background music. However, I want to modify my app so that image chosen by user will give them option to set as wallpaper....I don't want to implement any buttons in my app. User should be able to just touch the image , which will give them option to set as wallpaper...
I am getting error at this code curruntPosition=arg0;. It says "Current position cannot be resolve to a variable". I don't know what it mean ...
Following are my codes...
Mainactivity.java
import android.app.Activity;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ShareActionProvider;
public class MainActivity extends Activity {
MediaPlayer oursong;
ViewPager viewPager;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
oursong = MediaPlayer.create(MainActivity.this, R.raw.a);
oursong.start ();
viewPager = (ViewPager) findViewById(R.id.view_pager);
ImageAdapter adapter = new ImageAdapter(this);
viewPager.setAdapter(adapter);
viewPager.setOnPageChangeListener(new OnPageChangeListener() {
#Override
public void onPageSelected(int arg0) {
// TODO Auto-generated method stub
//Here you can set the wallpaper
curruntPosition=arg0;
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
// TODO Auto-generated method stub
}
#Override
public void onPageScrollStateChanged(int arg0) {
// TODO Auto-generated method stub
}
});
}
private ShareActionProvider mShareActionProvider;
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate menu resource file.
getMenuInflater().inflate(R.menu.activity_main, menu);
// Locate MenuItem with ShareActionProvider
MenuItem item = menu.findItem(R.id.menu_item_share);
// Fetch and store ShareActionProvider
mShareActionProvider = (ShareActionProvider) item.getActionProvider();
// Return true to display menu
return true;
}
// Call to update the share intent
private void setShareIntent(Intent shareIntent) {
if (mShareActionProvider != null) {
mShareActionProvider.setShareIntent(shareIntent);
}
}
#Override
protected void onPause(){
super.onPause();
oursong.release();
oursong = null;
}
}
imageadapter.java
import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
public class ImageAdapter extends PagerAdapter {
Context context;
private int[] GalImages = new int[] {
R.drawable.one,
R.drawable.two,
R.drawable.three
};
ImageAdapter(Context context){
this.context=context;
}
#Override
public int getCount() {
return GalImages.length;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == ((ImageView) object);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
ImageView imageView = new ImageView(context);
int padding = context.getResources().getDimensionPixelSize(R.dimen.padding_small);
imageView.setPadding(padding, padding, padding, padding);
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
imageView.setImageResource(GalImages[position]);
((ViewPager) container).addView(imageView, 0);
return imageView;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
((ViewPager) container).removeView((ImageView) object);
}
}
I just start with programming, so please give some explanations, or it will be great if you provide some codes .
First add this Permission to the Manifest
<uses-permission android:name="android.permission.SET_WALLPAPER">
Now for some code.
imageview.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
WallpaperManager myWallpaperManager
= WallpaperManager.getInstance(context);
try {
myWallpaperManager.setResource(GalImages[position]);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
Explantion : This will set that the Image will be clickable , when the image is clicked it will set the phone Wallpaper with the selected drawable.
getApplicationContext()
is the Context from the Activity.
This changes will take place inside the Adapter.
Activity
add this variable
int currentPosition;

The method getSystemService(String) is undefined for the type new Thread(){}

I'm attempting to multithread my code, and there are no errors apart from the one which reads in the title. I'm quite new to coding, so now that I have to supposedly turn my code inside out to allow the app to run smoothly, I'm unsure how to tackle the problem.
My Java code:
package com.bipbapapps.leagueclickerapp;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Typeface;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;
public class MainClass extends Activity implements OnClickListener {
public float goldCount;
Button minionClick;
Button storeClick;
Button storeDismiss;
TextView textGoldCount;
ImageView spinningBars;
String textTotal;
private SharedPreferences prefs;
PopupWindow pw;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Set full-screen
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.mainlayout);
// Initialize variables from popup window
LayoutInflater inflater = (LayoutInflater) this
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
PopupWindow pw = new PopupWindow(inflater.inflate(R.layout.storemenu,
null, false));
storeDismiss = (Button) pw.getContentView().findViewById(
R.id.menudismissid);
prefs = getSharedPreferences("LeagueClicker", Context.MODE_PRIVATE);
goldCount = prefs.getFloat("goldCount", 0.0f);
// Linking the variables
minionClick = (Button) findViewById(R.id.minioncentreid);
storeClick = (Button) findViewById(R.id.storeimageid);
textGoldCount = (TextView) findViewById(R.id.textviewtop);
spinningBars = (ImageView) findViewById(R.id.spinningbarsid);
// String which will display at the top of the app
textTotal = goldCount + " Gold";
// Setting TextView to the String
textGoldCount.setText(textTotal);
textGoldCount.setGravity(Gravity.CENTER);
Typeface tf = Typeface.createFromAsset(getAssets(), "mechanical.ttf");
textGoldCount.setTypeface(tf);
textGoldCount.setTextSize(35);
// Setting onClickListeners
minionClick.setOnClickListener(this);
storeClick.setOnClickListener(this);
storeDismiss.setOnClickListener(this);
}
#Override
public void onPause() {
super.onPause();
prefs.edit().putFloat("goldCount", goldCount).commit();
}
#Override
public void onResume() {
super.onResume();
goldCount = prefs.getFloat("goldCount", 0.0f);
t.start();
}
#Override
public void onStop() {
super.onStop();
prefs.edit().putFloat("goldCount", goldCount).commit();
Log.d(prefs.getFloat("goldCount", 0.0f) + "derprolw", "ejwfjbrea");
}
public void barsAnimation() {
Animation rotation = AnimationUtils.loadAnimation(this,
R.anim.spinningbarsanimation);
rotation.setRepeatCount(Animation.INFINITE);
spinningBars.startAnimation(rotation);
}
Thread t = new Thread(){
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.minioncentreid:
goldCount += 1.0;
prefs.edit().putFloat("goldCount", goldCount).commit();
textTotal = goldCount + " Gold";
textGoldCount.setText(textTotal);
textGoldCount.setGravity(Gravity.CENTER);
break;
case R.id.storeimageid:
LayoutInflater inflater = (LayoutInflater) this
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View popupview = inflater.inflate(R.layout.storemenu, null);
final PopupWindow pw = new PopupWindow(popupview, 300, 450);
pw.showAtLocation(v, Gravity.CENTER, 0, 0);
storeDismiss = (Button) pw.getContentView().findViewById(
R.id.menudismissid);
storeDismiss.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
pw.dismiss();
}
});
pw.showAsDropDown(storeClick, 0, 0);
break;
}
};
};
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
}
The thread is at "Thread t = new Thread(){". Does anyone know what I can do to solve this problem?
this is the context of the Thread, while you are actually looking to use .getSystemService of the Activity.
Use instead:
MainClass.this.getSystemService

Trying to get custom android camera working

I have developed a basic camera and am trying to get it working.
Here is the camera code
package com.example.camera;
import java.io.IOException;
import android.content.Context;
import android.hardware.Camera;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
public class CameraView extends SurfaceView implements SurfaceHolder.Callback {
private SurfaceHolder holder;
private Camera camera;
Object size;
public CameraView(Context context) {
super(context);
holder = this.getHolder();
holder.addCallback(this);
holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
holder.addCallback(this);
}
public Camera getCamera(){
return camera;
}
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
Camera.Parameters params = camera.getParameters();//Getting paramaters.
if(size!=null){ //make sure we don't pull a NullException.
params.setPreviewSize(width, height);//gotta set the size, since we know it.
}
camera.setParameters(params);//gotta set the paramaters now.
camera.startPreview();//starting the preview.
}
public void surfaceCreated(SurfaceHolder arg0) {
try{
camera = Camera.open();//setting the camera up.
camera.setPreviewDisplay(holder);//making the display our current SurfaceHolder
} catch (IOException e){
e.printStackTrace();//printing out the error message if it happens.
}
}
public void surfaceDestroyed(SurfaceHolder arg0) {
camera.stopPreview();
camera.release();
camera = null;
}
}
Now Im trying to call the camera from my main method and I just cant seem to make it work
package com.example.camera;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.hardware.Camera;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
public class main {
private static final int CAMERA_REQUEST = 1888;
private ImageView imageView;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
this.imageView = (ImageView)this.findViewById(R.id.imageView1);
Button photoButton = (Button) this.findViewById(R.id.button1);
photoButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
cam = cv.getCamera(); //notice how we used that method? ;)
cam.takePicture(null,null,PictureCallback_);
}
});
}
Camera.PictureCallback PictureCallback_ = new Camera.PictureCallback() {
public void onPictureTaken(byte[] imageData, Camera c) {
InputStream is = new ByteArrayInputStream(imageData);
Bitmap bmp = BitmapFactory.decodeStream(is);
}
} ;
Any help is appreciated. Trying to call the original camera activity getCamera and then get the picture taken and put it into imageView1 any help is appreciated.
Try to do this in your onClick() method:
cam.autoFocus(new AutoFocusCallback(){
Camera.ShutterCallback shutterCallback = new Camera.ShutterCallback() {
public void onShutter() {
// If you want to play your own sound (otherwise, it plays the sound by default)
}
};
#Override
public void onAutoFocus(boolean arg0, Camera arg1) {
cam.takePicture(shutterCallback, null, PictureCallback_);
}
});
I have created a camera library project here you can use this library to call the camera and take pictures and save it or read code on how to use the camera. Sample is given you can check it out

Categories