Surface view draw element of layout (android) - java

i have a surface view and i wish "draw" the content of a linear layout on my surface view.
My surface view is the preview of the camera, i wish when i take the picture the content of my layout is drawn on the picture.
How do this?
Thx.

Surface layout:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:gravity="bottom"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="#+id/takepicture"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="#drawable/trans_tshirt"
android:contentDescription="tshirt" />
main.xml
<LinearLayout android:layout_height="match_parent" android:layout_width="match_parent" android:orientation="vertical" xmlns:android="http://schemas.android.com/apk/res/android">
<SurfaceView android:layout_height="match_parent" android:layout_width="match_parent" android:id="#+id/camerapreview"/>
</LinearLayout>
java code:
package com.views;
import android.app.Activity;
import android.content.ContentValues;
import android.content.pm.ActivityInfo;
import android.graphics.PixelFormat;
import android.hardware.Camera;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.LayoutInflater;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.ImageView;
import android.widget.Toast;
import com.fashion.alex.R;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
public class HomeActivity extends Activity implements SurfaceHolder.Callback
{
private Camera camera;
private SurfaceView surfaceView;
private SurfaceHolder surfaceHolder;
private boolean previewing = false;
private LayoutInflater controlInflater = null;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
getWindow().setFormat(PixelFormat.UNKNOWN);
surfaceView = (SurfaceView)findViewById(R.id.camerapreview);
surfaceHolder = surfaceView.getHolder();
surfaceHolder.addCallback(this);
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
controlInflater = LayoutInflater.from(getBaseContext());
View viewControl = controlInflater.inflate(R.layout.tshirt_layout, null);
LayoutParams layoutParamsControl = new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
this.addContentView(viewControl, layoutParamsControl);
final ImageView ivButton = (ImageView)findViewById(R.id.takepicture);
ivButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
camera.takePicture(myShutterCallback,
myPictureCallback_RAW, myPictureCallback_JPG);
}}
);
}
Camera.ShutterCallback myShutterCallback = new Camera.ShutterCallback(){
#Override
public void onShutter() {
}
};
Camera.PictureCallback myPictureCallback_RAW = new Camera.PictureCallback(){
#Override
public void onPictureTaken(byte[] arg0, Camera arg1) {
}
};
Camera.PictureCallback myPictureCallback_JPG = new Camera.PictureCallback(){
#Override
public void onPictureTaken(byte[] arg0, Camera arg1) {
Uri uriTarget = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, new ContentValues());
OutputStream imageFileOS;
try {
imageFileOS = getContentResolver().openOutputStream(uriTarget);
imageFileOS.write(arg0);
imageFileOS.flush();
imageFileOS.close();
Toast.makeText(HomeActivity.this,
"Image saved: " + uriTarget.toString(),
Toast.LENGTH_LONG).show();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
camera.startPreview();
}
};
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
if(previewing){
camera.stopPreview();
previewing = false;
}
if (camera != null){
try {
camera.setPreviewDisplay(surfaceHolder);
camera.startPreview();
previewing = true;
} catch (IOException e) {
e.printStackTrace();
}
}
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
camera = Camera.open();
try {
camera.setPreviewDisplay(holder);
} catch (IOException exception) {
camera.release();
camera = null;
}
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
camera.stopPreview();
camera.release();
camera = null;
previewing = false;
}
}

create a Layout/.xml file..like below
1) LinearLayout A
2) Linear Layout A must have child views which may be BUtton/text whatever you want.
3) Linear Layout A must also have a surfaceview B
use this surfaceView B in your activity to show camera preview. in this way you can basically have surface view and other views on the screen.

Related

user_list_map <com.google.android.gms.maps.MapView>: No speakable text present

