I am trying to display a camera on in my android app, but all I am getting is a black box where the SurfaceView is located.
I am using this simple XML layout:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.lazylayer.photoshoot.MainActivity">
<SurfaceView
android:id="#+id/surface_view"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
With this Activity:
public class MainActivity extends AppCompatActivity implements SurfaceHolder.Callback {
SurfaceView surfaceView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
surfaceView = (SurfaceView)findViewById(R.id.surface_view);
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
try{
CameraManager cameraManager = (CameraManager)getSystemService(Context.CAMERA_SERVICE);
String[] cameras = cameraManager.getCameraIdList();
cameraManager.openCamera(cameras[0], deviceCallback, null);
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {}
CameraDevice.StateCallback deviceCallback = new CameraDevice.StateCallback() {
#Override
public void onOpened(CameraDevice camera) {
try {
List<Surface> surfaceList = Collections.singletonList(surfaceView.getHolder().getSurface());
camera.createCaptureSession(surfaceList, sessionCallback, null);
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
#Override
public void onDisconnected(CameraDevice camera) {}
#Override
public void onError(CameraDevice camera, int error) {}
};
CameraCaptureSession.StateCallback sessionCallback = new CameraCaptureSession.StateCallback() {
#Override
public void onConfigured(CameraCaptureSession session) {
}
#Override
public void onConfigureFailed(CameraCaptureSession session) {}
};
}
Here is what gets displayed when the app is ran on my phone:
I was able to fix the issue by using a FrameLayout instead of a SurfaceView
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/camera_view">
</FrameLayout>
Related
Today i am posting my first question here in stackoverflow.
My app's subject is speech to text application all the app is working but the text doen't appear in its zone after saying the speech. So i am here asking you all for help.
Belong my xml file :
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<EditText
android:id="#+id/edittext"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:hint="Tap Mic to Speak"
android:padding="20dp"
android:textColor="#000000"
android:textSize="20sp" />
<ImageButton
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/edittext"
android:layout_centerHorizontal="true"
android:padding="40dp"
android:background="#color/white"
android:src="#drawable/ic_baseline_mic_24" />
</RelativeLayout>
And my main code:
package com.example.translationapp;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
checkPermission();
final EditText edittext = findViewById(R.id.edittext);
final SpeechRecognizer mSpeechRecognizer = SpeechRecognizer.createSpeechRecognizer(this);
final Intent mSpeechRecognizerIntent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
mSpeechRecognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
mSpeechRecognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE,
Locale.getDefault());
mSpeechRecognizer.setRecognitionListener(new RecognitionListener() {
#Override
public void onReadyForSpeech(Bundle bundle) {
}
#Override
public void onBeginningOfSpeech() {
}
#Override
public void onRmsChanged(float v) {
}
#Override
public void onBufferReceived(byte[] bytes) {
}
#Override
public void onEndOfSpeech() {
}
#Override
public void onError(int i) {
}
#Override
public void onResults(Bundle bundle) {
//getting all the matches
ArrayList<String> matches = bundle
.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
//displaying the first match
if (matches != null) {
edittext.setText(matches.get(0));
}
}
#Override
public void onPartialResults(Bundle bundle) {
}
#Override
public void onEvent(int i, Bundle bundle) {
}
});
findViewById(R.id.button).setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
switch (motionEvent.getAction()) {
case MotionEvent.ACTION_UP:
mSpeechRecognizer.stopListening();
edittext.setHint("You will see input here");
break;
case MotionEvent.ACTION_DOWN:
mSpeechRecognizer.startListening(mSpeechRecognizerIntent);
edittext.setText("");
edittext.setHint("Listening...");
break;
}
return false;
}
});
}
private void checkPermission() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (!(ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED)) {
Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS,
Uri.parse("package:" + getPackageName()));
startActivity(intent);
finish();
}
}
}
}
So please again and thank you all for your time.
I've been looking for information on Google for 2 days. But all
without results.
I want to use not the full screen mode, but the reduced one, so that
you can scan a certain area.
In Api Google, I also did not find what I needed.
The variant with resizing in SurfaceView is attached with a picture.
As you can see, the result is deplorable ((.
Is there a solution to my problem?
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent">
<SurfaceView
android:layout_centerInParent="true"
android:id="#+id/surface_view"
android:layout_width="match_parent"
android:layout_height="100dp"/>
<TextView
android:id="#+id/txtView"
android:text="No Text"
android:layout_alignParentBottom="true"
android:textColor="#android:color/white"
android:textSize="20sp"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</RelativeLayout>
public class MainActivity extends AppCompatActivity {
#BindView(R.id.surface_view) SurfaceView cameraView;
#BindView(R.id.txtView) TextView txtView;
CameraSource cameraSource;
final int RequestCameraPermissionID = 1001;
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode){
case RequestCameraPermissionID:
if (grantResults[0]==PackageManager.PERMISSION_GRANTED){
if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
return;
}
try {
cameraSource.start(cameraView.getHolder());
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
TextRecognizer textRecognizer = new TextRecognizer.Builder(getApplicationContext()).build();
if (!textRecognizer.isOperational()) {
Log.e("MainActivity", "onCreate= " + "Detecter");
} else {
cameraSource = new CameraSource.Builder(getApplicationContext(), textRecognizer )
.setFacing(CameraSource.CAMERA_FACING_BACK)
.setRequestedFps(2.0f)
.setAutoFocusEnabled(true)
.build();
cameraView.getHolder().addCallback(new SurfaceHolder.Callback() {
#Override
public void surfaceCreated(SurfaceHolder holder) {
try {
if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.CAMERA},
RequestCameraPermissionID);
return;
}
cameraSource.start(cameraView.getHolder());
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
cameraSource.stop();
}
});
textRecognizer.setProcessor(new Detector.Processor<TextBlock>() {
#Override
public void release() {
}
#Override
public void receiveDetections(Detector.Detections<TextBlock> detections) {
final SparseArray<TextBlock> items=detections.getDetectedItems();
if (items.size()!=0){
txtView.post(() -> {
StringBuilder stringBuilder=new StringBuilder();
for (int i = 0; i < items.size(); i++) {
TextBlock item=items.valueAt(i);
stringBuilder.append(item.getValue());
stringBuilder.append("\n");
}
txtView.setText(stringBuilder.toString());
});
}
}
});
}
}
}
I am new to Android programming, and have one question.
I am trying to access findViewById in my AsyncTask, but obviously, by default this will not be available, because I am not performing any actions against a View object.
I have found, a few articles, explaining how to solve this, but they are old, 5 years and up, and would like to know if this is still the correct approach? I am using android's data binding methodology, and this is supposed to replace findViewById calls, but I don't see how, in this scenario?
Is this way of solving still valid?
Here, is my code, in case there is a better solution. I am trying to access the progressbar in this view from within the AsyncTask
My Profile view:
<?xml version="1.0" encoding="utf-8"?>
<layout>
<data>
<variable name="user" type="Models.User" />
<variable name="viewActions" type="ViewModel.ProfileViewModel" />
</data>
<LinearLayout xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center_horizontal|top">
<ProgressBar
android:id="#+id/progressPostUser"
android:layout_width="120dp"
android:layout_height="120dp"
android:visibility="gone"/>
<include layout="#layout/main_toolbar"/>
<ImageView
android:id="#+id/imagePlaceHolder"
android:layout_width="250dp"
android:layout_height="150dp"
android:layout_marginTop="20dp"
android:layout_marginBottom="5dp"
android:src="#mipmap/ic_account"/>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp">
<ImageButton
android:id="#+id/btnOpenCamera"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_marginRight="10dp"
android:src="#mipmap/ic_account"
android:onClick="btnOpenCamper_OnClick"/>
<ImageButton
android:id="#+id/btnChooseImage"
android:layout_width="50dp"
android:layout_height="50dp"
android:src="#mipmap/ic_view_list"/>
</LinearLayout>
<EditText
android:layout_width="250dp"
android:layout_height="50dp"
android:hint="Name"
android:text="#={user._name}"/>
<EditText
android:layout_width="250dp"
android:layout_height="50dp"
android:hint="Surname"
android:text="#={user._surname}"/>
<EditText
android:layout_width="250dp"
android:layout_height="50dp"
android:hint="Email"
android:text="#={user._email}"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Save"
android:onClick="#{() -> viewActions.onSaveClicked(user)}"/>
</LinearLayout>
My Activity class:
public class ProfileActivity extends MenuActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ActivityProfileBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_profile);
binding.setUser(new User());
binding.setViewActions(new ProfileViewModel(this));
//get the toolbar
Toolbar tb = (Toolbar)findViewById(R.id.toolbarMain);
setSupportActionBar(tb);
}
}
And the 'ViewModel' which handles events from the View.
public class ProfileViewModel {
private User mUser;
private Context mContext;
public ProfileViewModel(Context context){
mContext = context;
}
public void onSaveClicked(User user) {
String nameTest = user.get_name();
String surnameTest = user.get_surname();
Toast.makeText(mContext, user.get_name(), Toast.LENGTH_SHORT).show();
}
}
Here is my User class.
public class User extends BaseObservable {
public User() {
}
private String _name;
#Bindable
public String get_name() {
return _name;
}
public void set_name(String _name) {
this._name = _name;
notifyPropertyChanged(BR._name);
}
private String _surname;
#Bindable
public String get_surname() {
return _surname;
}
public void set_surname(String _surname) {
this._surname = _surname;
notifyPropertyChanged(BR._surname);
}
private String _email;
#Bindable
public String get_email() {
return _email;
}
public void set_email(String _email) {
this._email = _email;
notifyPropertyChanged(BR._email);
}
private Bitmap _profileImage;
public Bitmap get_profileImage() {
return _profileImage;
}
public void set_profileImage(Bitmap _profileImage) {
this._profileImage = _profileImage;
}
public String toJsonString(){
try{
JSONObject jObject = new JSONObject();
jObject.put("Name", get_name());
jObject.put("Surname", get_surname());
jObject.put("Email", get_email());
jObject.put("ProfileImage", Base64.encodeToString(convertBitmapToBytes(), Base64.DEFAULT));
} catch (Exception ex){
Log.d("Error", "User.toJson");
}
return "";
}
#Override
public String toString() {
return super.toString();
}
private byte[] convertBitmapToBytes(){
ByteArrayOutputStream stream = new ByteArrayOutputStream();
get_profileImage().compress(Bitmap.CompressFormat.PNG, 100, stream);
return stream.toByteArray();
}
}
You can do something like this. You can change information in the onPre, doInBackground, onPost --> This wouldnt matter much.
public class MainActivity extends AppCompatActivity {
TestView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.textView);
}
private class ASyncCall extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
//What happens BEFORE everything in the background.
}
#Override
protected Void doInBackground(Void... arg0) {
textView.setText("set the text");
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
//After you get everything you need from the JSON.
}
}
}
I really did not like the idea of passing context, and the View around to different objects, and like to keep the view specific functionality within the activity class itself, so I implemented an interface, that I passed around, as follow:
Here is my interface:
public interface IProfiler {
void ShowProgressbar();
void HideProgressbar();
void MakeToast();
}
My activity class implements this interface, as follow:
public class ProfileActivity extends MenuActivity implements IProfiler {
private ProgressBar mProgressar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ActivityProfileBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_profile);
binding.setUser(new User());
binding.setViewActions(new ProfileViewModel(this));
//get the toolbar
Toolbar tb = (Toolbar)findViewById(R.id.toolbarMain);
setSupportActionBar(tb);
//set the Progressbar
mProgressar = (ProgressBar)findViewById(R.id.progressPostUser);
}
#Override
public void ShowProgressbar() {
mProgressar.setVisibility(View.VISIBLE);
}
#Override
public void HideProgressbar() {
mProgressar.setVisibility(View.GONE);
}
#Override
public void MakeToast() {
Toast.makeText(this, "Some toast", Toast.LENGTH_SHORT);
}
}
My ProfileViewModel, which excepts the interface as parameter:
public class ProfileViewModel {
private User mUser;
private IProfiler mProfiler;
public ProfileViewModel(IProfiler profiler){
mProfiler = profiler;
}
public void onSaveClicked(User user) {
try {
String nameTest = user.get_name();
String surnameTest = user.get_surname();
new AsyncTaskPost(mProfiler).execute(new URL("http://www.Trackme.com"));
}
catch (Exception ex) {
}
}
}
And then finally, my AsyncTaskPost.
public class AsyncTaskPost extends AsyncTask<URL, Void, Void> {
private IProfiler mProfilerActions;
public AsyncTaskPost(IProfiler profilerActions){
mProfilerActions = profilerActions;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
mProfilerActions.ShowProgressbar();
}
#Override
protected Void doInBackground(URL... urls) {
try{
Thread.sleep(5000);
return null;
}
catch (Exception ex) {
return null;
}
}
#Override
protected void onPostExecute(Void aVoid) {
mProfilerActions.HideProgressbar();
mProfilerActions.MakeToast();
}
#Override
protected void onCancelled() {
super.onCancelled();
mProfilerActions.HideProgressbar();
}
}
I'm trying to put the admob in my LIBGDX application, but by following the tutorial GitHub and I can not run my application. Please someone tries to help me set up the code. Below is main_activity, main.xml.
Note: All modifications were made in AndroidManifest.xml as tutorial google admob.
Main.xml :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:ads="http://schemas.android.com/apk/res-auto"
android:id="#+id/main_layout"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
</LinearLayout>
MainAcitivity:
public class MainActivity extends AndroidApplication implements AdsController {
private static final String BANNER_AD_UNIT_ID = "ca-app-pub-3954521267929789/5402418153";
AdView bannerAd;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
AndroidApplicationConfiguration cfg = new AndroidApplicationConfiguration();
cfg.useGL20 = false;
View gameView = initializeForView(new FXGame(this), cfg);
setupAds();
RelativeLayout layout = new RelativeLayout(this);
layout.addView(gameView, ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.MATCH_PARENT);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
layout.addView(bannerAd, params);
setContentView(layout);
}
public void setupAds() {
bannerAd = new AdView(this);
bannerAd.setVisibility(View.INVISIBLE);
bannerAd.setBackgroundColor(0xff000000); // black
bannerAd.setAdUnitId(BANNER_AD_UNIT_ID);
bannerAd.setAdSize(AdSize.SMART_BANNER);
}
#Override
public void showBannerAd() {
runOnUiThread(new Runnable() {
#Override
public void run() {
bannerAd.setVisibility(View.VISIBLE);
AdRequest.Builder builder = new AdRequest.Builder();
AdRequest ad = builder.build();
bannerAd.loadAd(ad);
}
});
}
#Override
public void hideBannerAd() {
runOnUiThread(new Runnable() {
#Override
public void run() {
bannerAd.setVisibility(View.INVISIBLE);
}
});
}
}
MY FXGame:
public class FXGame extends Game {
private AdsController adsController;
public ZBGame(AdsController adsController){
this.adsController = adsController;
}
#Override
public void create() {
AssetLoader.load();
setScreen(new SplashScreen(this));
adsController.showBannerAd();
}
#Override
public void dispose() {
super.dispose();
AssetLoader.dispose();
}
}
Interface AdsController:
public interface AdsController {
public void showBannerAd();
public void hideBannerAd();
}
You are setting visibility of bannerAd wrong in your showBannerAd and hideBannerAd methods. It should be opposite. Additionaly please ensure that you are calling show showBannerAd().
AdMob view is not visible, but clickable. If call onResume() view become visible. When I use
AdMob library all work fine, but if use google play services for AdMob I got this issue.
My code is bellow.
protected void initAdMob(){
if (mAdView == null) {
mAdView = new AdView(MainActivity.this);
mAdView.setAdUnitId(getString(R.string.admob_id));
mAdView.setAdSize(AdSize.SMART_BANNER);
mAdView.loadAd(new AdRequest.Builder().build());
mAdView.setAdListener(new AdListener() {
#Override
public void onAdClosed() {
super.onAdClosed();
}
#Override
public void onAdFailedToLoad(int errorCode) {
super.onAdFailedToLoad(errorCode);
}
#Override
public void onAdLeftApplication() {
super.onAdLeftApplication();
}
#Override
public void onAdOpened() {
super.onAdOpened();
}
#Override
public void onAdLoaded() {
super.onAdLoaded();
}
});
}
}
private void showAdMob() {
initAdMob();
FrameLayout.LayoutParams params = new FrameLayout.LayoutParams( FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.WRAP_CONTENT);
params.gravity = Gravity.CENTER_HORIZONTAL;
mAdView.setLayoutParams(params);
FrameLayout fl = (FrameLayout) mainView.findViewById(R.id.adView);
if (fl != null) {
fl.removeAllViews();
fl.addView(mAdView, params);
}
}
#Override
public void onResume() {
if(mAdView != null){
mAdView.resume();
}
super.onResume();
}
view xml:
<FrameLayout
android:id="#+id/gameLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<FrameLayout
android:id="#+id/adView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_alignParentBottom="true"/>
</RelativeLayout>
Need to use Mediation ID instead Publisher ID in AdMob