So, I've been referencing this: http://developer.android.com/reference/android/hardware/Camera.html
I'm using LibGDX which is why you may see some difference, I've also changed mCamera to androidCamera for readability.
Here's my code:
package com.fmeg.tapdat.android.camera;
import java.io.IOException;
import android.hardware.Camera;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import com.fmeg.tapdat.android.AndroidLauncher;
import com.fmeg.tapdat.camera.CameraInterface;
public class AndroidCamera extends SurfaceView implements
SurfaceHolder.Callback, CameraInterface {
private AndroidLauncher application;
private SurfaceHolder mHolder;
private Camera androidCamera;
public AndroidCamera(AndroidLauncher _application) {
super(_application.getContext());
this.application = _application;
mHolder = getHolder();
mHolder.addCallback(this);
mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
surfaceCreated(mHolder);
}
#Override
public void showCamera(boolean show) {
androidCamera.startPreview();
}
/**
* Organized by call order
*/
#Override
public void surfaceCreated(SurfaceHolder holder) {
androidCamera = Camera.open();
try {
androidCamera.setPreviewDisplay(mHolder);
} catch (Exception e) {
}
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
Camera.Parameters params = androidCamera.getParameters();
params.setPreviewSize(width, height);
androidCamera.setParameters(params);
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
androidCamera.stopPreview();
androidCamera = null;
}
}
I have an interface called CameraInterface with the following code:
package com.fmeg.tapdat.camera;
public interface CameraInterface {
public void showCamera(boolean show);
}
In my main class (android project) my code looks like this
[code]
public class AndroidLauncher extends AndroidApplication {
#Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
AndroidApplicationConfiguration config = new AndroidApplicationConfiguration();
AndroidCamera cam = new AndroidCamera(this);
initialize(new TapdatGame(cam), config);
}
}
and in my main class (Core project)
package com.fmeg.tapdat;
import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL20;
import com.fmeg.tapdat.camera.CameraInterface;
public class TapdatGame extends ApplicationAdapter {
private CameraInterface camera;
public TapdatGame(CameraInterface cameraInterface) {
this.camera = cameraInterface;
}
#Override
public void create () {
camera.showCamera(true);
}
#Override
public void render () {
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
}
public CameraInterface getCamera() {
return camera;
}
}
Please help me get this working, the current implementation invokes an camera realted error
Tag(Camera) - Error 1001
Related
There is two arrows as you see in picture ..
one indicate to Activities in my project
other one indicate to recommended activity to declare in manifest ..
but there is no recommended activity except " StreamingActivity "
when i run my application ,, application show me that message " Unfortunately , application has stopped "
this code for publisheractivity
package khaabbas.huthaifa.com.talk_listen;
import android.hardware.Camera;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import com.red5pro.streaming.R5Connection;
import com.red5pro.streaming.R5Stream;
import com.red5pro.streaming.R5StreamProtocol;
import com.red5pro.streaming.config.R5Configuration;
import com.red5pro.streaming.source.R5Camera;
import com.red5pro.streaming.source.R5Microphone;
//import android.graphics.Camera;
public class PublishFragment extends android.support.v4.app.Fragment implements SurfaceHolder.Callback {
public static android.support.v4.app.Fragment newInstance() {
PublishFragment fragment = new PublishFragment();
Bundle args = new Bundle();
fragment.setArguments(args);
return fragment;
}
public PublishFragment() {
// Required empty public constructor
}
public R5Configuration configuration;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
configuration = new R5Configuration(R5StreamProtocol.RTSP, "localhost", 8554, "live", 1.0f);
configuration.setLicenseKey("NBZF-UFM2-GCEP-OUYZ");
configuration.setBundleID(getActivity().getPackageName());
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_publish, container, false);
return v;
}
protected Camera camera;
protected boolean isPublishing = false;
protected R5Stream stream;
private void preview() {
camera = Camera.open(Camera.CameraInfo.CAMERA_FACING_FRONT);
SurfaceView surface = (SurfaceView) getActivity().findViewById(R.id.surfaceView);
surface.getHolder().addCallback(this);
}
#Override
public void surfaceCreated(SurfaceHolder surfaceHolder) {
try {
camera.setPreviewDisplay(surfaceHolder);
camera.startPreview();
}
catch(Exception e) {
e.printStackTrace();
}
}
#Override
public void surfaceChanged(SurfaceHolder surfaceHolder, int i, int i2, int i3) {
}
#Override
public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
}
#Override
public void onResume() {
super.onResume();
preview();
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Button publishButton = (Button) getActivity().findViewById(R.id.publishButton);
publishButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onPublishToggle();
}
});
}
private void onPublishToggle() {
Button publishButton = (Button) getActivity().findViewById(R.id.publishButton);
if(isPublishing) {
stop();
}
else {
start();
}
isPublishing = !isPublishing;
publishButton.setText(isPublishing ? "stop" : "start");
}
public void start() {
camera.stopPreview();
stream = new R5Stream(new R5Connection(configuration));
stream.setView((SurfaceView) getActivity().findViewById(R.id.surfaceView));
R5Camera r5Camera = new R5Camera(camera, 320, 240);
R5Microphone r5Microphone = new R5Microphone();
stream.attachCamera(r5Camera);
stream.attachMic(r5Microphone);
stream.publish("red5prostream", R5Stream.RecordType.Live);
camera.startPreview();
}
public void stop() {
if(stream != null) {
stream.stop();
camera.startPreview();
}
}
#Override
public void onPause() {
super.onPause();
if(isPublishing) {
onPublishToggle();
}
}
}
Remove both this activity because u used only single activity it define activity and two other is fragment.
<activity android:name=".S"/>
<activity android:name=".Sub"/>
and fragment call used below code..
Fragment fragment = new HomeFragment();
getSupportFragmentManager().beginTransaction()
.replace(R.id.fragment_frame, fragment, fragment.getClass().getSimpleName()).addToBackStack(null).commit();
No need to declare fragment on manifest, remove fragment declaration from manifest because you are declare fragment within section in manifest file.
I created a SurfaceView (you can see it in the following) and started in from my Main Activity. I overwrote the onTouchEvent method in the SurfaceView and the problem is that the data I want to have logged with Log.d isn't logged, I don't get any Message...
Does anyone have an idea how I can fix this?
My SurfaceView:
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.util.Log;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
public class MainGamePanel extends SurfaceView implements SurfaceHolder.Callback {
private float top;
private float left;
private float bottom;
private float right;
private MainThread thread;
MainGamePanel(Context context) {
super(context);
getHolder().addCallback(this);
thread = new MainThread(getHolder(), this);
setFocusable(true);
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
setWillNotDraw(false);
thread.setRunningMode(MainThread.RUNNING);
thread.start();
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
boolean retry = true;
while (retry) {
try {
thread.join();
retry = false;
} catch (Exception e) {
}
}
}
#Override
public boolean onTouchEvent(MotionEvent event) {
float x = event.getX();
float y = event.getY();
right = x + 30;
left = x - 30;
top = y - 30;
bottom = y + 30;
Log.d("tag", x + " " + y);
return true;
}
#Override
protected void onDraw(Canvas canvas) {
}
}
My Main Activity:
import android.app.Activity;
import android.os.Bundle;
import android.os.PersistableBundle;
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState, PersistableBundle persistentState) {
super.onCreate(savedInstanceState, persistentState);
setContentView(new MainGamePanel(getApplicationContext()));
}
}
Try changing "getApplicationContext()" to "this" in following part of code:
setContentView(new MainGamePanel(getApplicationContext()));
to
setContentView(new MainGamePanel(this));
NOTE:
The code shown below may be a bit hard to read, but i hope it can help. Sorry for that.
I get this error whenever i press HOME button and my app goes background.
java.lang.RuntimeException: Parcel: unable to marshal value
elektro_fr.newapplication.FragmentsActivity$3#a6c25e4
I'm new to android programming and i would like to create a class which can offer me all the functions without implementing them each time.
I made a My_Activity class:
package elektro_fr.my_android;
import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.GestureDetectorCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.GestureDetector;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.WindowManager;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
public abstract class My_Activity extends AppCompatActivity implements GestureDetector.OnGestureListener, GestureDetector.OnDoubleTapListener{
private int myLayout;
protected Bundle mySettings;
private boolean gesturesEnabled=false;
private GestureDetectorCompat myGestureDetector;
private boolean canStart=false;
private boolean menuEnabled=false;
private HashMap<String,Action> menuEntries;
protected List<My_Fragment> fragmentsList=new LinkedList<>();
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
myGestureDetector = new GestureDetectorCompat(this,this);
if (savedInstanceState==null){
canStart=true;
}
init();
setContentView(myLayout);
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putSerializable("LIST",menuEntries);
for (int counter=0;counter<fragmentsList.size();counter++){
getSupportFragmentManager().putFragment(outState,"FRAGMENT_SETTINGS_"+counter,fragmentsList.get(counter));
}
}
#Override
protected void onStart() {
super.onStart();
if (canStart) setGraphics();
canStart=false;
}
protected abstract void init();
protected abstract void setGraphics();
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
if (savedInstanceState!=null){
menuEntries=(HashMap<String, Action>) savedInstanceState.getSerializable("LIST");
int size=getSupportFragmentManager().getFragments().size();
for (int counter=0;counter<size;counter++){
fragmentsList.add(counter,(My_Fragment)getSupportFragmentManager().getFragment(savedInstanceState,"FRAGMENT_SETTINGS_"+counter));
}
}
refreshState();
}
abstract protected void refreshState();
#Override
public boolean onCreateOptionsMenu(Menu menu) {
return menuEnabled;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
if (menuEntries.get(item.getTitle())!=null){
menuEntries.get(item.getTitle()).doAction();
}
return menuEnabled;
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
if (menuEnabled){
if (menuEntries.size()!=0){
menu.clear();
int counter=0;
for (String s: menuEntries.keySet()){
menu.add(Menu.NONE,counter,Menu.NONE,s);
counter++;
}
}
}
return menuEnabled;
}
protected void setGestures(boolean enabled){
gesturesEnabled=enabled;
}
protected void setMenu(boolean enabled){
menuEnabled=enabled;
menuEntries=new HashMap<>();
}
protected HashMap<String, Action> getMenuEntries(){
return menuEntries;
}
public My_Fragment addFragment(Class<? extends My_Fragment> fragmentClass, int fragmentContainer, int fragmentID, Bundle fragmentArgs){
My_Fragment fragment = null;
try {
fragment = fragmentClass.newInstance();
}
catch (InstantiationException e){
}
catch (IllegalAccessException e){
e.printStackTrace();
}
fragment.setArguments(fragmentArgs);
getSupportFragmentManager().beginTransaction().add(fragmentContainer, fragment).commit();
fragmentsList.add(fragment);
return fragment;
}
protected My_Fragment getFragment(Class<? extends My_Fragment> fragmentClass){
for (My_Fragment f: fragmentsList){
if (fragmentClass.isInstance(f)){
return f;
}
}
return null;
}
public void removeFragment(My_Fragment fragment,boolean addToBackStack){
if (fragment.isAdded()){
FragmentTransaction transaction=getSupportFragmentManager().beginTransaction();
if (addToBackStack)transaction.addToBackStack(null);
transaction.remove(fragment);
transaction.commit();
getSupportFragmentManager().executePendingTransactions();
if (!addToBackStack)fragmentsList.remove(fragment);
}
}
protected void setFullScreen(boolean fullScreen){
WindowManager.LayoutParams attrs = getWindow().getAttributes();
if (fullScreen) {
attrs.flags |= WindowManager.LayoutParams.FLAG_FULLSCREEN;
}
else {
attrs.flags &= ~WindowManager.LayoutParams.FLAG_FULLSCREEN;
}
getWindow().setAttributes(attrs);
}
protected void hideActionBar(boolean hidden){
if (hidden){
getSupportActionBar().hide();
}
else getSupportActionBar().show();
}
protected void setLayout(int layoutID){
myLayout=layoutID;
}
public boolean onTouchEvent(MotionEvent event) {
if (gesturesEnabled){
this.myGestureDetector.onTouchEvent(event);
}
return true;
}
public boolean onSingleTapConfirmed(MotionEvent e) {
My_AndroidTools.KeyboardTools.closeInputKeyboard(getCurrentFocus());
return true;
}
public boolean onDoubleTap(MotionEvent e) {
return true;
}
public boolean onDoubleTapEvent(MotionEvent e) {
return true;
}
public boolean onDown(MotionEvent e) {
return true;
}
public void onShowPress(MotionEvent e) {
}
public boolean onSingleTapUp(MotionEvent e) {
return true;
}
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return true;
}
public void onLongPress(MotionEvent e) {
}
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return false;
}
}
This is FragmentsActivity, which extends and implements My_Activity:
package elektro_fr.newapplication;
import android.os.Bundle;
import android.util.Log;
import android.widget.RelativeLayout;
import elektro_fr.my_android.Action;
import elektro_fr.my_android.My_Activity;
import elektro_fr.my_android.My_Fragment;
import elektro_fr.newapplication.R;
public class FragmentsActivity extends My_Activity implements My_Fragment.fragmentOperations {
private MyTopFragment topFragment;
private MyBottomFragment bottomFragment;
#Override
protected void init() {
setLayout(R.layout.fragments);
setGestures(true);
setMenu(true);
}
#Override
protected void setGraphics() {
Bundle args=new Bundle();
args.putInt(MyTopFragment.LAYOUT_ID,R.layout.ts_fragment);
args.putInt(My_Fragment.CENTER_HORIZONTAL,RelativeLayout.CENTER_HORIZONTAL);
topFragment = (MyTopFragment) addFragment(MyTopFragment.class,R.id.MainLayout,R.layout.ts_fragment,args);
Bundle args2=new Bundle();
args2.putInt(My_Fragment.LAYOUT_ID,R.layout.bs_fragment);
args2.putInt(My_Fragment.LAYOUT_WIDTH,RelativeLayout.LayoutParams.MATCH_PARENT);
args2.putInt(My_Fragment.LAYOUT_HEIGHT,RelativeLayout.LayoutParams.WRAP_CONTENT);
args2.putInt(My_Fragment.BELOW, R.id.ts);
args2.putInt(My_Fragment.CENTER_HORIZONTAL,RelativeLayout.CENTER_HORIZONTAL);
bottomFragment = (MyBottomFragment) addFragment(MyBottomFragment.class,R.id.MainLayout,R.layout.bs_fragment,args2);
getMenuEntries().put("Menu Item #1", new Action() {
#Override
public void doAction() {
Log.i("Ciccio","you pressed 1");
}
});
getMenuEntries().put("Menu Item #2", new Action() {
#Override
public void doAction() {
Log.i("Ciccio","you pressed 2");
}
});
getMenuEntries().put("Menu Item #3", new Action() {
#Override
public void doAction() {
Log.i("Ciccio","you pressed 3");
}
});
}
protected void refreshState(){
topFragment = (MyTopFragment) getFragment(MyTopFragment.class);
bottomFragment = (MyBottomFragment) getFragment(MyBottomFragment.class);
}
#Override
public void ClickButtonOperation(Object[] arguments) {
switch((Integer)arguments[0]){
case 0:
bottomFragment.setText((String)arguments[1],(String)arguments[2]);
break;
}
}
}
This is My_Fragment class:
package elektro_fr.my_android;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.text.Layout;
import android.util.Log;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
public abstract class My_Fragment extends Fragment {
public final static String LAYOUT_ID="layout_id";
public final static String LAYOUT_WIDTH="layout_width";
public final static String LAYOUT_HEIGHT="layout_height";
public final static String BELOW="layout_below";
public final static String ABOVE="layout_above";
public final static String ALIGN_PARENT_BOTTOM="align_parent_bottom";
public final static String CENTER_HORIZONTAL="center_horizontal";
private String[] params={
LAYOUT_ID,LAYOUT_WIDTH, LAYOUT_HEIGHT, ALIGN_PARENT_BOTTOM, CENTER_HORIZONTAL, BELOW, ABOVE
};
protected int fragmentLayout;
protected fragmentOperations myActivity;
protected Bundle mySettings;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState!=null){
mySettings=new Bundle();
mySettings.putAll(savedInstanceState);
}
else mySettings=getArguments();
fragmentLayout=mySettings.getInt(LAYOUT_ID);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (savedInstanceState != null) {
mySettings.putAll(savedInstanceState);
refreshState();
}
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
setState();
outState.putAll(mySettings);
}
public interface fragmentOperations{
void ClickButtonOperation(Object[] arguments);
}
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view=inflater.inflate(fragmentLayout,container,false);
int widthSettings=mySettings.getInt(params[1]);
int heightSettings=mySettings.getInt(params[2]);
view.setLayoutParams(new RelativeLayout.LayoutParams((widthSettings==0?RelativeLayout.LayoutParams.WRAP_CONTENT:widthSettings),(heightSettings==0?RelativeLayout.LayoutParams.WRAP_CONTENT:heightSettings)));
RelativeLayout.LayoutParams layoutConfig= (RelativeLayout.LayoutParams) view.getLayoutParams();
for (int counter=3;counter<params.length;counter++){
int settings=mySettings.getInt(params[counter]);
if (settings!=0){
if (counter==5){
layoutConfig.addRule(RelativeLayout.BELOW,settings);
}
else if (counter==6){
layoutConfig.addRule(RelativeLayout.ABOVE,settings);
}
else{
layoutConfig.addRule(settings);
}
}
}
init(view);
return view;
}
protected abstract void init(View v);
protected abstract void setState();
protected abstract void refreshState();
#Override
public void onAttach(Context context) {
super.onAttach(context);
myActivity=(fragmentOperations)getActivity();
}
}
EDIT:
Finally, Action (interface), which i edited in order to implement Serializable:
package elektro_fr.my_android;
import java.io.Serializable;
public interface Action extends Serializable{
public void doAction();
}
This is the error:
Process: elektro_fr.newapplication, PID: 24970
java.lang.RuntimeException: Parcelable encountered IOException writing serializable object (name = elektro_fr.newapplication.FragmentsActivity$3)
Caused by:
Caused by: java.io.NotSerializableException: elektro_fr.newapplication.FragmentsActivity
why should i implement serializable in this class?
You try to save menuEntries in OnSaveInstanceState, but the type is HashMap and this type is not serializable. Only primitive can be save or custom object when your implement the serialization yourself.
SOLUTION:
Following Johann67 idea:
Ok I understand your code. You can't do that. When you serialize an
object, only the fields are serialized and save. But here you try to
serialize the doAction() method... You need to change the Action
object. Maybe you can just save the item position on your HashMap or
create an object and store your information in the fields.
So I modified my code.
First of all Ichanged my menuEntries object to a List of String.
Second, i created a new method:
protected void dispatchItemAction(int itemID);
which can be overridden in order to switch between actions to do, based on the itemID.
And i modified this method:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
dispatchItemAction(item.getItemId());
return menuEnabled;
}
protected void dispatchItemAction(int itemID){
}
now, to add menu items:
protected void addMenuItems(){
getMenuEntries().add("Menu Item #1");
getMenuEntries().add("Menu Item #2");
getMenuEntries().add("Menu Item #3");
}
#Override
protected void dispatchItemAction(int itemID) {
switch(itemID){
case 0:
Log.i("Log","Pressed #1.");
break;
case 1:
Log.i("Log","Pressed #2.");
break;
case 2:
Log.i("Log","Pressed #3.");
break;
}
}
I saw this one from here. And I just want to try if it is working.
Link: http://www.javacodegeeks.com/2011/03/android-http-camera-live-preview.html
This is the first class called MyCamAppActivity.java
package com.javacodegeeks.android.camera;
import android.app.Activity;
import android.os.Bundle;
import android.view.SurfaceView;
import android.view.Window;
public class MyCamAppActivity extends Activity {
private SurfaceView cameraPreview;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
cameraPreview = new CameraPreview(this);
setContentView(cameraPreview);
}
}
And this is the 2nd class called the CameraPreview
package com.javacodegeeks.android.camera;
import android.content.Context;
import android.hardware.Camera;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
public class CameraPreview extends SurfaceView implements SurfaceHolder.Callback {
private SurfaceHolder holder;
private Camera camera;
public CameraPreview(Context context) {
super(context);
holder = getHolder();
holder.addCallback(this);
holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
#Override
public void surfaceChanged(SurfaceHolder holder2, int format, int w, int h) {
Camera.Parameters parameters = camera.getParameters();
parameters.setPreviewSize(w, h);
camera.setParameters(parameters);
camera.startPreview();
}
#Override
public void surfaceCreated(SurfaceHolder holder1) {
try {
camera = Camera.open();
camera.setPreviewDisplay(holder1);
}
catch (Exception e) {
Log.i("Exception surfaceCreated()", "e=" + e);
camera.release();
camera = null;
}
}
#Override
public void surfaceDestroyed(SurfaceHolder arg0) {
camera.stopPreview();
camera.release();
camera = null;
}
}
As far as I know, when you use surfaceview in android programming it automatically generated the picture on your screen. But in my case, it's just plain black picture. Btw, the complete package in the site doesn't have any .xml contents in it. So, I don't know if I still have to fix something in the xml. Hope someone or any of you could help me ASAP.
I am an amateur programmer, and have been playing around with android development. I am currently trying my hand at generating a fractal heightmap. In order to test if teh map is generating properly I need to be able to draw the map to the screen. This is where I've been running into trouble.
Here's the code for my MainActivity, DrawMap class (where my onDraw() is), and my CanvasThread() class.
Main Activity:
package com.psstudios.HMG;
import android.app.*;
import android.os.*;
import android.view.*;
import android.widget.*;
import android.view.View.OnClickListener;
import android.util.Log;
public class MainActivity extends Activity
{
/** Called when the activity is first created. */
Button Startgen = null;
Boolean run=true;
private void log(String text) {
Log.d("heightmap",text);
AppendLog app = new AppendLog(text);
}
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.main);
Startgen = (Button) findViewById(R.id.startgen);
log("loop");
Startgen.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
log("Starting world generation");
WorldGen world=new WorldGen(200,200);
log("World generation complete, drawing heightmap");
setContentView(new DrawMap(MainActivity.this, world));
log("Went too far");
}
});
run=false;
}
}
DrawMap:
package com.psstudios.HMG;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Bitmap;
import android.graphics.Bitmap.*;
import android.graphics.Paint;
import android.graphics.Color;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.util.Log;
import android.util.*;
public class DrawMap extends SurfaceView implements SurfaceHolder.Callback
{
int drawtype=1; //variable for which type of map to draw
Bitmap drawbitmap=null;
CanvasThread canvasThread=null;
Boolean run= true;
int Worldx=200;
int Worldy=200;
WorldGen _world=null;
public void log(String text){
Log.d("Heightmap", text);
AppendLog app = new AppendLog(text);
}
public void init(){
log("init();");
canvasThread=new CanvasThread(getHolder(), this);
setFocusable(true);
log("Post-CanvasThread");
}
public DrawMap(Context context){
super(context);
log("DrawMap(Context context)");
getHolder().addCallback(this);
init();
}
public DrawMap(Context context, AttributeSet attrs) {
super(context, attrs);
log("DrawMap(Context context, AttributeSet attrs)");
getHolder().addCallback(this);
init();
}
public DrawMap(Context context,WorldGen world){
super(context);
log("DrawMap(Context context, WorldGen world)");
getHolder().addCallback(this);
_world=world;
init();
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format,int width, int height){
log("surfaceChanged()");
}
#Override
public void surfaceCreated(SurfaceHolder holder){
log("Surface Created");
canvasThread.setRunning(true);
canvasThread.run();
}
#Override
public void surfaceDestroyed(SurfaceHolder holder){
log("Surface Destroyed");
Boolean retry = true;
canvasThread.setRunning(false);
while(retry){
try {
canvasThread.join();
retry=false;
} catch (InterruptedException e) {
//we will try again and again
}
}
}
#Override
public void onDraw(Canvas canvas){
log("onDraw()");
Paint paint = new Paint();
Paint paint2 = new Paint();
//canvas.drawColor(Color.BLACK);
paint.setColor(Color.WHITE);
paint.setStrokeWidth(10);
paint2.setColor(Color.BLUE);
for(int x=0; x<Worldx-1; x++){
for(int y=0; y<Worldy-1; y++){
//log(x + " : " + y);
canvas.drawPoint(x+20, y+20, paint);
canvas.drawPoint(x+220, y+220, paint2);
}
}
}
}
CanvasThread:
package com.psstudios.HMG;
import android.graphics.Canvas;
import android.view.*;
import android.util.Log;
public class CanvasThread extends Thread
{
private SurfaceHolder _surfaceHolder;
private DrawMap _drawMap;
private Boolean _run = false;
private void log(String text){
Log.d("HeightmapGen",text);
AppendLog app = new AppendLog(text);
}
public CanvasThread(SurfaceHolder surfaceHolder, DrawMap drawMap){
_surfaceHolder=surfaceHolder;
_drawMap=drawMap;
log("CanvasThread()");
}
public void setRunning(Boolean run){
log("setRunning()");
_run=run;
}
#Override
public void run() {
log("run()");
Canvas c;
while(_run){
c=null;
try{
c=_surfaceHolder.lockCanvas(null);
synchronized (_surfaceHolder) {
_drawMap.onDraw(c);
}
} finally {
if(c != null){
_surfaceHolder.unlockCanvasAndPost(c);
}
}
}
}
}
The program makes it to the onDraw(); function, and runs through the for loop, but nothing is showing up on the screen. I imagine I'm missing something pretty stupid, but I cannot seem to figure out what's wrong.
Thanks in advance for any help you guys can give me.