I'm trying to create a route planner app and I'm getting the error user_list_map <com.google.android.gms.maps.MapView>: No speakable text present' I don't understand what this error is telling more nor do I understand what I need to do for it.
Here is my XML code:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/white">
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:weightSum="100"
android:background="#color/white">
<androidx.recyclerview.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="50"
android:id="#+id/user_list_recycler_view">
</androidx.recyclerview.widget.RecyclerView>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="50"
android:id="#+id/map_container">
<com.google.android.gms.maps.MapView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/user_list_map"/>
</RelativeLayout>
</LinearLayout>
<ProgressBar
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/progressBar"
android:layout_centerInParent="true"
android:visibility="gone"/>
</RelativeLayout>
Heres the Java code:
package com.example.destinationrouteplanner.ui;
import static com.example.destinationrouteplanner.Constants.MAPVIEW_BUNDLE_KEY;
import android.Manifest;
import android.app.Fragment;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.example.destinationrouteplanner.R;
import com.example.destinationrouteplanner.adapters.UserRecyclerAdapter;
import com.example.destinationrouteplanner.models.MarkerCluster;
import com.example.destinationrouteplanner.models.User;
import com.example.destinationrouteplanner.models.UserLocation;
import com.example.destinationrouteplanner.util.MyClusterManagerRenderer;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapView;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.LatLngBounds;
import com.google.firebase.auth.FirebaseAuth;
import com.google.maps.android.clustering.ClusterManager;
import java.util.ArrayList;
public class UserListFragment extends Fragment implements OnMapReadyCallback
{
private static final String TAG = "UserListFragment";
private RecyclerView mUserListRecyclerView;
private MapView mMapView;
private ArrayList<User> mUserList = new ArrayList<>();
private UserRecyclerAdapter mUserRecyclerAdapter;
private ArrayList<UserLocation> mUserLocations = new ArrayList<>();
private GoogleMap mGoogleMap;
private LatLngBounds mMapBoundary;
private UserLocation mUserPosition;
private ClusterManager mClusterManager;
private MyClusterManagerRenderer mClusterManagerRenderer;
private ArrayList<MarkerCluster> mClusterMarkers = new ArrayList<>();
public static UserListFragment newInstance() {
return new UserListFragment();
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mUserList = getArguments().getParcelableArrayList(getString(R.string.intent_user_list));
}
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_user_list, container, false);
mUserListRecyclerView = view.findViewById(R.id.user_list_recycler_view);
mMapView = view.findViewById(R.id.user_list_map);
initUserListRecyclerView();
initGoogleMap(savedInstanceState);
return view;
}
private void initGoogleMap(Bundle savedInstanceState){
// *** IMPORTANT ***
// MapView requires that the Bundle you pass contain _ONLY_ MapView SDK
// objects or sub-Bundles.
Bundle mapViewBundle = null;
if (savedInstanceState != null) {
mapViewBundle = savedInstanceState.getBundle(MAPVIEW_BUNDLE_KEY);
}
mMapView.onCreate(mapViewBundle);
mMapView.getMapAsync(this);
}
private void initUserListRecyclerView() {
mUserRecyclerAdapter = new UserRecyclerAdapter(mUserList);
mUserListRecyclerView.setAdapter(mUserRecyclerAdapter);
mUserListRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
Bundle mapViewBundle = outState.getBundle(MAPVIEW_BUNDLE_KEY);
if (mapViewBundle == null) {
mapViewBundle = new Bundle();
outState.putBundle(MAPVIEW_BUNDLE_KEY, mapViewBundle);
}
mMapView.onSaveInstanceState(mapViewBundle);
}
#Override
public void onResume() {
super.onResume();
mMapView.onResume();
}
#Override
public void onStart() {
super.onStart();
mMapView.onStart();
}
#Override
public void onStop() {
super.onStop();
mMapView.onStop();
}
#Override
public void onMapReady(GoogleMap map) {
if (ActivityCompat.checkSelfPermission(getActivity(), android.Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
map.setMyLocationEnabled(true);
mGoogleMap = map;
addMapMarkers();
}
#Override
public void onPause() {
mMapView.onPause();
super.onPause();
}
#Override
public void onDestroy() {
mMapView.onDestroy();
super.onDestroy();
}
#Override
public void onLowMemory() {
super.onLowMemory();
mMapView.onLowMemory();
}
private void addMapMarkers()
{
if (mGoogleMap !=null)
{
if(mClusterManager == null)
{
mClusterManager = new ClusterManager<MarkerCluster>(getActivity().getApplicationContext(), mGoogleMap);
}
if (mClusterManagerRenderer == null)
{
mClusterManagerRenderer = new MyClusterManagerRenderer(getActivity(), mGoogleMap, mClusterManager);
mClusterManager.setRenderer(mClusterManagerRenderer);
}
for (UserLocation userLocation: mUserLocations)
{
Log.d(TAG, "AddMapMarkers: location: " + userLocation.getGeo_point().toString());
try {
String snippet = "";
if (userLocation.getUser().getUser_id().equals(FirebaseAuth.getInstance().getUid()))
{
snippet = "This is you";
}else {
snippet = "Determine route to " + userLocation.getUser().getUsername() + "?";
}
int avatar = R.drawable.speedvanimage; //Set the default avatar
try {
avatar = Integer.parseInt(userLocation.getUser().getAvatar());
}catch (NumberFormatException e)
{
Log.d(TAG, "addMapMarkers: no avatar for: " + userLocation.getUser().getUsername() + ", setting default");
}
MarkerCluster newMarkerCluster = new MarkerCluster(new LatLng(userLocation.getGeo_point().getLatitude(), userLocation.getGeo_point().getLongitude()),userLocation.getUser().getUsername(), snippet, avatar, userLocation.getUser());
mClusterManager.addItem(newMarkerCluster);
mClusterMarkers.add(newMarkerCluster);
}catch (NullPointerException e)
{
Log.e(TAG, "addMapMarkers: NullPointerException: " + e.getMessage());
}
}
mClusterManager.cluster();
setCameraView();
}
}
private void setCameraView()
{
double bottomBoundary = mUserPosition.getGeo_point().getLatitude() - .1;
double leftBoundary = mUserPosition.getGeo_point().getLongitude() - .1;
double topBoundary = mUserPosition.getGeo_point().getLatitude() - .1;
double rightBoundary = mUserPosition.getGeo_point().getLongitude() - .1;
}
}
Still not sure why this error is coming up weird because it shouldn't be really

Trying to make a treasure hunter game, but having issues with the surview script

The general idea is an app that allows the user to click on a field and find items. The item definitions come from a excel file. Items will scatter across the field in a random positions. When the user click on the screen it will create holes. Items that are found will display in a list when pressing the inventory button. I am having trouble with the DrawSurface script.
xml:
<android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:id="#+id/mField" />
<LinearLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="50dp">
<Button
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="0.5"
android:text="View Inventory"
android:id="#+id/btnInventory"/>
<Button
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="0.5"
android:text="Credits"
android:id="#+id/btnCredits"/>
</LinearLayout>
</LinearLayout>
MainActivity:
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.app.AlertDialog;
import android.content.DialogInterface;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivityimplementsView.OnClickListener {
ArrayList<Item> inv = DrawSurface.getInventory();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.btnInventory).setOnClickListener(this);
findViewById(R.id.btnCredits).setOnClickListener(this);
}
#Override
public void onClick(View view) {
if (view.getId() == R.id.btnCredits) {
AlertDialog.Builder dialog = new AlertDialog.Builder(this);
dialog.setTitle("Made by");
dialog.setMessage("DJon Archer" + "\nMGMS | CSE\n08/10/2017");
dialog.setPositiveButton(" OK ", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
}
});
dialog.show();
}
else if (view.getId() == R.id.btnInventory)
{
loadItems();
}
}
private ArrayList<Item> loadItems()
{
InputStream input = getResources().openRawResource(R.raw.items);
BufferedReader reader = null;
ArrayList<Item> items = new ArrayList<Item>();
String line;
try
{
reader = new BufferedReader(new InputStreamReader(input));
while ((line = reader.readLine()) !=null)
{
items.add(new Item(line));
}
}
catch (Exception e)
{
Log.e("MainActivity", "Reading list of Items failed!", e);
}
finally
{
try {
if (reader != null) reader.close();
}
catch (Exception e)
{
Log.e("MainActivity", "Error closing file reader.", e);
}
}
return items;
}
}
Item:
public class Item {
public String name;
public int x;
public int y;
//constructor
public Item(String n) {
name = n;
}
}
DrawSurface:
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.SurfaceHolder;uu
import android.view.SurfaceView;
import android.view.View;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
abstract class DrawSurface extends SurfaceView implements SurfaceHolder.Callback, View.OnTouchListener
{
SurfaceHolder holder;
Bitmap mBMPField;
Bitmap mBMPHole;
private static ArrayList<Item> mItems;
public DrawSurface(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
// Getting the holder
holder = getHolder();
holder.addCallback(this);
setOnTouchListener(this);
findViewById(R.id.mField);
}
int radius = Math.max(mBMPHole.getHeight(),mBMPHole.getWidth()) / 2;
public static ArrayList<Item> getInventory() {
//called from MainActivity.java
return mItems;
}
#Override
public boolean onTouch(View v, MotionEvent event) {
if(event.getAction()== MotionEvent.ACTION_DOWN)
{
for (int i=mItems.size()-1; i>0; i--)
mItems.get(i);
dx = mItems.x - center.x;
dy = mItems.y - center.y;
if((dx)*(dx) + (dy)*(dy) < radius*radius)
{
mItems.remove(i);
}
}
setWillNotDraw(false);
}
//Surface holder allows to control and monitor the surface
#Override
public void surfaceCreated(SurfaceHolder holder)
{
Canvas c = holder.lockCanvas();
if (c!=null) mField.Dim.set(0,0, c.getWidth(),c.getHeight());
holder.unlockCanvasAndPost(c);
invalidate();
for (int i=0; i<mItems.size(); i++)
{
mItems.get(i).x = (int)(Math.random() * (float)mFieldDim.width());
mItems.get(i).y = (int)(Math.random() * (float)mFieldDim.height());
}
}
#Override
public void onDraw(Canvas canvas)
{
drawBitmap();
}
void drawBitmap()
{
mBMPField = BitmapFactory.decodeResource(getResources(), R.drawable.field);
mBMPHole = BitmapFactory.decodeResource(getResources(), R.drawable.hole);
}
}

