In my android app I use a Fragment (CameraFragment see below) which uses a BarcodeView. When a Barcode is scanned(BarcodeCallBack) I check if it fits a pattern and if not I want to resume the scanning, but this does not work. The camera keeps running but no Barcode is scanned. As a quickfix I replace the entire Fragment but this is not how it has to be...
The Fragment:
package com.stickydata;
import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Vibrator;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.amazonaws.mobile.AWSMobileClient;
import com.amazonaws.mobilehelper.auth.IdentityManager;
import com.google.zxing.ResultPoint;
import com.journeyapps.barcodescanner.BarcodeCallback;
import com.journeyapps.barcodescanner.BarcodeResult;
import com.journeyapps.barcodescanner.BarcodeView;
import com.stickydata.AWSUtil.SDtagUtil;
import com.stickydata.events.EventResumeBarcodeScan;
import org.greenrobot.eventbus.EventBus;
import java.util.List;
import static com.facebook.FacebookSdk.getApplicationContext;
public class CameraFragment extends Fragment {
private IdentityManager identityManager;
Context mcontext;
private BarcodeView barcodeView;
final int PERMISSIONS_REQUEST_ACCESS_CAMERA=0;
View view;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view=inflater.inflate(R.layout.fragment_camera, container, false);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M &&
getActivity().checkSelfPermission(Manifest.permission.CAMERA)
!= PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.CAMERA},
PERMISSIONS_REQUEST_ACCESS_CAMERA);
} else {
barcodeView = (BarcodeView) view.findViewById(R.id.barcode_scanner);
barcodeView.decodeSingle(callback);
}
mcontext=getContext();
return view;
}
#Override
public void onResume() {
super.onResume();
barcodeView = (BarcodeView) view.findViewById(R.id.barcode_scanner);
barcodeView.resume();
barcodeView.decodeSingle(callback);
}
#Override
public void onPause() {
super.onPause();
barcodeView = (BarcodeView) view.findViewById(R.id.barcode_scanner);
barcodeView.pause();
}
private BarcodeCallback callback = new BarcodeCallback() {
#Override
public void barcodeResult(BarcodeResult result) {
if (result.getText() != null) {
barcodeView.pause();
//the vibrator on success
Vibrator v = (Vibrator) getApplicationContext().getSystemService(Context.VIBRATOR_SERVICE);
// Vibrate for 500 milliseconds
v.vibrate(200);
//after the string has been read we prozess it
String tag_string=result.getText();
AWSMobileClient.initializeMobileClientIfNecessary(getApplicationContext());
// Obtain a reference to the mobile client. It is created in the Application class.
final AWSMobileClient awsMobileClient = AWSMobileClient.defaultMobileClient();
// Obtain a reference to the identity manager.
identityManager = awsMobileClient.getIdentityManager();
SDtagUtil sdTag=new SDtagUtil(tag_string,identityManager,awsMobileClient,mcontext);
if(!sdTag.prozessTag()){//if the tag was not scanned succesfully let us start the scan again
EventBus.getDefault().post(new EventResumeBarcodeScan("bla"));
//TODO NOT WORKING
// barcodeView.resume();
// barcodeView.decodeSingle(callback);
}
}
}
#Override
public void possibleResultPoints(List<ResultPoint> resultPoints) {
}
};
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == PERMISSIONS_REQUEST_ACCESS_CAMERA|| grantResults!=null) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
barcodeView = (BarcodeView) view.findViewById(R.id.barcode_scanner);
barcodeView.decodeContinuous(callback);
}
}
}
}
The fragment xml file
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.journeyapps.barcodescanner.BarcodeView
android:id="#+id/barcode_scanner"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:zxing_use_texture_view="true"
app:zxing_preview_scaling_strategy="fitCenter"/>
</LinearLayout>
Changed to decodeContinous as suggested. The problem remains:
package com.stickydata;
import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Vibrator;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.amazonaws.mobile.AWSMobileClient;
import com.amazonaws.mobilehelper.auth.IdentityManager;
import com.google.zxing.ResultPoint;
import com.journeyapps.barcodescanner.BarcodeCallback;
import com.journeyapps.barcodescanner.BarcodeResult;
import com.journeyapps.barcodescanner.BarcodeView;
import com.stickydata.AWSUtil.SDtagUtil;
import com.stickydata.events.EventResumeBarcodeScan;
import org.greenrobot.eventbus.EventBus;
import java.util.List;
import static com.facebook.FacebookSdk.getApplicationContext;
public class CameraFragment extends Fragment {
private IdentityManager identityManager;
Context mcontext;
private BarcodeView barcodeView;
final int PERMISSIONS_REQUEST_ACCESS_CAMERA=0;
View view;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view=inflater.inflate(R.layout.fragment_camera, container, false);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M &&
getActivity().checkSelfPermission(Manifest.permission.CAMERA)
!= PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.CAMERA},
PERMISSIONS_REQUEST_ACCESS_CAMERA);
} else {
barcodeView = (BarcodeView) view.findViewById(R.id.barcode_scanner);
barcodeView.decodeContinuous(callback);
}
mcontext=getContext();
return view;
}
#Override
public void onResume() {
super.onResume();
barcodeView = (BarcodeView) view.findViewById(R.id.barcode_scanner);
barcodeView.resume();
barcodeView.decodeContinuous(callback);
}
#Override
public void onPause() {
super.onPause();
barcodeView = (BarcodeView) view.findViewById(R.id.barcode_scanner);
barcodeView.pause();
}
private BarcodeCallback callback = new BarcodeCallback() {
#Override
public void barcodeResult(BarcodeResult result) {
if (result.getText() != null) {
barcodeView.pause();
//the vibrator on success
Vibrator v = (Vibrator) getApplicationContext().getSystemService(Context.VIBRATOR_SERVICE);
// Vibrate for 500 milliseconds
v.vibrate(200);
//after the string has been read we prozess it
String tag_string=result.getText();
AWSMobileClient.initializeMobileClientIfNecessary(getApplicationContext());
// Obtain a reference to the mobile client. It is created in the Application class.
final AWSMobileClient awsMobileClient = AWSMobileClient.defaultMobileClient();
// Obtain a reference to the identity manager.
identityManager = awsMobileClient.getIdentityManager();
SDtagUtil sdTag=new SDtagUtil(tag_string,identityManager,awsMobileClient,mcontext);
if(!sdTag.prozessTag()){//if the tag was not scanned succesfully let us start the scan again
// EventBus.getDefault().post(new EventResumeBarcodeScan("bla"));
//TODO NOT WORKING
barcodeView.resume();
barcodeView.decodeContinuous(callback);
}
}
}
#Override
public void possibleResultPoints(List<ResultPoint> resultPoints) {
}
};
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == PERMISSIONS_REQUEST_ACCESS_CAMERA|| grantResults!=null) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
barcodeView = (BarcodeView) view.findViewById(R.id.barcode_scanner);
barcodeView.decodeContinuous(callback);
}
}
}
}
Hi user1406731 you are using the wrong callback, we do something similar in our mobile app. Replace your decodeSingle() callback function with decodeContinuous() callback and it should work. Here is a working example from the official doc Continous Callback example. Hope it helps you.
Hi i tried to run your code & made a little change. This is what i tested and works fine for me
import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.google.zxing.ResultPoint;
import com.journeyapps.barcodescanner.BarcodeCallback;
import com.journeyapps.barcodescanner.BarcodeResult;
import com.journeyapps.barcodescanner.BarcodeView;
import com.example.scanner.R;
import com.example.scanner.ui.base.BaseFragment;
import java.util.List;
/**
* Created by Rishabh Bhatia on 12/5/17.
*/
public class CameraFragment extends BaseFragment {
Context mcontext;
private BarcodeView barcodeView;
final int PERMISSIONS_REQUEST_ACCESS_CAMERA=0;
View view;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view=inflater.inflate(R.layout.fragment_camera, container, false);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M &&
getActivity().checkSelfPermission(Manifest.permission.CAMERA)
!= PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.CAMERA},
PERMISSIONS_REQUEST_ACCESS_CAMERA);
} else {
barcodeView = (BarcodeView) view.findViewById(R.id.barcode_scanner);
barcodeView.decodeContinuous(callback);
}
mcontext=getContext();
return view;
}
#Override
public void onResume() {
super.onResume();
barcodeView = (BarcodeView) view.findViewById(R.id.barcode_scanner);
barcodeView.resume();
}
#Override
public void onPause() {
super.onPause();
barcodeView = (BarcodeView) view.findViewById(R.id.barcode_scanner);
barcodeView.pause();
}
private BarcodeCallback callback = new BarcodeCallback() {
#Override
public void barcodeResult(BarcodeResult result) {
if (result.getText() != null) {
barcodeView.pause();
//after the string has been read we prozess it
String tag_string=result.getText();
Log.e("RISHABH", "pausing scanner, got some data "+tag_string);
if(!tag_string.equals("abc")){//if the tag was not scanned succesfully let us start the scan again
Log.e("RISHABH", "resuming scanner, data needed was not found");
barcodeView.resume(); //notice we don't call decodeContinuous function again
}
}
}
#Override
public void possibleResultPoints(List<ResultPoint> resultPoints) {
}
};
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == PERMISSIONS_REQUEST_ACCESS_CAMERA) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
barcodeView = (BarcodeView) view.findViewById(R.id.barcode_scanner);
barcodeView.decodeContinuous(callback);
}
}
}
}
Here is my logcat
05-12 23:54:13.226 31403-31403/com.example.scanner E/RISHABH: pausing scanner, got some data ABC-abc-1234
05-12 23:54:13.226 31403-31403/com.example.scanner E/RISHABH: resuming scanner, data needed was not found
05-12 23:54:18.280 31403-31403/com.example.scanner E/RISHABH: pausing scanner, got some data ABC-abc-1234
05-12 23:54:18.280 31403-31403/com.example.scanner E/RISHABH: resuming scanner, data needed was not found
05-12 23:54:19.350 31403-31403/com.example.scanner E/RISHABH: pausing scanner, got some data ABC-abc-1234
05-12 23:54:19.350 31403-31403/com.example.scanner E/RISHABH: resuming scanner, data needed was not found
05-12 23:54:20.350 31403-31403/com.example.scanner E/RISHABH: pausing scanner, got some data ABC-abc-1234
05-12 23:54:20.350 31403-31403/com.example.scanner E/RISHABH: resuming scanner, data needed was not found
05-12 23:54:21.450 31403-31403/com.example.scanner E/RISHABH: pausing scanner, got some data ABC-abc-1234
05-12 23:54:21.450 31403-31403/com.example.scanner E/RISHABH: resuming scanner, data needed was not found
05-12 23:54:22.510 31403-31403/com.example.scanner E/RISHABH: pausing scanner, got some data ABC-abc-1234
05-12 23:54:22.510 31403-31403/com.example.scanner E/RISHABH: resuming scanner, data needed was not found
05-12 23:54:33.000 31403-31403/com.example.scanner E/RISHABH: pausing scanner, got some data abc
I figured it out and thought it might help someone.
I had exactly the same issue, then figured out that resume() method do a check if it is running on MainThread.
public class Util {
public static void validateMainThread() {
if (Looper.getMainLooper() != Looper.myLooper()) {
throw new IllegalStateException("Must be called from the main thread.");
}
}
}
Here are examples of how to run code on MainThread:
Running code in main thread from another thread
I tried to run it from #JavscriptInterface method and here is my code:
public class MyInterface {
Context mContext;
ActivityMain activityMain;
MyInterface(Context c, ActivityMain am) {
mContext = c;
activityMain = am;
}
#JavascriptInterface
public void resumeScanner() {
Toast.makeText(mContext, "resume", Toast.LENGTH_SHORT).show();
Handler mainHandler = new Handler(mContext.getMainLooper());
Runnable myRunnable = new Runnable() {
#Override
public void run() {
activityMain.barcodeView.resume();
}
};
mainHandler.post(myRunnable);
}
}
Related
I am very new to android development and am building an app that can read characteristics from a BLE device. I am able to connect to a device and read its characteristics. However, I have a problem is displaying the characteristics using an adapter. Initially, I tried using the RecycleView adapter but my program kept going back to the main activity as soon as I tried to notify my recycleview adapter and everything left on the Logcat would be this:
2020-11-24 13:35:37.220 12966-12966/? I/zygote64: Late-enabling -Xcheck:jni
2020-11-24 13:35:37.346 12966-12966/com.example.wbdmx I/LoadedApk: No resource references to update in package zui.platform
2020-11-24 13:35:37.368 12966-12966/com.example.wbdmx W/Typeface: setThemeFont(): FontPath Not Changed!
2020-11-24 13:35:37.683 12966-12993/com.example.wbdmx D/OpenGLRenderer: HWUI GL Pipeline
2020-11-24 13:35:37.757 12966-12993/com.example.wbdmx I/Adreno: QUALCOMM build : e89802c, I1ef8061d77
Build Date : 03/28/18
OpenGL ES Shader Compiler Version: EV031.22.00.01
Local Branch :
Remote Branch : quic/gfx-adreno.lnx.1.0.r36-rel
Remote Branch : NONE
Reconstruct Branch : NOTHING
2020-11-24 13:35:37.766 12966-12993/com.example.wbdmx I/Adreno: PFP: 0x005ff087, ME: 0x005ff063
2020-11-24 13:35:37.774 12966-12993/com.example.wbdmx I/zygote64: android::hardware::configstore::V1_0::ISurfaceFlingerConfigs::hasWideColorDisplay retrieved: 0
2020-11-24 13:35:37.776 12966-12993/com.example.wbdmx I/OpenGLRenderer: Initialized EGL, version 1.4
2020-11-24 13:35:37.776 12966-12993/com.example.wbdmx D/OpenGLRenderer: Swap behavior 2
2020-11-24 13:35:37.871 12966-12966/com.example.wbdmx D/QuickpanelHelper: mUpdateSettings connect cost:3
2020-11-24 13:35:37.887 12966-12966/com.example.wbdmx D/QuickpanelHelper: mUpdateSettings connect cost:1
I thought recycleview was the problem and now am using a custom listview adapter but the same thing shows up in my Logcat as soon as a device is connected and the app goes back to the MainActivity view. Here are my files:
MainActivity.java:
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.bluetooth.le.BluetoothLeScanner;
import android.bluetooth.le.ScanCallback;
import android.bluetooth.le.ScanFilter;
import android.bluetooth.le.ScanResult;
import android.bluetooth.le.ScanSettings;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;
public class MainActivity extends AppCompatActivity {
private BluetoothAdapter mBluetoothAdapter = null;
private BluetoothLeScanner bleScanner=null;
private ScanSettings scanSettings;
private ScanCallback scanCallback;
private static final int REQUEST_ENABLE_BT = 1;
private static final int REQUEST_PERMISSIONS = 2;
private boolean isScanning = false;
private ArrayList<ScanResult> scanResult = new ArrayList<>();
private scanResultAdapter scanAdapter;
private RecyclerView recyclerView;
private Button scan_btn;
#RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final BluetoothManager bluetoothManager =
(BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
mBluetoothAdapter = bluetoothManager.getAdapter();
if (mBluetoothAdapter == null) {
Toast.makeText(this, "bluetooth_not_supported", Toast.LENGTH_SHORT).show();
finish();
}
recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(linearLayoutManager);
scanAdapter = new scanResultAdapter(scanResult, new CustomItemClickListner() {
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
#Override
public void onItemClick(View v, int position) {
if(isScanning){
stopScan();
}
final BluetoothDevice device = scanResult.get(position).getDevice();
Log.w("ScanResultAdapter", "Connecting to device "+device.getAddress());
Operations(v, device);
}
});
recyclerView.setAdapter(scanAdapter);
//button so that we can change its text when clicked
scan_btn = (Button) findViewById(R.id.search_button);
}
public void Operations(View view, BluetoothDevice device){
Intent intent = new Intent(this, BleOperationsActivity.class);
intent.putExtra(BluetoothDevice.EXTRA_DEVICE, device);
startActivity(intent);
}
#Override
protected void onResume() {
super.onResume();
// Ensures Bluetooth is enabled on the device. If Bluetooth is not currently enabled,
// fire an intent to display a dialog asking the user to grant permission to enable it.
if (!mBluetoothAdapter.isEnabled()) {
final Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
return;
}
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED ||
ContextCompat.checkSelfPermission(this,
Manifest.permission.READ_PHONE_STATE)
!= PackageManager.PERMISSION_GRANTED ||
ContextCompat.checkSelfPermission(this,
Manifest.permission.READ_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED ||
ContextCompat.checkSelfPermission(this,
Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.READ_PHONE_STATE,
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE},
REQUEST_PERMISSIONS);
}
}
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
private void startScan(){
//response to the scan button
bleScanner = mBluetoothAdapter.getBluetoothLeScanner();
scanSettings = new ScanSettings.Builder().setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY).build();
scanResult.clear();
scanAdapter.notifyDataSetChanged();
scanCallback = new ScanCallback(){
#Override
public void onScanResult(int callbackType, ScanResult result){
ListIterator<ScanResult> item_iterator = scanResult.listIterator();
boolean flag = true;
while(item_iterator.hasNext()){
ScanResult item = item_iterator.next();
if(item.getDevice().getAddress().equals(result.getDevice().getAddress())){
flag = false;
}
}
if(flag) {
Log.i("ScanCallback", "Found unique BLE device! Name : " + result.getDevice().getName() + " address: " +result.getDevice().getAddress());
scanResult.add(result);
scanAdapter.notifyItemInserted(scanResult.size()-1); }
}
#Override
public void onScanFailed(int errorCode){
Log.e("ScanCallback", "onScanFailed: code " + errorCode);
}
};
scanResult.clear();
// ScanFilter filter = new ScanFilter.Builder().setDeviceAddress("D7:42:44:9F:56:C9").build();
// List<ScanFilter> filters = null;
// filters.add(filter);
bleScanner.startScan(null, scanSettings, scanCallback);
isScanning = true;
}
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
private void stopScan(){
bleScanner.stopScan(scanCallback);
isScanning = false;
scan_btn.setText("SEARCH FOR DEVICES");
}
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public void button_function(View v) {
if(isScanning){
stopScan();
}
else{
startScan();
scan_btn.setText("STOP SEARCH");
}
}
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
#Override
protected void onPause() {
super.onPause();
if (bleScanner != null) {
stopScan();
bleScanner = null;
}
}
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
#Override
protected void onStop() {
super.onStop();
if (bleScanner != null) {
stopScan();
bleScanner = null;
}
}
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
#Override
protected void onDestroy() {
super.onDestroy();
if (bleScanner != null) {
stopScan();
bleScanner = null;
}
}
}
scanResultAdapter.java:
package com.example.wbdmx;
import android.bluetooth.le.ScanResult;
import android.os.Build;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.RequiresApi;
import androidx.recyclerview.widget.RecyclerView;
import java.util.List;
public class scanResultAdapter extends RecyclerView.Adapter<scanResultAdapter.ViewHolder> {
private List<ScanResult> scanResult;
private CustomItemClickListner listner;
public static class ViewHolder extends RecyclerView.ViewHolder {
TextView deviceName;
TextView deviceAddress;
TextView deviceRssi;
public ViewHolder(View view) {
super(view);
// Define click listener for the ViewHolder's View
deviceName = view.findViewById(R.id.device_name);
deviceAddress = view.findViewById(R.id.device_address);
deviceRssi = view.findViewById(R.id.device_rssi);
}
}
public scanResultAdapter(List<ScanResult> dataSet, CustomItemClickListner listner) {
scanResult = dataSet;
this.listner = listner;
}
// Create new views (invoked by the layout manager)
#Override
public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
// Create a new view, which defines the UI of the list
View view = LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.listitem_device, viewGroup, false);
final ViewHolder mViewHolder = new ViewHolder(view);
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
listner.onItemClick(v, mViewHolder.getAdapterPosition());
}
});
return mViewHolder;
}
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
#Override
public void onBindViewHolder(ViewHolder viewHolder, final int position) {
// Get element from your dataset at this position and replace the
// contents of the view with that element
viewHolder.deviceName.setText(scanResult.get(position).getDevice().getName() == null ? "Unknown": scanResult.get(position).getDevice().getName());
viewHolder.deviceRssi.setText(String.valueOf(scanResult.get(position).getRssi()));
viewHolder.deviceAddress.setText(scanResult.get(position).getDevice().getAddress());
}
// Return the size of your dataset (invoked by the layout manager)
#Override
public int getItemCount() {
if (scanResult == null) return 0;
return scanResult.size();
}
}
BleOperations.java:
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.OrientationHelper;
import androidx.recyclerview.widget.RecyclerView;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattService;
import android.bluetooth.BluetoothProfile;
import android.bluetooth.le.ScanResult;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.function.Consumer;
import java.util.stream.Collectors;
public class BleOperationsActivity extends AppCompatActivity {
private BluetoothDevice device;
private ArrayList<BluetoothGattCharacteristic> characteristics = new ArrayList<>();
private List<BluetoothGattService> services;
private static final int GATT_MAX_MTU_SIZE = 517;
ListView listView;
private characteristicAdapter charAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
if(device == null) Log.e("BleOperationsIntent", "Missing BluetoothDevice from MainActivity");
device.connectGatt(this, false, gattCallback);
setContentView(R.layout.activity_ble_operations);
listView = (ListView)findViewById(R.id.list);
}
// public void setupRecyclerView(){
// recyclerView = (RecyclerView) findViewById(R.id.characteristics_recycler_view);
// LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this, RecyclerView.VERTICAL, false);
// recyclerView.setLayoutManager(linearLayoutManager);
// charAdapter = new characteristicAdapter(characteristics, new CustomItemClickListner() {
// #RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
// #Override
// public void onItemClick(View v, int position) {
// final BluetoothGattCharacteristic character= characteristics.get(position);
// }
// }, this);
// recyclerView.setAdapter(charAdapter);
// }
private BluetoothGattCallback gattCallback = new BluetoothGattCallback() {
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
#Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
super.onConnectionStateChange(gatt, status, newState);
if(status == gatt.GATT_SUCCESS){
if (newState == BluetoothProfile.STATE_CONNECTED){
Log.w("BluetoothGattCallback", "Successfully connected to device " + gatt.getDevice().getAddress());
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
boolean ans = gatt.discoverServices();
Log.d("onConnectionStateChange", "Discover Services started: " + ans);
gatt.requestMtu(GATT_MAX_MTU_SIZE);
}
});
//gatt.discoverServices();
}
else if(newState == BluetoothProfile.STATE_DISCONNECTED){
Log.w("BluetoothGattCallback", "Succesfully disconnected form device "+ gatt.getDevice().getAddress());
gatt.close();
}
else{
Log.w("BluetoothGattCallback", "Error "+status+" encountered for "+gatt.getDevice().getAddress()+ "\nDisconnecting...");
gatt.close();
}
}
}
#RequiresApi(api = Build.VERSION_CODES.N)
#Override
public void onServicesDiscovered(BluetoothGatt gatt, int status){
super.onServicesDiscovered(gatt, status);
services = gatt.getServices();
Log.w("BluetoothGattCallback", "Discovered "+ services.size()+" for "+gatt.getDevice().getAddress());
characteristics.addAll(services.stream().flatMap(s -> s.getCharacteristics().stream())
.collect(Collectors.toList()));
Log.w("onServicesDiscovered", "size = "+characteristics.size());
printGattTable(services);
runOnUiThread(new Runnable() {
#Override
public void run() {
// charAdapter.notifyDataSetChanged();
// Log.w("onServicesDiscovered", "adapter item count = "+ charAdapter.getItemCount());
charAdapter = new characteristicAdapter(characteristics, getApplicationContext());
listView.setAdapter(charAdapter);
}
});
}
#Override
public void onMtuChanged(BluetoothGatt gatt, int mtu, int status){
boolean event = status ==BluetoothGatt.GATT_SUCCESS;
Log.w("onMtuChanged", "ATT MTU changed to "+mtu+" "+ event);
}
#Override
public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status){
if(status == BluetoothGatt.GATT_SUCCESS){
Log.i("BluetoothGattCallback", "Read characteristic success for "+ characteristic.getUuid().toString());
}
else if(status == BluetoothGatt.GATT_READ_NOT_PERMITTED){
Log.i("BluetoothGattCallback", "Read not permitted for "+ characteristic.getUuid().toString());
}
else{
Log.i("BluetoothGattCallback", "Characteristic read failed for "+ characteristic.getUuid().toString());
}
}
};
private void printGattTable(List<BluetoothGattService> services){
if(services.isEmpty()){
Log.i("printGattTable", "No service and characteristic available, call discoverServices() first?");
return;
}
Iterator<BluetoothGattService> it = services.iterator();
while(it.hasNext()){
BluetoothGattService service = it.next();
Log.i("printGattTable", "Service "+ service.getUuid()+"\nCharacteristics:\n"+service.getCharacteristics()+"\n");
}
}
}
characteristicsAdapter.java:
package com.example.wbdmx;
import android.bluetooth.BluetoothGattCharacteristic;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import java.util.List;
public class characteristicAdapter extends ArrayAdapter<BluetoothGattCharacteristic> implements View.OnClickListener{
private List<BluetoothGattCharacteristic> characteristics;
private Context mContext;
private static class ViewHolder{
TextView characteristic_uuid;
TextView characteristic_property;
}
public characteristicAdapter(List<BluetoothGattCharacteristic> characteristics, Context m) {
super(m, R.layout.row_characteristic, characteristics);
this.characteristics = characteristics;
this.mContext = m;
}
#Override
public void onClick(View v) {
}
public View getView(int position, View convertView, ViewGroup parent){
BluetoothGattCharacteristic character = getItem(position);
ViewHolder viewHolder;
final View result;
if(convertView == null){
viewHolder = new ViewHolder();
LayoutInflater inflater = LayoutInflater.from(getContext());
convertView = inflater.inflate(R.layout.row_characteristic, parent, false);
viewHolder.characteristic_uuid = (TextView) convertView.findViewById(R.id.characteristic_uuid);
viewHolder.characteristic_property= (TextView) convertView.findViewById(R.id.characteristic_properties);
result = convertView;
convertView.setTag(viewHolder);
}
else{
viewHolder = (ViewHolder)convertView.getTag();
result = convertView;
}
viewHolder.characteristic_uuid.setText(character.getUuid().toString());
viewHolder.characteristic_property.setText((character.getProperties()));
return convertView;
}
}
Edit 1: removed the build gradle file and some xml files because i hit the character limit.
This is the causing the crash:
2020-11-24 14:54:13.897 16688-16789/com.example.wbdmx D/BluetoothGatt: onConnectionUpdated() - Device=D7:42:44:9F:56:C9 interval=39 latency=0 timeout=500 status=0
2020-11-24 14:54:13.901 16688-16688/com.example.wbdmx W/ResourceType: No package identifier when getting value for resource number 0x00000002
2020-11-24 14:54:13.902 16688-16688/com.example.wbdmx D/AndroidRuntime: Shutting down VM
2020-11-24 14:54:13.912 16688-16688/com.example.wbdmx E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.wbdmx, PID: 16688
android.content.res.Resources$NotFoundException: String resource ID #0x2
at android.content.res.Resources.getText(Resources.java:339)
at android.widget.TextView.setText(TextView.java:5496)
at com.example.wbdmx.characteristicAdapter.getView(characteristicAdapter.java:53)
at android.widget.AbsListView.obtainView(AbsListView.java:2388)
at android.widget.ListView.measureHeightOfChildren(ListView.java:1408)
at android.widget.ListView.onMeasure(ListView.java:1315)
at android.view.View.measure(View.java:22087)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6602)
at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1514)
at android.widget.LinearLayout.measureVertical(LinearLayout.java:806)
at android.widget.LinearLayout.onMeasure(LinearLayout.java:685)
at android.view.View.measure(View.java:22087)
at androidx.constraintlayout.widget.ConstraintLayout$Measurer.measure(ConstraintLayout.java:792)
at androidx.constraintlayout.solver.widgets.ConstraintWidgetContainer.measure(ConstraintWidgetContainer.java:583)
at androidx.constraintlayout.solver.widgets.ConstraintWidgetContainer.layout(ConstraintWidgetContainer.java:682)
at androidx.constraintlayout.solver.widgets.analyzer.BasicMeasure.solveLinearSystem(BasicMeasure.java:159)
at androidx.constraintlayout.solver.widgets.analyzer.BasicMeasure.solverMeasure(BasicMeasure.java:290)
at androidx.constraintlayout.solver.widgets.ConstraintWidgetContainer.measure(ConstraintWidgetContainer.java:119)
at androidx.constraintlayout.widget.ConstraintLayout.resolveSystem(ConstraintLayout.java:1578)
at androidx.constraintlayout.widget.ConstraintLayout.onMeasure(ConstraintLayout.java:1690)
at android.view.View.measure(View.java:22087)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6602)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
at androidx.appcompat.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:146)
at android.view.View.measure(View.java:22087)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6602)
at androidx.appcompat.widget.ActionBarOverlayLayout.onMeasure(ActionBarOverlayLayout.java:490)
at android.view.View.measure(View.java:22087)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6602)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
at android.view.View.measure(View.java:22087)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6602)
at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1514)
at android.widget.LinearLayout.measureVertical(LinearLayout.java:806)
at android.widget.LinearLayout.onMeasure(LinearLayout.java:685)
at android.view.View.measure(View.java:22087)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6602)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
at com.android.internal.policy.DecorView.onMeasure(DecorView.java:786)
at android.view.View.measure(View.java:22087)
at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2504)
at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1542)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1799)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1430)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6885)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:966)
at android.view.Choreographer.doCallbacks(Choreographer.java:778)
at android.view.Choreographer.doFrame(Choreographer.java:713)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:952)
at android.os.Handler.handleCallback(Handler.java:790)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6606)
at java.lang.reflect.Method.invoke(Native Method)
2020-11-24 14:54:13.913 16688-16688/com.example.wbdmx E/AndroidRuntime: at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:810)
All of this was happening because I didn't convert character.getProperties() to a string value in getView() in my characteristicAdapter file.
I'm trying to create a barcode reader. The program works perfectly when the barcode is big. To read small barcodes i will need autofocus enabled.
I added setAutoFocusEnabled(true) to cameraSource, but it doesnt work.
How can i fix the following code to get autofocus working?
My testting device is a samsung galaxy J1 sm111m android 5.1.1 API 22
package com.gutimore.android.pdf417;
import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.hardware.Camera;
import android.os.Vibrator;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.SparseArray;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.widget.TextView;
import com.google.android.gms.vision.CameraSource;
import com.google.android.gms.vision.Detector;
import com.google.android.gms.vision.barcode.Barcode;
import com.google.android.gms.vision.barcode.BarcodeDetector;
import java.io.IOException;
public class MainActivity extends AppCompatActivity {
SurfaceView cameraPreview;
TextView txtResult;
BarcodeDetector barcodeDetector;
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(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
return;
}
try {
cameraSource.start(cameraPreview.getHolder());
} catch (IOException e) {
e.printStackTrace();
}
}
}
break;
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
cameraPreview = findViewById(R.id.cameraPreview);
txtResult = findViewById(R.id.txtResult);
barcodeDetector = new BarcodeDetector.Builder(this)
.setBarcodeFormats(Barcode.PDF417)
.build();
cameraSource = new CameraSource
.Builder(this, barcodeDetector)
.setRequestedPreviewSize(640, 480)
.setAutoFocusEnabled(true)
.build();
//Add Event
cameraPreview.getHolder().addCallback(new SurfaceHolder.Callback() {
#Override
public void surfaceCreated(SurfaceHolder surfaceHolder) {
if (ActivityCompat.checkSelfPermission(getApplicationContext(), android.Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
//Request permission
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.CAMERA},RequestCameraPermissionID);
return;
}
try {
cameraSource.start(cameraPreview.getHolder());
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void surfaceChanged(SurfaceHolder surfaceHolder, int i, int i1, int i2) {
}
#Override
public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
cameraSource.stop();
}
});
barcodeDetector.setProcessor(new Detector.Processor<Barcode>() {
#Override
public void release() {
}
#Override
public void receiveDetections(Detector.Detections<Barcode> detections) {
final SparseArray<Barcode> qrcodes = detections.getDetectedItems();
if(qrcodes.size() != 0)
{
txtResult.post(new Runnable() {
#Override
public void run() {
//Create vibrate
Vibrator vibrator = (Vibrator)getApplicationContext().getSystemService(Context.VIBRATOR_SERVICE);
vibrator.vibrate(1000);
txtResult.setText(qrcodes.valueAt(0).displayValue);
}
});
}
}
});
}
}
Use CamaraSource from (link)
package com.google.android.gms.samples.vision.barcodereader.ui.camera;
And initialize, as below
CameraSource camera = new CameraSource.Builder(requireContext(), barcodeDetector)
.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE)
.build();
But on some old samsung devices autofocus still won't be working. Better use ZXing
I am adding images to the firebase storage. But before adding i want to check the network connectivity for that i used a AsyncTask. But after adding it my app started crashing...
Following is my AddImages.java File of fragment_add_images.xml file
package com.example.lenovo.jdstudio;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.Toast;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import static android.app.Activity.RESULT_OK;
import static android.content.ContentValues.TAG;
import static java.security.AccessController.getContext;
/**
* A simple {#link Fragment} subclass.
*/
public class AddImages extends Fragment {
private static final int GALLERY_REQUEST = 1;
ArrayAdapter<CharSequence> adapter;
private EditText mtitle;
private EditText mresolution;
private EditText mImageType;
private EditText mprice;
private Spinner mcategory;
private ImageView mSelectImage;
private Button mSbtn;
private ProgressDialog mProgress;
private Uri mImageuri = null;
private StorageReference mStorage;
public AddImages() {
// Required empty public constructor
}
// checks if connection has active_internet connection
public static boolean hasInternetAccess(Context context) {
if (isNetworkAvailable(context)) {
try {
HttpURLConnection urlc = (HttpURLConnection)
(new URL("http://clients3.google.com/generate_204")
.openConnection());
urlc.setRequestProperty("User-Agent", "Android");
urlc.setRequestProperty("Connection", "close");
urlc.setConnectTimeout(1500);
urlc.connect();
return (urlc.getResponseCode() == 204 &&
urlc.getContentLength() == 0);
} catch (IOException e) {
Log.e(TAG, "Error checking internet connection", e);
}
} else {
return true;
}
return false;
}
// checks if user is connected to the any network
private static boolean isNetworkAvailable(Context context) {
ConnectivityManager connectivityManager
= (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_add_images, container, false);
mtitle = (EditText) v.findViewById(R.id.edit_title);
mresolution = (EditText) v.findViewById(R.id.edit_resol);
mSelectImage = (ImageView) v.findViewById(R.id.imageView);
mImageType = (EditText) v.findViewById(R.id.edit_image_type);
mprice = (EditText) v.findViewById(R.id.edit_price);
mcategory = (Spinner) v.findViewById(R.id.cat_spin);
mSbtn = (Button) v.findViewById(R.id.submit_btn);
//Initialisee progress dialog
mProgress = new ProgressDialog(getContext());
mProgress.setIndeterminate(true);
mProgress.setMessage("Uploading Please Wait...");
// DB instance
mStorage = FirebaseStorage.getInstance().getReference();
//setting the spinner
adapter = ArrayAdapter.createFromResource(getContext(), R.array.category, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mcategory.setAdapter(adapter);
final String category_value = mcategory.getSelectedItem().toString();
//Image Selection from gallery
mSelectImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent galleryIntent = new Intent(Intent.ACTION_GET_CONTENT);
galleryIntent.setType("image/*");
startActivityForResult(galleryIntent, GALLERY_REQUEST);
}
});
//Posting the activity on the database
mSbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new UploadingTask().execute(category_value);
}
});
return v;
}
// Start adding the images to the DB
private void startAdding(String category_value) {
StorageReference filepath = mStorage.child("My_Images").child(category_value).child(mImageuri.getLastPathSegment());
filepath.putFile(mImageuri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Uri downloadurl = taskSnapshot.getDownloadUrl();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
mProgress.setMessage(e.getMessage());
mProgress.show();
}
});
}
//show Alert box
private void showAlert(String title, String message) {
AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.setTitle(title);
builder.setMessage(message);
builder.setNeutralButton("Dismiss", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builder.show();
}
//To show the progress dialog
private void showProgressDialog(boolean shouldShow) {
if (shouldShow) {
mProgress.show();
} else {
mProgress.dismiss();
}
}
// checks if user has entered all the field
#NonNull
private Boolean isFormValid() {
String title_val = mtitle.getText().toString().trim();
String resolution_val = mresolution.getText().toString().trim();
String image_type_val = mImageType.getText().toString().trim();
String price_val = mprice.getText().toString().trim();
String category_value = mcategory.getSelectedItem().toString();
if (!TextUtils.isEmpty(title_val) &&
!TextUtils.isEmpty(resolution_val) &&
!TextUtils.isEmpty(image_type_val) &&
!TextUtils.isEmpty(price_val) &&
mImageuri != null &&
category_value != "Select Category") {
return true;
}
return false;
}
//Reset All the value after uploading the images
private void clearAll() {
mtitle.setText("");
mresolution.setText("");
mprice.setText("");
mImageType.setText("");
mcategory.setSelection(0);
mSelectImage.setImageResource(R.mipmap.add_btn);
}
// Set the selected image from the gallery to the Imageview
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == GALLERY_REQUEST && resultCode == RESULT_OK) {
mImageuri = data.getData();
mSelectImage.setImageURI(mImageuri);
}
}
// perform all the task on the background Thread
class UploadingTask extends AsyncTask<String, Void, Boolean> {
#Override
protected void onPreExecute() {
super.onPreExecute();
if (isFormValid()) {
showProgressDialog(true);
} else {
showAlert("Error", "Please fill all the details");
}
}
#Override
protected void onPostExecute(Boolean aBoolean) {
super.onPostExecute(aBoolean);
showProgressDialog(false);
if (aBoolean) {
showAlert("Successful", "Upload complete.");
} else {
showAlert("Failed", "Upload doesn't complete");
}
clearAll();
}
#Override
protected Boolean doInBackground(String... params) {
String catValue = params[0];
if (hasInternetAccess(getContext())) {
showAlert("Error", "Network is not available");
} else {
startAdding(catValue);
}
return null;
}
}
}
Following is the Error I am getting
E/WindowManager: android.view.WindowLeaked: Activity com.example.lenovo.jdstudio.MainActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{42192078 V.E..... R....... 0,0-683,378} that was originally added here
at android.view.ViewRootImpl.<init>(ViewRootImpl.java:422)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:250)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
at android.app.Dialog.show(Dialog.java:297)
at android.support.v7.app.AlertDialog$Builder.show(AlertDialog.java:958)
at com.example.lenovo.jdstudio.AddImages.showAlert(AddImages.java:173)
at com.example.lenovo.jdstudio.AddImages.access$300(AddImages.java:45)
at com.example.lenovo.jdstudio.AddImages$UploadingTask.onPreExecute(AddImages.java:236)
at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:587)
at android.os.AsyncTask.execute(AsyncTask.java:535)
at com.example.lenovo.jdstudio.AddImages$2.onClick(AddImages.java:136)
at android.view.View.performClick(View.java:4463)
at android.view.View$PerformClick.run(View.java:18770)
at android.os.Handler.handleCallback(Handler.java:808)
at android.os.Handler.dispatchMessage(Handler.java:103)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:5333)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:828)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:644)
at dalvik.system.NativeStart.main(Native Method)
D/GraphicBuffer: create handle(0x6178f580) (w:688, h:378, f:1)
D/OpenGLRenderer: Flushing caches (mode 0)
D/GraphicBuffer: close handle(0x6177a680) (w:688 h:378 f:1)
D/GraphicBuffer: close handle(0x63688d98) (w:688 h:378 f:1)
D/GraphicBuffer: close handle(0x6178f580) (w:688 h:378 f:1)
D/ActivityThread: ACT-DESTROY_ACTIVITY handled : 1 / android.os.BinderProxy#42190ad0
V/FA: Connection attempt already in progress
D/FA: Connected to remote service
V/FA: Processing queued up service tasks: 2
D/SQLiteDatabase: beginTransaction()
D/SQLiteDatabase: endTransaction()
V/FA: Inactivity, disconnecting from the service
I/Process: Sending signal. PID: 10017 SIG: 9
W/IInputConnectionWrapper: showStatusIcon on inactive InputConnection
Disconnected from the target VM, address: 'localhost:8600', transport: 'socket'
Please Help me out!!
This is a problem I came across when attempting to show a ProgressDialog in onPreExecute() in an AsyncTask. The only solution I found was to manage the dialog outside the task, so instead of
mSbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new UploadingTask().execute(category_value);
}
});
try instead:
mSbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (isFormValid()) {
showProgressDialog(true);
new UploadingTask().execute(category_value);
} else {
showAlert("Error", "Please fill all the details");
}
}
});
And remove the corresponding code from the onPreExecute() method in UploadingTask.
I think the dialog can be dismissed in onPostExecute() without problem, but you could set up a callback interface to the task to notify the caller when the task is complete to allow it to manage the dismissal.
I am trying to make a text scanner application with camera that recognizes text and shows in screen.But instead of showing camera it shows a black screen. How can I solve this.
My code is here
package com.myapp.game.easynepalirecharge;
import android.Manifest;
import android.app.ActionBar;
import android.content.pm.PackageManager;
import android.graphics.Camera;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.util.SparseArray;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.ViewGroup;
import android.widget.TextView;
import com.google.android.gms.vision.CameraSource;
import com.google.android.gms.vision.Detector;
import com.google.android.gms.vision.text.TextBlock;
import com.google.android.gms.vision.text.TextRecognizer;
import java.io.IOException;
public class MainActivity extends AppCompatActivity {
SurfaceView cameraView;
TextView textView;
CameraSource cameraSource;
final int REQUESTCAMERAPERMISSION = 105;
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull final int[] grantResults) {
switch (requestCode) {
case REQUESTCAMERAPERMISSION:
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.checkSelfPermission(getApplication(), 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);
cameraView = (SurfaceView) findViewById(R.id.surfaceView);
textView = (TextView) findViewById(R.id.textView);
TextRecognizer textRecognizer = new TextRecognizer.Builder(getApplicationContext()).build();
if (!textRecognizer.isOperational()) {
Log.v("haha", "error not operational");
} else {
cameraSource = new CameraSource.Builder(getApplicationContext(), textRecognizer).
setFacing(CameraSource.CAMERA_FACING_BACK)
.setRequestedPreviewSize(3840, 2160)
.setRequestedFps(2.0f)
.setAutoFocusEnabled(true)
.build();
cameraView.getHolder().addCallback(new SurfaceHolder.Callback() {
#Override
public void surfaceCreated(SurfaceHolder holder) {
try {
if (ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.CAMERA}, REQUESTCAMERAPERMISSION);
cameraSource.start(cameraView.getHolder());
return;
}
} catch (Exception 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) {
textView.post(new Runnable() {
#Override
public void run() {
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i <= items.size(); i++) {
TextBlock item = items.valueAt(i);
stringBuilder.append(item.getValue());
stringBuilder.append("\n");
}
textView.setText(stringBuilder.toString());
}
});
}
}
}
);
}
}
}
and another thing I wanna ask. Which one is better. This or the tess two library?
have you stopped camera properly. Try to do camera functions in thread so that your single task does not be expensive. The reason i thought problem is that get your permission at run time.
try this
https://developer.android.com/training/permissions/requesting.html
The code is posted here and the app crashes when the login button is clicked with null pointer exception at homefragment on click.im a beginer.please help.logcat http://postimg.org/image/6d1qyszkd/
simple facebook class basically is :
public SimpleFacebook()
{
mSessionStatusCallback = new SessionStatusCallback();
}
public static void initialize(Activity activity)
{
if (mInstance == null)
{
mInstance = new SimpleFacebook();
}
mActivity = activity;
}
public static SimpleFacebook getInstance(Activity activity)
{
if (mInstance == null)
{
mInstance = new SimpleFacebook();
}
mActivity = activity;
return mInstance;
}
public static SimpleFacebook getInstance()
{
return mInstance;
}
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.util.Pair;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.parse.GetDataCallback;
import com.sromku.simple.fb.SimpleFacebook;
import com.sromku.simple.fb.Properties;
import com.sromku.simple.fb.SimpleFacebook;
import com.sromku.simple.fb.SimpleFacebook.OnFriendsRequestListener;
import com.sromku.simple.fb.SimpleFacebook.OnLoginListener;
import com.sromku.simple.fb.SimpleFacebook.OnLogoutListener;
import com.sromku.simple.fb.SimpleFacebook.OnProfileRequestListener;
import com.sromku.simple.fb.entities.Profile;
import com.sromku.simple.fb.example.utils.Utils;
import com.sromku.simple.fb.utils.Attributes;
import com.sromku.simple.fb.utils.PictureAttributes;
import com.sromku.simple.fb.utils.PictureAttributes.PictureType;
public class HomeFragment extends Fragment {
protected static final String TAG = HomeFragment.class.getName();
private SimpleFacebook mSimpleFacebook;
ProgressDialog mProgress;
Button mButtonLogin;
Button mButtonLogout;
TextView mTextStatus;
// Login listener
private OnLoginListener mOnLoginListener = new OnLoginListener()
{
#Override
public void onFail(String reason)
{
mTextStatus.setText(reason);
Log.w(TAG, "Failed to login");
}
#Override
public void onException(Throwable throwable)
{
mTextStatus.setText("Exception: " + throwable.getMessage());
Log.e(TAG, "Bad thing happened", throwable);
}
#Override
public void onThinking()
{
// show progress bar or something to the user while login is happening
mTextStatus.setText("Thinking...");
}
#Override
public void onLogin()
{
// change the state of the button or do whatever you want
mTextStatus.setText("Logged in");
loggedInUIState();
toast("You are logged in");
}
#Override
public void onNotAcceptingPermissions()
{
toast("You didn't accept read permissions");
}
};
// Logout listener
private OnLogoutListener mOnLogoutListener = new OnLogoutListener()
{
#Override
public void onFail(String reason)
{
mTextStatus.setText(reason);
Log.w(TAG, "Failed to login");
}
#Override
public void onException(Throwable throwable)
{
mTextStatus.setText("Exception: " + throwable.getMessage());
Log.e(TAG, "Bad thing happened", throwable);
}
#Override
public void onThinking()
{
// show progress bar or something to the user while login is happening
mTextStatus.setText("Thinking...");
}
#Override
public void onLogout()
{
// change the state of the button or do whatever you want
mTextStatus.setText("Logged out");
loggedOutUIState();
toast("You are logged out");
}
};
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.homend_home_fragment, container, false);
// test local language
Utils.updateLanguage(getActivity(), "en");
Utils.printHashKey(getActivity());
mButtonLogin = (Button)rootView.findViewById(R.id.button_login);
mButtonLogout = (Button)rootView.findViewById(R.id.button_logout);
mTextStatus = (TextView)rootView.findViewById(R.id.text_status);
mButtonLogin.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View arg0)
{
mSimpleFacebook.login(mOnLoginListener);
}
});
// 2. Logout example
mButtonLogout.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View arg0)
{
mSimpleFacebook.logout(mOnLogoutListener);
}
});
return rootView;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
mSimpleFacebook.onActivityResult(getActivity(), requestCode, resultCode, data);
super.onActivityResult(requestCode, resultCode, data);
}
private void setUIState()
{
if (mSimpleFacebook.isLogin())
{
loggedInUIState();
}
else
{
loggedOutUIState();
}
}
/**
* Show toast
*
* #param message
*/
private void toast(String message)
{
Toast.makeText(getActivity(), message, Toast.LENGTH_SHORT).show();
}
private void loggedInUIState()
{
mButtonLogin.setEnabled(false);
mButtonLogout.setEnabled(true);
mTextStatus.setText("Logged in");
}
private void loggedOutUIState()
{
mButtonLogin.setEnabled(true);
mButtonLogout.setEnabled(false);
mTextStatus.setText("Logged out");
}
private void showDialog()
{
mProgress = ProgressDialog.show(getActivity(), "Thinking",
"Waiting for Facebook", true);
}
private void hideDialog()
{
mProgress.hide();
}
public class OnProfileRequestAdapter implements OnProfileRequestListener
{
#Override
public void onThinking()
{
}
#Override
public void onException(Throwable throwable)
{
}
#Override
public void onFail(String reason)
{
}
#Override
public void onComplete(Profile profile)
{
}
}
}
I think problem might be here. You have just declared your variable
private SimpleFacebook mSimpleFacebook;
you haven't initialized that variable so you got NPE
So initialized it on onCreateView() method.
mSimpleFacebook = SimpleFacebook.getInstance(getActivity());
And yet you get error then you need to finally change
mSimpleFacebook = SimpleFacebook.getInstance();
Add this line to manifest file..
<activity android:name="com.facebook.LoginActivity" android:screenOrientation="portrait" android:configChanges="keyboardHidden|orientation">
</activity>
which would be finally works for you.!!