Change the ImageView Layer

Hye there I'm new to OpenCV but somehow good at Android! I have edited a code to change the Camera Background. For the Image to Set at the Background; I have been successfully done with it! Now the problem is that the ImageView comes over the camera screen! I just want my ImageView to come under the Camera I mean at the back of my camera! My code that I'm using is:
import android.util.Log;
import java.io.IOException;
import android.app.Activity;
import android.content.pm.ActivityInfo;
import android.content.res.Resources;
import android.graphics.PixelFormat;
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.LayoutParams;
import android.widget.ImageView;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import java.util.Random;
public class CustomCameraActivity extends Activity implements SurfaceHolder.Callback {
Camera camera;
SurfaceView surfaceView;
SurfaceHolder surfaceHolder;
boolean previewing = false;
LayoutInflater controlInflater = null;
private static final String TAG = "Svetlin SurfaceView";
private ImageView image;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
getWindow().setFormat(PixelFormat.UNKNOWN);
surfaceView = (SurfaceView)findViewById(R.id.camerapreview);
surfaceHolder = surfaceView.getHolder();
surfaceHolder.addCallback(this);
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
controlInflater = LayoutInflater.from(getBaseContext());
View viewControl = controlInflater.inflate(R.layout.custom, null);
LayoutParams layoutParamsControl = new LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.FILL_PARENT);
this.addContentView(viewControl, layoutParamsControl);
image=(ImageView)findViewById(R.id.myimage);
image.setAlpha(150);
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
if(previewing){
camera.stopPreview();
previewing = false;
}
if (camera != null){
try {
camera.setPreviewDisplay(surfaceHolder);
camera.startPreview();
previewing = true;
} catch (IOException e) {
e.printStackTrace();
}
}
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
camera = Camera.open();
Camera.Parameters params = camera.getParameters();
params.setSceneMode(Camera.Parameters.SCENE_MODE_SUNSET);
//ImageView overlay = (ImageView) findViewById(R.id.ImageView01);
//overlay.bringToFront();
camera.setParameters(params);
// tryDrawing(holder);
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
camera.stopPreview();
camera.release();
camera = null;
previewing = false;
}
private void tryDrawing(SurfaceHolder holder) {
Log.i(TAG, "Trying to draw...");
Canvas canvas = holder.lockCanvas();
if (canvas == null) {
Log.e(TAG, "Cannot draw onto the canvas as it's null");
} else {
drawMyStuff(canvas);
holder.unlockCanvasAndPost(canvas);
}
}
private void drawMyStuff(final Canvas canvas) {
Random random = new Random();
Log.i(TAG, "Drawing...");
canvas.drawRGB(255, 128, 128);
}
}
The White Image Should Come Behind the Camera as you can see in the screen shot!
The thing is I just need to know that how can I change the Camera Background doing so! Please give me Hints or any Idea so that can help me. THANKS IN ADVANCE!

Emulator doesn't show any picture. SurfaceView Android

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.

Using seekbar in android

I am making an android application where i got a seekbar for some music. I got the seekbar to show the music playing status, where i currently am in the music playback. But how can i setup a listener so that i can say that the mediaplayer would play a specific place on a track? I know the code for setting the play time in mediaplayer, but how can i handle the click events from seekbar? like onClick() or anything similar?
FIXED:
My code:
package com.mycompany.appname;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import android.app.ListActivity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Environment;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.SlidingDrawer;
public class MusicActivity extends ListActivity implements OnClickListener, OnSeekBarChangeListener {
//Called when the activity is first created
List<String> myList = new ArrayList<String>();
EditText AddItemToListViewEditText;
static final String[] COUNTRIES = new String[] {
"Movies"
};
MediaPlayer mp1;
String musicUri;
Button PausePlay;
int positionInt;
SlidingDrawer slidingDrawer2;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.musicscreen);
//Import views
PausePlay = (Button)findViewById(R.id.PausePlay);
slidingDrawer2 = (SlidingDrawer)findViewById(R.id.slidingDrawer2);
//Setup onClickListener for the buttons
PausePlay.setOnClickListener(this);
//Setup mediaPlayer
mp1 = new MediaPlayer();
//Setup ListView
setListAdapter((ListAdapter) new ArrayAdapter<String>(this, R.layout.list_item, COUNTRIES));
setListAdapter((ListAdapter) new ArrayAdapter<String>(this, R.layout.list_item, myList));
//Setup seekBar
final SeekBar progress = (SeekBar)findViewById(R.id.musicProgressBar);
progress.setOnSeekBarChangeListener(this);
ListView lv = getListView();
lv.setTextFilterEnabled(true);
File mFile = new File(Environment.getExternalStorageDirectory() + "/Music/");
myList.addAll(Arrays.asList(mFile.list()));
setListAdapter((ListAdapter) new ArrayAdapter<String>(this, R.layout.list_item, myList));
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
//When an item is clicked, play it on a MediaPlayer
//Play song
positionInt = position;
if (mp1.isPlaying()) {
//Reset mediaPlayer
mp1.reset();
try {
musicUri = Environment.getExternalStorageDirectory() + "/Music/" + myList.get(positionInt);
mp1.setDataSource(musicUri);
mp1.prepare();
mp1.start();
slidingDrawer2.animateOpen();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {
try {
musicUri = Environment.getExternalStorageDirectory() + "/Music/" + myList.get(position);
mp1.setDataSource(musicUri);
mp1.prepare();
mp1.start();
slidingDrawer2.animateOpen();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//Setup seekBar
final SeekBar progress = (SeekBar)findViewById(R.id.musicProgressBar);
progress.setProgress(0);
progress.setMax(mp1.getDuration());
new CountDownTimer(mp1.getDuration(), 250) {
public void onTick(long millisUntilFinished) {
if (progress.getProgress() == mp1.getDuration()) {
mp1.reset();
progress.setProgress(0);
} else {
progress.setProgress(mp1.getCurrentPosition());
}
}
public void onFinish() {}
}.start();
}
}
});
}
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if (fromUser == true) {
mp1.seekTo(seekBar.getProgress());
} else {
//Do nothing
}
}
#Override
public boolean onKeyDown(int KeyCode, KeyEvent event) {
if ((KeyCode == KeyEvent.KEYCODE_BACK)) {
if (mp1.isPlaying()) {
mp1.reset();
System.exit(0);
} else {
finish();
}
return true;
}
return super.onKeyDown(KeyCode, event);
}
public void onClick(View src) {
switch(src.getId()) {
case R.id.PausePlay:
if (mp1.isPlaying()) {
mp1.pause();
PausePlay.setText("Play");
} else {
mp1.start();
PausePlay.setText("Pause");
}
break;
}
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
}
My xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Musikk"
android:textAppearance="?android:attr/textAppearanceLarge" />
<FrameLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<ListView
android:id="#+android:id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
</ListView>
<SlidingDrawer
android:id="#+id/slidingDrawer2"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:content="#+id/content"
android:handle="#+id/handle" >
<Button
android:id="#+id/handle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Spiller nĂ¥" />
<LinearLayout
android:id="#+id/content"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<SeekBar
android:id="#+id/musicProgressBar"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<Button
android:id="#+id/PausePlay"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Pause" />
</LinearLayout>
</LinearLayout>
</SlidingDrawer>
</FrameLayout>
</LinearLayout>
You'll want to implement SeekBar.OnSeekBarChangeListener, then implement the onProgressChanged method.
This is called when the progress is changed (eg a user click somewhere on the seekbar), and will provide you with the new position.
Example:
public void onProgressChanged (SeekBar seekBar, int progress, boolean fromUser) {
// Do something
}
Don't forget to register the OnSeekBarChanged listener with seekBar.setOnseekBarChangeListener
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
// TODO Auto-generated method stub
if (fromUser) {
mp1.seekTo(progress);
seekBar.setProgress(progress);
}
}

Categories

Resources