Related
// Camera activity code
public class CamActivity extends AppCompatActivity implements
ActivityCompat.OnRequestPermissionsResultCallback,
AspectRatioFragment.Listener {
public static boolean activityStatus;
private Handler handler = new Handler();
private FirebaseAnalytics mFirebaseAnalytics;
private static final String TAG = "CamActivity";
private static final int REQUEST_CAMERA_PERMISSION = 1;
private static final String FRAGMENT_DIALOG = "dialog";
private static final int SELECT_PICTURE = 1;
private static final int[] FLASH_OPTIONS = {
CameraView.FLASH_AUTO,
CameraView.FLASH_OFF,
CameraView.FLASH_ON,
};
private static final int[] FLASH_ICONS = {
R.drawable.ic_flash_auto,
R.drawable.ic_flash_off,
R.drawable.ic_flash_on,
};
private static final int[] FLASH_TITLES = {
R.string.flash_auto,
R.string.flash_off,
R.string.flash_on,
};
private int mCurrentFlash;
private CameraView mCameraView;
private Handler mBackgroundHandler;
private FloatingActionButton fab;
private ImageView open_gallery;
private View.OnClickListener mOnClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.take_picture:
if (mCameraView != null) {
try {
mCameraView.takePicture();
/*handler.postDelayed(() ->
mCameraView.takePicture(),
500);*/
}catch (Exception e){
Log.e(TAG,"mCameraView"+e.toString());
}
}
break;
case R.id.open_gallery:
openGallery();
break;
}
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mFirebaseAnalytics = FirebaseAnalytics.getInstance(this);
Bundle bundle1 = new Bundle();
bundle1.putString(TAG, TAG);
bundle1.putString(TAG, TAG);
mFirebaseAnalytics.logEvent(TAG, bundle1);
setContentView(R.layout.activity_camera_renderer);
mCameraView = findViewById(R.id.camera);
open_gallery = findViewById(R.id.open_gallery);
if (open_gallery!=null)
open_gallery.setOnClickListener(mOnClickListener);
activityStatus = true;
if (mCameraView != null) {
mCameraView.addCallback(mCallback);
}
fab = findViewById(R.id.take_picture);
if (fab != null) {
fab.setOnClickListener(mOnClickListener);
}
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayShowTitleEnabled(false);
}
//toolbar.setTitle("Camera");
toolbar.setNavigationIcon(R.drawable.ic_back_arrow);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
closeCamera();
}
});
//Listen for capture image and close camera
registerReceiver(syncCamReceiver, new IntentFilter("Camera"));
}
#Override
public void onBackPressed() {
closeCamera();
super.onBackPressed();
}
/**CLose camera**/
private void closeCamera(){
try{
unregisterReceiver(syncCamReceiver);
}
catch (Exception e){
Log.d(TAG,"Error while unregistering");
}
SN88Constant.getIk6Obj(getApplicationContext()).sendPhotoSwitch(false);
CamActivity.this.finish();
}
BroadcastReceiver syncCamReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context arg0, Intent intent) {
if (intent.getAction().equalsIgnoreCase("Camera")) {
//0 for open cam, 1 take picture 2 close camera
if(intent.getIntExtra(Constants.CAMERA_REQUEST_TYPE,-1)==1){
fab .performClick();
}
else if(intent.getIntExtra(Constants.CAMERA_REQUEST_TYPE,-1)==2){
CamActivity.this.finish();
}
}
}
};
#Override
protected void onResume() {
activityStatus = true;
try {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
== PackageManager.PERMISSION_GRANTED) {
if (mCameraView != null)
mCameraView.start();
} else if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.CAMERA)) {
ConfirmationDialogFragment
.newInstance(R.string.camera_permission_confirmation,
new String[]{Manifest.permission.CAMERA},
REQUEST_CAMERA_PERMISSION,
R.string.camera_permission_not_granted)
.show(getSupportFragmentManager(), FRAGMENT_DIALOG);
} else {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA},
REQUEST_CAMERA_PERMISSION);
}
}catch (Exception e){
Log.d(TAG,"Camera_onresume"+e.toString());
}
super.onResume();
}
#Override
protected void onPause() {
mCameraView.stop();
super.onPause();
}
#Override
protected void onDestroy() {
closeCamera();
activityStatus = false;
if (mBackgroundHandler != null) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
mBackgroundHandler.getLooper().quitSafely();
} else {
mBackgroundHandler.getLooper().quit();
}
mBackgroundHandler = null;
}
super.onDestroy();
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions,
#NonNull int[] grantResults) {
switch (requestCode) {
case REQUEST_CAMERA_PERMISSION:
if (permissions.length != 1 || grantResults.length != 1) {
throw new RuntimeException("Error on requesting camera permission.");
}
if (grantResults[0] != PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, R.string.camera_permission_not_granted,
Toast.LENGTH_SHORT).show();
}
// No need to start camera here; it is handled by onResume
break;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.aspect_ratio:
FragmentManager fragmentManager = getSupportFragmentManager();
if (mCameraView != null
&& fragmentManager.findFragmentByTag(FRAGMENT_DIALOG) == null) {
final Set<AspectRatio> ratios = mCameraView.getSupportedAspectRatios();
final AspectRatio currentRatio = mCameraView.getAspectRatio();
AspectRatioFragment.newInstance(ratios, currentRatio)
.show(fragmentManager, FRAGMENT_DIALOG);
}
return true;
case R.id.switch_flash:
if (mCameraView != null) {
mCurrentFlash = (mCurrentFlash + 1) % FLASH_OPTIONS.length;
item.setTitle(FLASH_TITLES[mCurrentFlash]);
item.setIcon(FLASH_ICONS[mCurrentFlash]);
mCameraView.setFlash(FLASH_OPTIONS[mCurrentFlash]);
}
return true;
case R.id.switch_camera:
if (mCameraView != null) {
try {
int facing = mCameraView.getFacing();
mCameraView.setFacing(facing == CameraView.FACING_FRONT ?
CameraView.FACING_BACK : CameraView.FACING_FRONT);
}catch (Exception e){
e.printStackTrace();
}
}
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onAspectRatioSelected(#NonNull AspectRatio ratio) {
if (mCameraView != null) {
//Toast.makeText(this, ratio.toString(), Toast.LENGTH_SHORT).show();
try {
mCameraView.setAspectRatio(ratio);
}catch (Exception e){
Log.d(TAG,"onAspectRatioSelected"+e.toString());
}
}
}
private Handler getBackgroundHandler() {
if (mBackgroundHandler == null) {
HandlerThread thread = new HandlerThread("background");
thread.start();
mBackgroundHandler = new Handler(thread.getLooper());
}
return mBackgroundHandler;
}
private CameraView.Callback mCallback
= new CameraView.Callback() {
#Override
public void onCameraOpened(CameraView cameraView) {
Log.d(TAG, "onCameraOpened");
}
#Override
public void onCameraClosed(CameraView cameraView) {
Log.d(TAG, "onCameraClosed");
}
#Override
public void onPictureTaken(CameraView cameraView, final byte[] data) {
Log.d(TAG, "onPictureTaken " + data.length);
Toast.makeText(cameraView.getContext(), R.string.picture_taken, Toast.LENGTH_SHORT)
.show();
getBackgroundHandler().post(new Runnable() {
#Override
public void run() {
String folderPath = Environment.getExternalStorageDirectory() + "/DCIM/Camera";
File folder = new File(folderPath);
if (!folder.exists()) {
File wallpaperDirectory = new File(folderPath);
wallpaperDirectory.mkdir();
}
File file = new File(folderPath,"/Img"+System.currentTimeMillis()+ ".png");
OutputStream os = null;
try {
os = new FileOutputStream(file);
os.write(data);
os.close();
scanFile(file.getAbsolutePath());
} catch (IOException e) {
Log.w(TAG, "Cannot write to " + file, e);
} finally {
if (os != null) {
try {
os.close();
} catch (IOException e) {
// Ignore
}
}
}
}
});
}
};
public static class ConfirmationDialogFragment extends DialogFragment {
private static final String ARG_MESSAGE = "message";
private static final String ARG_PERMISSIONS = "permissions";
private static final String ARG_REQUEST_CODE = "request_code";
private static final String ARG_NOT_GRANTED_MESSAGE = "not_granted_message";
public static ConfirmationDialogFragment newInstance(#StringRes int message,
String[] permissions, int requestCode, #StringRes int notGrantedMessage) {
ConfirmationDialogFragment fragment = new ConfirmationDialogFragment();
Bundle args = new Bundle();
args.putInt(ARG_MESSAGE, message);
args.putStringArray(ARG_PERMISSIONS, permissions);
args.putInt(ARG_REQUEST_CODE, requestCode);
args.putInt(ARG_NOT_GRANTED_MESSAGE, notGrantedMessage);
fragment.setArguments(args);
return fragment;
}
#NonNull
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final Bundle args = getArguments();
return new AlertDialog.Builder(getActivity())
.setMessage(args.getInt(ARG_MESSAGE))
.setPositiveButton(android.R.string.ok,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
String[] permissions = args.getStringArray(ARG_PERMISSIONS);
if (permissions == null) {
throw new IllegalArgumentException();
}
ActivityCompat.requestPermissions(getActivity(),
permissions, args.getInt(ARG_REQUEST_CODE));
}
})
.setNegativeButton(android.R.string.cancel,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getActivity(),
args.getInt(ARG_NOT_GRANTED_MESSAGE),
Toast.LENGTH_SHORT).show();
}
})
.create();
}
}
//Scans the saved file so it appears in the gallery
private void scanFile(String path) {
MediaScannerConnection.scanFile(this,
new String[] { path }, null,
new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
Log.i("TAG", "Finished scanning " + path);
}
});
}
/*
* open gallery for image preview
* */
private void openGallery(){
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Select Picture"), SELECT_PICTURE);
}
}
// Getting error :
E/CamActivity: mCameraViewjava.lang.NullPointerException: Attempt to invoke virtual method 'void android.hardware.camera2.CaptureRequest$Builder.set(android.hardware.camera2.CaptureRequest$Key, java.lang.Object)' on a null object reference
I have a problem. I want to use the method onNewIntent() in a fragment. I have fortunately received one really good answer ( Please have a look ). I tried to work with this code snipped, but unfortunately the NFC tag cannot be read. What is it that I am doing wrong?
I hope you can help me with this issue. I would be very thankful for every answer.
The new code was always inserted between the comment lines // NEW INTENT
UserFragmentGeldaufladen
public class UserFragmentGeldaufladen extends Fragment {
private Button btn_user_geldaufladen, btn_user_main_geldsendenAbort;
private EditText edittext_user_geldaufladen;
private Dialog epicDialog;
private NfcAdapter nfcAdapter;
private PendingIntent pendingIntent;
private boolean writeMode;
private IntentFilter writeTagFilters[];
private Context context;
private Tag myTag;
private interface RetrievalEventListener<T> {
abstract void onDataRetrieved(T t);
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_user_geldaufladen, container, false);
btn_user_geldaufladen = view.findViewById(R.id.btn_user_geldaufladen);
edittext_user_geldaufladen = view.findViewById(R.id.edittext_user_geldaufladen);
context = view.getContext();
epicDialog = new Dialog(view.getContext());
nfcAdapter = NfcAdapter.getDefaultAdapter(view.getContext());
if (nfcAdapter == null) {
// Stop here, we definitely need NFC
Toast.makeText(view.getContext(), "This device doesn't support NFC.", Toast.LENGTH_LONG).show();
}
// NEW INTENT
Intent i = new Intent(context, UserHomeActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
//i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // -> this will be require, if you will be update your fragment from BroadcastReceiver or Service
startActivity(i);
// NEW INTENT
readFromIntent( getActivity().getIntent());
pendingIntent = PendingIntent.getActivity(context, 0, new Intent(context, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
IntentFilter tagDetected = new IntentFilter(NfcAdapter.ACTION_TAG_DISCOVERED);
tagDetected.addCategory(Intent.CATEGORY_DEFAULT);
btn_user_geldaufladen.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
transaction();
}
});
return view;
}
// NEW INTENT
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//get first time intent
Intent intent = getActivity().getIntent();
((UserHomeActivity)getActivity()).setOnNewIntentListener(new OnNewIntentListener() {
#Override
public void newIntent(Intent intent) {
readFromIntent(intent);
if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(intent.getAction())) {
myTag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
}
}
});
}
// NEW INTENT
private void readFromIntent(Intent intent) {
String action = intent.getAction();
if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(action)
|| NfcAdapter.ACTION_TECH_DISCOVERED.equals(action)
|| NfcAdapter.ACTION_NDEF_DISCOVERED.equals(action)) {
Parcelable[] rawMsgs = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
NdefMessage[] msgs = null;
if (rawMsgs != null) {
msgs = new NdefMessage[rawMsgs.length];
for (int i = 0; i < rawMsgs.length; i++) {
msgs[i] = (NdefMessage) rawMsgs[i];
}
}
buildTagViews(msgs);
}
}
private void buildTagViews(NdefMessage[] msgs) {
if (msgs == null || msgs.length == 0) return;
String text = "";
// String tagId = new String(msgs[0].getRecords()[0].getType());
byte[] payload = msgs[0].getRecords()[0].getPayload();
String textEncoding = ((payload[0] & 128) == 0) ? "UTF-8" : "UTF-16"; // Get the Text Encoding
int languageCodeLength = payload[0] & 0063; // Get the Language Code, e.g. "en"
// String languageCode = new String(payload, 1, languageCodeLength, "US-ASCII");
try {
// Get the Text
text = new String(payload, languageCodeLength + 1, payload.length - languageCodeLength - 1, textEncoding);
} catch (UnsupportedEncodingException e) {
Log.e("UnsupportedEncoding", e.toString());
}
System.out.println(text);
}
/***
* Initiates the transaction
*/
private void transaction() {
String amount_geldaufladen = String.valueOf(edittext_user_geldaufladen.getText());
if(!amount_geldaufladen.isEmpty() && Integer.parseInt(amount_geldaufladen) > 0) {
showWaitingPopup();
}
}
/***
* Shows that the user should confirm the payment
*/
private void showWaitingPopup() {
epicDialog.setContentView(R.layout.user_main_popup_waiting);
epicDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
btn_user_main_geldsendenAbort = (Button) epicDialog.findViewById(R.id.btn_user_main_geldsendenAbort);
btn_user_main_geldsendenAbort.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
firebaseTransaction(new RetrievalEventListener<Integer>() {
#Override
public void onDataRetrieved(Integer integer) {
if(integer == 1) {
// do something
}
}
});
epicDialog.dismiss();
}
});
epicDialog.show();
}
/***
* Accesses the Firebase database and handles everything
*/
private void firebaseTransaction(final RetrievalEventListener<Integer> retrievalEventListener) {
// do Something
retrievalEventListener.onDataRetrieved(1);
}
/*
#Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
setIntent(intent);
readFromIntent(intent);
if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(intent.getAction())) {
myTag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
}
}
*/
#Override
public void onPause(){
super.onPause();
WriteModeOff();
}
#Override
public void onResume(){
super.onResume();
WriteModeOn();
}
/******************************************************************************
**********************************Enable Write********************************
******************************************************************************/
private void WriteModeOn(){
writeMode = true;
nfcAdapter.enableForegroundDispatch((Activity) context, pendingIntent, writeTagFilters, null);
}
/******************************************************************************
**********************************Disable Write*******************************
******************************************************************************/
private void WriteModeOff(){
writeMode = false;
nfcAdapter.disableForegroundDispatch((Activity) context);
}
}
UserHomeActivity
public class UserHomeActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener, UserOnFragmentBtnSelected {
Toolbar toolbar;
DrawerLayout drawer;
ActionBarDrawerToggle toggle;
NavigationView navigationView;
FragmentManager fragmentManager;
FragmentTransaction fragmentTransaction;
Fragment fragment;
String username;
// NEW INTENT
private OnNewIntentListener mOnNewIntentListener;
#Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
if (mOnNewIntentListener != null) {
mOnNewIntentListener.newIntent(intent);
}
}
public void setOnNewIntentListener(OnNewIntentListener onNewIntentListener) {
this.mOnNewIntentListener = onNewIntentListener;
}
// NEW INTENT
OnNewIntentListener
public interface OnNewIntentListener {
void newIntent(Intent intent);
}
I am a new android studio user. I am trying to build a BLE GATT service app. the app works fine for unpaired devices. However, the issue arises when I tried to scan for a device which is already paired. it does not show on the scan.
I am not using MainActivity, instead of that, I am using DeviceScanActivity as my Main. here's the snippet of that part:
public class DeviceScanActivity extends ListActivity {
private LeDeviceListAdapter mLeDeviceListAdapter;
private BluetoothAdapter mBluetoothAdapter;
private boolean mScanning;
private Handler mHandler;
private static final int REQUEST_ENABLE_BT = 1;
private static final long SCAN_PERIOD = 7500;
private static final int LOCATION_REQUEST = 255;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// getActionBar().setTitle(R.string.title_devices);
getActionBar().setDisplayShowTitleEnabled(false);
mHandler = new Handler();
if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
Toast.makeText(this, R.string.ble_not_supported, Toast.LENGTH_SHORT).show();
finish();
}
final BluetoothManager bluetoothManager =
(BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
mBluetoothAdapter = bluetoothManager.getAdapter();
if (mBluetoothAdapter == null) {
Toast.makeText(this, R.string.error_bluetooth_not_supported, Toast.LENGTH_SHORT).show();
finish();
return;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
if (!mScanning) {
menu.findItem(R.id.menu_stop).setVisible(false);
menu.findItem(R.id.menu_scan).setVisible(true);
menu.findItem(R.id.menu_refresh).setActionView(null);
} else {
menu.findItem(R.id.menu_stop).setVisible(true);
menu.findItem(R.id.menu_scan).setVisible(false);
menu.findItem(R.id.menu_refresh).setActionView(
R.layout.actionbar_indeterminate_progress);
}
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_scan:
mLeDeviceListAdapter.clear();
scanLeDevice(true);
break;
case R.id.menu_stop:
scanLeDevice(false);
break;
}
return true;
}
#Override
protected void onStart(){
super.onStart();
verifyPermissionAndScan();
if (!mBluetoothAdapter.isEnabled()){
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
mBluetoothAdapter.stopLeScan(mLeScanCallback);
} else {
mLeDeviceListAdapter = new LeDeviceListAdapter();
setListAdapter(mLeDeviceListAdapter);
}
}
#Override
protected void onResume() {
super.onResume();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_ENABLE_BT && resultCode == Activity.RESULT_CANCELED) {
finish();
return;
}
super.onActivityResult(requestCode, resultCode, data);
}
#Override
protected void onPause() {
super.onPause();
scanLeDevice(false);
mLeDeviceListAdapter.clear();
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
final BluetoothDevice device = mLeDeviceListAdapter.getDevice(position);
if (device == null) return;
final Intent intent = new Intent(this, DeviceControlActivity.class);
intent.putExtra(DeviceControlActivity.EXTRAS_DEVICE_NAME, device.getName());
intent.putExtra(DeviceControlActivity.EXTRAS_DEVICE_ADDRESS, device.getAddress());
if (mScanning) {
mBluetoothAdapter.stopLeScan(mLeScanCallback);
mScanning = false;
}
startActivity(intent);
}
private void scanLeDevice(final boolean enable) {
if (enable && !mScanning) {
mHandler.postDelayed(new Runnable() {
#Override
public void run() {
mScanning = false;
mBluetoothAdapter.stopLeScan(mLeScanCallback);
invalidateOptionsMenu();
}
}, SCAN_PERIOD);
mScanning = true;
mBluetoothAdapter.startLeScan(mLeScanCallback);
} else {
mScanning = false;
mBluetoothAdapter.stopLeScan(mLeScanCallback);
}
invalidateOptionsMenu();
}
private class LeDeviceListAdapter extends BaseAdapter {
private ArrayList<BluetoothDevice> mLeDevices;
private LayoutInflater mInflater;
private HashMap<BluetoothDevice, Integer> mDevicesRssi = new HashMap<>();
public LeDeviceListAdapter() {
super();
mLeDevices = new ArrayList<>();//i removed BluetoothDevice from the diamond bracket
mInflater = DeviceScanActivity.this.getLayoutInflater();
}
public void addDevice(BluetoothDevice device, int rssi) {
if (mDevicesRssi.containsKey(device)) {
int oldRssi = mDevicesRssi.get(device);
if (Math.abs(oldRssi - rssi) > 2) {
mDevicesRssi.put(device, rssi);
notifyDataSetChanged();
}
} else {
mDevicesRssi.put(device, rssi);
notifyDataSetChanged();
}
if(!mLeDevices.contains(device)) {
mLeDevices.add(device);
notifyDataSetChanged();
}
}
public BluetoothDevice getDevice(int position) {
return mLeDevices.get(position);
}
public void clear() {
mLeDevices.clear();
}
#Override
public int getCount() {
return mLeDevices.size();
}
#Override
public Object getItem(int i) {
return mLeDevices.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
ViewHolder viewHolder;
//
BluetoothDevice device = mLeDevices.get(i);
//
if (view == null) {
view = mInflater.inflate(R.layout.listitem_device, null);
viewHolder = new ViewHolder();
viewHolder.deviceAddress = (TextView) view.findViewById(R.id.device_address);
viewHolder.deviceName = (TextView) view.findViewById(R.id.device_name);
viewHolder.deviceRssi = (TextView) view.findViewById(R.id.device_rssi);
viewHolder.deviceBonded = (TextView) view.findViewById(R.id.device_bonded);
view.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) view.getTag();
}
final String deviceName = device.getName();
if (deviceName != null && deviceName.length() > 0)
viewHolder.deviceName.setText(deviceName);
else
viewHolder.deviceName.setText(R.string.unknown_device);
viewHolder.deviceAddress.setText(device.getAddress());
updateBondedState(device, viewHolder);
updateRssi(device, viewHolder);
return view;
}
private void updateBondedState(BluetoothDevice device, ViewHolder viewHolder) {
switch(device.getBondState()) {
case BOND_NONE:
viewHolder.deviceBonded.setVisibility(View.INVISIBLE);
break;
case BOND_BONDING:
viewHolder.deviceBonded.setText(R.string.bonding_state);
viewHolder.deviceBonded.setVisibility(View.VISIBLE);
break;
case BOND_BONDED:
viewHolder.deviceBonded.setText(R.string.bonded_state);
viewHolder.deviceBonded.setVisibility(View.VISIBLE);
break;
}
}
private void updateRssi(BluetoothDevice device, ViewHolder viewHolder) {
final int rssi = mDevicesRssi.get(device);
viewHolder.deviceRssi.setText(String.format("%s dBm", String.valueOf(rssi)));
}
}
private BluetoothAdapter.LeScanCallback mLeScanCallback =
new BluetoothAdapter.LeScanCallback() {
#Override
public void onLeScan(final BluetoothDevice device, final int rssi, byte[] scanRecord) {
runOnUiThread(new Runnable() {
#Override
public void run() {
mLeDeviceListAdapter.addDevice(device,rssi);
mLeDeviceListAdapter.notifyDataSetChanged();
}
});
}
};
static class ViewHolder {
TextView deviceName;
TextView deviceAddress;
TextView deviceRssi;
TextView deviceBonded;
}
#TargetApi(23)
private void verifyPermissionAndScan() {
if (ContextCompat.checkSelfPermission(this, ACCESS_COARSE_LOCATION) == PERMISSION_GRANTED) {
Toast.makeText(this, R.string.location_already_given, Toast.LENGTH_LONG);
} else {
requestPermissions(new String[] {ACCESS_COARSE_LOCATION}, LOCATION_REQUEST);
}
}
#Override
public void onRequestPermissionsResult (int requestCode, String[] permissions, int[] grantResults) {
if (requestCode != LOCATION_REQUEST) return;
if (grantResults.length > 0 && grantResults[0] == PERMISSION_GRANTED) {
Toast.makeText(this, R.string.permission_allowed, Toast.LENGTH_LONG).show();
} else {
Toast.makeText(this, R.string.permission_not_allowed, Toast.LENGTH_LONG).show();
}
}
}
This is my DeviceControlActiviy class file:
public class DeviceControlActivity extends Activity {
private final static String TAG = DeviceControlActivity.class.getSimpleName();
public static final String EXTRAS_DEVICE_NAME = "DEVICE_NAME";
public static final String EXTRAS_DEVICE_ADDRESS = "DEVICE_ADDRESS";
private TextView mConnectionState;
private TextView mDataField;
private String mDeviceName;
private String mDeviceAddress;
private ExpandableListView mGattServicesList;
private BluetoothLeService mBluetoothLeService;
private ArrayList<ArrayList<BluetoothGattCharacteristic>> mGattCharacteristics =
new ArrayList<ArrayList<BluetoothGattCharacteristic>>();
private boolean mConnected = false;
private BluetoothGattCharacteristic mNotifyCharacteristic;
private final String LIST_NAME = "NAME";
private final String LIST_UUID = "UUID";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.gatt_services_characteristics);
final Intent intent = getIntent();
mDeviceName = intent.getStringExtra(EXTRAS_DEVICE_NAME);
mDeviceAddress = intent.getStringExtra(EXTRAS_DEVICE_ADDRESS);
((TextView) findViewById(R.id.device_address)).setText(mDeviceAddress);
mGattServicesList = (ExpandableListView) findViewById(R.id.gatt_services_list);
mGattServicesList.setOnChildClickListener(servicesListClickListner);
mConnectionState = (TextView) findViewById(R.id.connection_state);
mDataField = (TextView) findViewById(R.id.data_value);
// getActionBar().setTitle(mDeviceName);
getActionBar().setDisplayShowTitleEnabled(false);
getActionBar().setDisplayHomeAsUpEnabled(true);
final Intent gattServiceIntent = new Intent(this, BluetoothLeService.class);
bindService(gattServiceIntent, mServiceConnection, BIND_AUTO_CREATE);
}
private final ServiceConnection mServiceConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName componentName, IBinder service) {
mBluetoothLeService = ((BluetoothLeService.LocalBinder) service).getService();
if (!mBluetoothLeService.initialize()) {
Log.e(TAG, "Unable to initialize Bluetooth");
finish();
}
// mBluetoothLeService.connect(mDeviceAddress);
}
#Override
public void onServiceDisconnected(ComponentName componentName) {
mBluetoothLeService = null;
}
};
private final BroadcastReceiver mGattUpdateReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if (BluetoothLeService.ACTION_GATT_CONNECTED.equals(action)) {
mConnected = true;
updateConnectionState(R.string.connected);
invalidateOptionsMenu();
} else if (BluetoothLeService.ACTION_GATT_DISCONNECTED.equals(action)) {
mConnected = false;
updateConnectionState(R.string.disconnected);
invalidateOptionsMenu();
clearUI();
} else if (BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED.equals(action)) {
displayGattServices(mBluetoothLeService.getSupportedGattServices());
} else if (BluetoothLeService.ACTION_DATA_AVAILABLE.equals(action)) {
displayData(intent.getStringExtra(BluetoothLeService.EXTRA_DATA));
}
}
};
private final ExpandableListView.OnChildClickListener servicesListClickListner =
new ExpandableListView.OnChildClickListener() {
#Override
public boolean onChildClick(ExpandableListView parent, View v, int groupPosition,
int childPosition, long id) {
if (mGattCharacteristics != null) {
final BluetoothGattCharacteristic characteristic =
mGattCharacteristics.get(groupPosition).get(childPosition);
final int charaProp = characteristic.getProperties();
if ((charaProp | BluetoothGattCharacteristic.PROPERTY_READ) > 0) {
if (mNotifyCharacteristic != null) {
mBluetoothLeService.setCharacteristicNotification(
mNotifyCharacteristic, false);
mNotifyCharacteristic = null;
}
mBluetoothLeService.readCharacteristic(characteristic);
}
if ((charaProp | BluetoothGattCharacteristic.PROPERTY_NOTIFY) > 0) {
mNotifyCharacteristic = characteristic;
mBluetoothLeService.setCharacteristicNotification(
characteristic, true);
}
return true;
}
return false;
}
};
private void clearUI() {
mGattServicesList.setAdapter((SimpleExpandableListAdapter) null);
mDataField.setText(R.string.no_data);
}
#Override
protected void onResume() {
super.onResume();
registerReceiver(mGattUpdateReceiver, makeGattUpdateIntentFilter());
if (mBluetoothLeService != null) {
final boolean result = mBluetoothLeService.connect(mDeviceAddress);
Log.d(TAG, "Connect request result=" + result);
}
}
#Override
protected void onPause() {
super.onPause();
unregisterReceiver(mGattUpdateReceiver);
}
#Override
protected void onDestroy() {
super.onDestroy();
unbindService(mServiceConnection);
mBluetoothLeService = null;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.gatt_services, menu);
if (mConnected) {
menu.findItem(R.id.menu_connect).setVisible(false);
menu.findItem(R.id.menu_disconnect).setVisible(true);
} else {
menu.findItem(R.id.menu_connect).setVisible(true);
menu.findItem(R.id.menu_disconnect).setVisible(false);
}
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()) {
case R.id.menu_connect:
mBluetoothLeService.connect(mDeviceAddress);
return true;
case R.id.menu_disconnect:
mBluetoothLeService.disconnect();
return true;
case android.R.id.home:
onBackPressed();
return true;
}
return super.onOptionsItemSelected(item);
}
private void updateConnectionState(final int resourceId) {
runOnUiThread(new Runnable() {
#Override
public void run() {
mConnectionState.setText(resourceId);
}
});
}
private void displayData(String data) {
if (data != null) {
mDataField.setText(data);
}
}
private void displayGattServices(List<BluetoothGattService> gattServices) {
if (gattServices == null) return;
String uuid = null;
String unknownServiceString = getResources().getString(R.string.unknown_service);
String unknownCharaString = getResources().getString(R.string.unknown_characteristic);
ArrayList<HashMap<String, String>> gattServiceData = new ArrayList<HashMap<String, String>>();
ArrayList<ArrayList<HashMap<String, String>>> gattCharacteristicData
= new ArrayList<ArrayList<HashMap<String, String>>>();
mGattCharacteristics = new ArrayList<ArrayList<BluetoothGattCharacteristic>>();
for (BluetoothGattService gattService : gattServices) {
HashMap<String, String> currentServiceData = new HashMap<String, String>();
uuid = gattService.getUuid().toString();
currentServiceData.put(
LIST_NAME, SampleGattAttributes.lookup(uuid, unknownServiceString));
currentServiceData.put(LIST_UUID, uuid);
gattServiceData.add(currentServiceData);
ArrayList<HashMap<String, String>> gattCharacteristicGroupData =
new ArrayList<HashMap<String, String>>();
List<BluetoothGattCharacteristic> gattCharacteristics =
gattService.getCharacteristics();
ArrayList<BluetoothGattCharacteristic> charas =
new ArrayList<BluetoothGattCharacteristic>();
for (BluetoothGattCharacteristic gattCharacteristic : gattCharacteristics) {
charas.add(gattCharacteristic);
HashMap<String, String> currentCharaData = new HashMap<String, String>();
uuid = gattCharacteristic.getUuid().toString();
currentCharaData.put(
LIST_NAME, SampleGattAttributes.lookup(uuid, unknownCharaString));
currentCharaData.put(LIST_UUID, uuid);
gattCharacteristicGroupData.add(currentCharaData);
}
mGattCharacteristics.add(charas);
gattCharacteristicData.add(gattCharacteristicGroupData);
}
SimpleExpandableListAdapter gattServiceAdapter = new SimpleExpandableListAdapter(
this,
gattServiceData,
android.R.layout.simple_expandable_list_item_2,
new String[] {LIST_NAME, LIST_UUID},
new int[] { android.R.id.text1, android.R.id.text2 },
gattCharacteristicData,
android.R.layout.simple_expandable_list_item_2,
new String[] {LIST_NAME, LIST_UUID},
new int[] { android.R.id.text1, android.R.id.text2 }
);
mGattServicesList.setAdapter(gattServiceAdapter);
}
private static IntentFilter makeGattUpdateIntentFilter() {
final IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(BluetoothLeService.ACTION_GATT_CONNECTED);
intentFilter.addAction(BluetoothLeService.ACTION_GATT_DISCONNECTED);
intentFilter.addAction(BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED);
intentFilter.addAction(BluetoothLeService.ACTION_DATA_AVAILABLE);
return intentFilter;
}
}
I get the device name, address and RSSI for unpaired devices perfectly. but if the device is already paired it does not show on the device list, also if I click on a device on the unpaired device list, it does not automatically pair the device with the phone. I need to do it manually from the phone's BT setting.
This displays all the devices the phone was paired with (even if it is not paired with currently)
JAVA
for(BluetoothDevice device : BluetoothAdapter.getDefaultAdapter().getBondedDevices()){
device.getName(); // name
device.getAddress();// Address
}
KOTLIN
for (device in BluetoothAdapter.getDefaultAdapter().bondedDevices) {
device.name // name
device.address// Address
}
Hope this helps!
Im having problem with permissions for reading storage in my phone. I have to list all audio files in my phone so I have tried to ask for permisiion with "activitycompact.requestPermissions" The only problem is, that when application is installed and firstly opened it says "MusicPlayer has stopped" and after that dialog it open request for Permissions, so I allow it and then I had to reopen this file. I dont know how to ask for those permissions before it crashes.
Main Activity
public class MainActivity extends ListActivity {
private static final int UPDATE_FREQUENCY = 500;
private static final int STEP_VALUE = 4000;
private MediaCursorAdapter mediaAdapter = null;
private TextView selectedFile= null;
private SeekBar seekbar = null;
private MediaPlayer player = null;
private ImageButton playButton = null;
private ImageButton previousButton = null;
private ImageButton nextButton = null;
private boolean isStarted = true;
private String currentFile = "";
private boolean isMovingseekBar = false;
private final Handler handler = new Handler();
private final Runnable updatePositionRunnable = new Runnable() {
public void run() {
updatePosition();
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{android.Manifest.permission.READ_EXTERNAL_STORAGE},
1);
selectedFile = (TextView) findViewById(R.id.selectedfile);
seekbar = (SeekBar) findViewById(R.id.seekbar);
playButton = (ImageButton) findViewById(R.id.play);
previousButton = (ImageButton) findViewById(R.id.previous);
nextButton = (ImageButton) findViewById(R.id.next);
player = new MediaPlayer();
player.setOnCompletionListener(onCompletion);
player.setOnErrorListener(onError);
seekbar.setOnSeekBarChangeListener(seekBarChanged);
Cursor cursor = getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null, null, null, null);
if (null != cursor) {
cursor.moveToFirst();
mediaAdapter = new MediaCursorAdapter(this, R.layout.listitem, cursor);
setListAdapter(mediaAdapter);
playButton.setOnClickListener(onButtonClick);
nextButton.setOnClickListener(onButtonClick);
previousButton.setOnClickListener(onButtonClick);
}
}
#Override
protected void onListItemClick(ListView list, View view, int position,long id) {
super.onListItemClick(list, view, position, id);
currentFile = (String) view.getTag();
startPlay(currentFile);
}
#Override
protected void onDestroy(){
super.onDestroy();
handler.removeCallbacks(updatePositionRunnable);
player.stop();
player.reset();
player.release();
player = null;
}
private void startPlay(String file) {
selectedFile.setText(file);
seekbar.setProgress(0);
player.stop();
player.reset();
try {
player.setDataSource(file);
player.prepare();
player.start();
} catch (IllegalArgumentException e){
e.printStackTrace();
} catch (IllegalStateException e){
e.printStackTrace();
} catch (IOException e){
e.printStackTrace();
}
seekbar.setMax(player.getDuration());
playButton.setImageResource(android.R.drawable.ic_media_pause);
updatePosition();
isStarted = true;
}
private void stopPlay() {
player.stop();
player.reset();
playButton.setImageResource(android.R.drawable.ic_media_play);
handler.removeCallbacks(updatePositionRunnable);
seekbar.setProgress(0);
isStarted = false;
}
private void updatePosition() {
handler.removeCallbacks(updatePositionRunnable);
handler.postDelayed(updatePositionRunnable, UPDATE_FREQUENCY);
}
private class MediaCursorAdapter extends SimpleCursorAdapter{
MediaCursorAdapter(Context context, int layout, Cursor c){
super(context, layout,c,
new String[] {MediaStore.MediaColumns.DISPLAY_NAME, MediaStore.MediaColumns.TITLE, MediaStore.Audio.AudioColumns.DURATION},
new int[] {R.id.displayname, R.id.title,R.id.duration});
}
#Override
public void bindView(View view,Context context, Cursor cursor) {
TextView title = (TextView) view.findViewById(R.id.title);
TextView name = (TextView) view.findViewById(R.id.displayname);
TextView duration = (TextView) view.findViewById(R.id.duration);
name.setText(cursor.getString(
cursor.getColumnIndex(MediaStore.MediaColumns.DISPLAY_NAME)));
title.setText(cursor.getString(
cursor.getColumnIndex(MediaStore.MediaColumns.TITLE)));
view.setTag(cursor.getString(cursor.getColumnIndex(MediaStore.MediaColumns.DATA)));
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
LayoutInflater inflater = LayoutInflater.from(context);
View v = inflater.inflate(R.layout.listitem, parent, false);
bindView(v, context, cursor);
return v;
}
}
private View.OnClickListener onButtonClick = new View.OnClickListener() {
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.play: {
if (player.isPlaying()) {
handler.removeCallbacks(updatePositionRunnable);
player.pause();
playButton.setImageResource(android.R.drawable.ic_media_play);
} else {
if (isStarted) {
player.start();
playButton.setImageResource(android.R.drawable.ic_media_pause);
updatePosition();
} else {
startPlay(currentFile);
}
}
break;
}
case R.id.next: {
int seekto = player.getCurrentPosition() + STEP_VALUE;
if (seekto < player.getDuration())
seekto = player.getDuration();
player.pause();
player.seekTo(seekto);
player.start();
break;
}
case R.id.previous: {
int seekto = player.getCurrentPosition() - STEP_VALUE;
if (seekto < player.getDuration())
seekto = player.getDuration();
player.pause();
player.seekTo(seekto);
player.start();
break;
}
}
}
};
private MediaPlayer.OnCompletionListener onCompletion = new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
stopPlay();
}
};
private MediaPlayer.OnErrorListener onError = new MediaPlayer.OnErrorListener() {
#Override
public boolean onError(MediaPlayer mp, int what, int extra) {
return false;
}
};
private SeekBar.OnSeekBarChangeListener seekBarChanged = new SeekBar.OnSeekBarChangeListener() {
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
isMovingseekBar = false;
}
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fomUser) {
if (isMovingseekBar) {
player.seekTo(progress);
Log.i("OnSeekBarChangeListener", "onProgressChange");
}
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
isMovingseekBar = true;
}
};
1) Please make sure you have added the permission in Manifest.XML
2) I can not see anything like you are handling the requested permission result.
Remove below from your onCreate
Cursor cursor = getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null, null, null, null);
if (null != cursor) {
cursor.moveToFirst();
mediaAdapter = new MediaCursorAdapter(this, R.layout.listitem, cursor);
setListAdapter(mediaAdapter);
}
and keep in side of
#Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
if(requestCode ==YOUR_REQ_CODE) {
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//Do your stuff here.
}
}
Try this,
Add this in onCreate()
if( checkIfAlreadyhavePermission(activity, Manifest.permission.READ_EXTERNAL_STORAGE) ){
// Add the code here the code you need to work after accepting permission
player = new MediaPlayer();
player.setOnCompletionListener(onCompletion);
player.setOnErrorListener(onError);
seekbar.setOnSeekBarChangeListener(seekBarChanged);
Cursor cursor = getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null, null, null, null);
if (null != cursor) {
cursor.moveToFirst();
mediaAdapter = new MediaCursorAdapter(this, R.layout.listitem, cursor);
setListAdapter(mediaAdapter);
}
}else {
requestForSpecificPermission(
activity, Manifest.permission.READ_EXTERNAL_STORAGE);
}
And add this to MainActivity
public boolean checkIfAlreadyhavePermission(Activity activity, String permission) {
int result = ContextCompat.checkSelfPermission(activity, permission);
if (result == PackageManager.PERMISSION_GRANTED) {
return true;
} else {
return false;
}
}
public void requestForSpecificPermission(Activity activity, String granted_permission) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
ActivityCompat.requestPermissions(activity, new String[]{granted_permission}, 101);
}
}
Please note if you have only permission issue it will work. Please share your logcat
when ask permission use below code ..
if (ActivityCompat.checkSelfPermission(EdittextActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(EdittextActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE)) {
WriteBtn(view); // hear define your code after getting permission.
}
else {
ActivityCompat.requestPermissions(EdittextActivity.this,new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 1);
}
}
also when you allow permission and call your particular method that time used below code ..
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode==1){
display(); // call your method that required permission.
}
}
May this help you :
--------------------------------
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
Add this line in manifest
if any error then
<permission
android:name="android.permission.READ_EXTERNAL_STORAGE"
android:protectionLevel="signature" />
- Optional
------------------------------
public class PermissionUtils
{
Context context;
Activity current_activity;
PermissionResultCallback permissionResultCallback;
ArrayList<String> permission_list=new ArrayList<>();
ArrayList<String> listPermissionsNeeded=new ArrayList<>();
String dialog_content="";
int req_code;
public PermissionUtils(Context context)
{
this.context=context;
this.current_activity= (Activity) context;
permissionResultCallback= (PermissionResultCallback) context;
}
/**
* Check the API Level & Permission
*
* #param permissions
* #param dialog_content
* #param request_code
*/
public void check_permission(ArrayList<String> permissions, String dialog_content, int request_code)
{
this.permission_list=permissions;
this.dialog_content=dialog_content;
this.req_code=request_code;
if(Build.VERSION.SDK_INT >= 23)
{
if (checkAndRequestPermissions(permissions, request_code))
{
permissionResultCallback.PermissionGranted(request_code);
Log.i("all permissions", "granted");
Log.i("proceed", "to callback");
}
}
else
{
permissionResultCallback.PermissionGranted(request_code);
Log.i("all permissions", "granted");
Log.i("proceed", "to callback");
}
}
/**
* Check and request the Permissions
*
* #param permissions
* #param request_code
* #return
*/
private boolean checkAndRequestPermissions(ArrayList<String> permissions, int request_code) {
if(permissions.size()>0)
{
listPermissionsNeeded = new ArrayList<>();
for(int i=0;i<permissions.size();i++)
{
int hasPermission = ContextCompat.checkSelfPermission(current_activity,permissions.get(i));
if (hasPermission != PackageManager.PERMISSION_GRANTED) {
listPermissionsNeeded.add(permissions.get(i));
}
}
if (!listPermissionsNeeded.isEmpty())
{
ActivityCompat.requestPermissions(current_activity, listPermissionsNeeded.toArray(new String[listPermissionsNeeded.size()]),request_code);
return false;
}
}
return true;
}
/**
*
*
* #param requestCode
* #param permissions
* #param grantResults
*/
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults)
{
switch (requestCode)
{
case 1:
if(grantResults.length>0)
{
Map<String, Integer> perms = new HashMap<>();
for (int i = 0; i < permissions.length; i++)
{
perms.put(permissions[i], grantResults[i]);
}
final ArrayList<String> pending_permissions=new ArrayList<>();
for (int i = 0; i < listPermissionsNeeded.size(); i++)
{
if (perms.get(listPermissionsNeeded.get(i)) != PackageManager.PERMISSION_GRANTED)
{
if(ActivityCompat.shouldShowRequestPermissionRationale(current_activity,listPermissionsNeeded.get(i)))
pending_permissions.add(listPermissionsNeeded.get(i));
else
{
Log.i("Go to settings","and enable permissions");
permissionResultCallback.NeverAskAgain(req_code);
// Toast.makeText(current_activity, "Go to settings and enable permissions", Toast.LENGTH_LONG).show();
return;
}
}
}
if(pending_permissions.size()>0)
{
showMessageOKCancel(dialog_content,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case DialogInterface.BUTTON_POSITIVE:
check_permission(permission_list,dialog_content,req_code);
break;
case DialogInterface.BUTTON_NEGATIVE:
Log.i("permisson","not fully given");
if(permission_list.size()==pending_permissions.size())
permissionResultCallback.PermissionDenied(req_code);
else
permissionResultCallback.PartialPermissionGranted(req_code,pending_permissions);
break;
}
}
});
}
else
{
Log.i("all","permissions granted");
Log.i("proceed","to next step");
permissionResultCallback.PermissionGranted(req_code);
}
}
break;
}
}
/**
* Explain why the app needs permissions
*
* #param message
* #param okListener
*/
private void showMessageOKCancel(String message, DialogInterface.OnClickListener okListener) {
new AlertDialog.Builder(current_activity)
.setMessage(message)
.setPositiveButton("Ok", okListener)
.setNegativeButton("Cancel", okListener)
.create()
.show();
}
}
=============================
// You can add any permission here
ArrayList<String> permissions = new ArrayList<>();
PermissionUtils permissionUtils;
permissionUtils = new PermissionUtils(context);
permissions.add(Manifest.permission.READ_EXTERNAL_STORAGE);
//i.e permissions.add(Manifest.permission.READ_EXTERNAL_STORAGE);
permissionUtils.check_permission(permissions,getResources()
.getString(R.string.explain_here_why_the_app_needs_permissions), 1);
=============================
Activty that implements PermissionResultCallback
===================
Make interface
public interface PermissionResultCallback
{
void PermissionGranted(int request_code);
void PartialPermissionGranted(int request_code, ArrayList<String>
granted_permissions);
void PermissionDenied(int request_code);
void NeverAskAgain(int request_code);
}
-----------------------------
This is my full code below. am coding an android app that can select image from gallery or any where and upload it to Mysql server through php but if image is not selected and the upload button is press the application crashes so i want to implement the function that it shows error dialog / warning dialog if image is not selected from gallery have already implemented it in EditText but cannot implement it in Image. below is my code
package com.app.markeet;
public class ActivityPost extends AppCompatActivity implements View.OnClickListener {
private Button buttonUpload;
private Button buttonChoose;
EditText editTitle, editTextPrice, editTextDescription, editTextStatus, editTextAuthorsname, editTextAuthorsphone;
private ImageView imageView,choiceItemImg,choiceItemImg2,choiceItemImg3,choiceItemImg4;
public static final String KEY_TITLE = "name";
public static final String KEY_IMAGE = "image";
public static final String KEY_PRICE = "price";
public static final String KEY_DESCRIPTION = "description";
public static final String KEY_STOCK = "stock";
public static final String KEY_AUTHORSNAME = "authorsname";
public static final String KEY_AUTHORSPHONE = "authorsphone";
public static final String KEY_STATUS = "status";
public static final String UPLOAD_URL = "http://192.168.0.199/config/upload.php";
private int PICK_IMAGE_REQUEST = 1;
public static final int CREATE_POST_IMG = 5;
private Bitmap bitmap;
private Uri outputFileUri;
public static final int SELECT_POST_IMG = 3;
public static final String APP_TEMP_FOLDER = "kobobay";
String[] categories = { "Animals and Pets", "Electronics and Video",
"Fashion and Beauty", "Home, Furniture and Garden", "Mobile Phone and Tablets", "PC, Laptop and Accessories",
"Jobs and Services", "Real Estate and Roommate", "Hobbles, Art and Sport", "Books and Tutorial",
"Vehicles", "Other"};
int[] catevalue = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12};
Spinner spinner1;
TextView textView1;
private Toolbar toolbar;
private ActionBar actionBar;
private String selectedPostImg = "";
ImageView mChoiceItemImg, mLocationDelete;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_post);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeButtonEnabled(true);
actionBar.setTitle("");
buttonUpload = (Button) findViewById(R.id.buttonUpload);
buttonChoose = (Button) findViewById(R.id.buttonChooseImage);
editTitle = (EditText)findViewById(R.id.editTitle);
editTextPrice = (EditText)findViewById(R.id.editPrice);
editTextDescription = (EditText)findViewById(R.id.editDescription);
editTextStatus = (EditText)findViewById(R.id.editStatus);
editTextAuthorsname = (EditText)findViewById(R.id.editName);
editTextAuthorsphone = (EditText)findViewById(R.id.editPhone);
imageView = (ImageView) findViewById(R.id.imageView);
textView1 = (TextView)findViewById(R.id.text1);
spinner1 = (Spinner)findViewById(R.id.spinner1);
ArrayAdapter<String> adapter1 =
new ArrayAdapter<String>(ActivityPost.this,
android.R.layout.simple_spinner_item, categories);
adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner1.setAdapter(adapter1);
spinner1.setOnItemSelectedListener(onItemSelectedListener1);
buttonChoose.setOnClickListener(this);
buttonUpload.setOnClickListener(this);
choiceItemImg = (ImageView) findViewById(R.id.choiceItemImg);
choiceItemImg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showFileChooser();
}
});
mChoiceItemImg = (ImageView) findViewById(R.id.choiceItemImg2);
mChoiceItemImg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (selectedPostImg.length() == 0) {
imageFromGallery();
} else {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(ActivityPost.this);
alertDialog.setTitle(getText(R.string.action_remove));
alertDialog.setMessage(getText(R.string.label_delete_img));
alertDialog.setCancelable(true);
alertDialog.setNeutralButton(getText(R.string.action_cancel), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alertDialog.setPositiveButton(getText(R.string.action_remove), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
mChoiceItemImg.setImageResource(R.drawable.ic_camera);
selectedPostImg = "";
dialog.cancel();
}
});
alertDialog.show();
}
}
});
String URL = Constant.WEB_URL + "get/user_info.php";
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonResponse= new JSONObject(response);
//txtName.setText(jsonResponse.getString("fullname"));
editTextAuthorsname.setText(jsonResponse.getString("login"));
//txtEmail.setText(jsonResponse.getString("email"));
editTextAuthorsphone.setText(jsonResponse.getString("phone"));// you need to create this textView txtPoints.
} catch (Throwable t) {
Log.e("onResponse", "The response: " + response + " seems to not be json formatted.");
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(ActivityPost.this,error.toString(), Toast.LENGTH_SHORT).show();
}
}){
#Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<String, String>();
params.put("username",ThisApplication.getInstance().getUsername());
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
AdapterView.OnItemSelectedListener onItemSelectedListener1 =
new AdapterView.OnItemSelectedListener(){
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
String s1 = String.valueOf(catevalue[position]);
textView1.setText(s1);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {}
};
private void showFileChooser() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
}
public void imageFromGallery() {
Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(Intent.createChooser(intent, getText(R.string.label_select_img)), SELECT_POST_IMG);
}
public void imageFromCamera() {
try {
File root = new File(Environment.getExternalStorageDirectory(), APP_TEMP_FOLDER);
if (!root.exists()) {
root.mkdirs();
}
File sdImageMainDirectory = new File(root, "post.jpg");
outputFileUri = Uri.fromFile(sdImageMainDirectory);
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
startActivityForResult(cameraIntent, CREATE_POST_IMG);
} catch (Exception e) {
Toast.makeText(ActivityPost.this, "Error occured. Please try again later.", Toast.LENGTH_SHORT).show();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
Uri filePath = data.getData();
try {
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
choiceItemImg.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
if (requestCode == SELECT_POST_IMG && resultCode == RESULT_OK && data != null && data.getData() != null) {
Uri filePath = data.getData();
try {
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
choiceItemImg2.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
public String getStringImage(Bitmap bmp){
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] imageBytes = baos.toByteArray();
String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
return encodedImage;
}
public void uploadImage(){
final String GetAuthorsname = editTextAuthorsname.getText().toString();
final String GetAuthorsphone = editTextAuthorsphone.getText().toString();
final String GetTitle = editTitle.getText().toString().trim();
final String image = getStringImage(bitmap);
final String GetPrice = editTextPrice.getText().toString();
final String GetStock = textView1.getText().toString();
final String GetDescription = editTextDescription.getText().toString();
final String GetStatus = editTextStatus.getText().toString();
class UploadImage extends AsyncTask<Void,Void,String> {
ProgressDialog loading;
#Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(ActivityPost.this,"Please wait...","uploading",false,false);
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
Toast.makeText(ActivityPost.this,s, Toast.LENGTH_LONG).show();
}
#Override
protected String doInBackground(Void... params) {
RequestHandler rh = new RequestHandler();
HashMap<String,String> param = new HashMap<String,String>();
param.put(KEY_TITLE,GetTitle);
param.put(KEY_IMAGE,image);
param.put(KEY_PRICE,GetPrice);
param.put(KEY_STOCK,GetStock);
param.put(KEY_DESCRIPTION,GetDescription);
param.put(KEY_STATUS,GetStatus);
param.put(KEY_AUTHORSNAME,GetAuthorsname);
param.put(KEY_AUTHORSPHONE,GetAuthorsphone);
String result = rh.sendPostRequest(UPLOAD_URL, param);
return result;
}
}
UploadImage u = new UploadImage();
u.execute();
}
public Boolean checkPicture() {
String image = getStringImage(bitmap);
String GetPrice = editTextPrice.getText().toString();
String GetDescription = editTextDescription.getText().toString();
String GetStatus = editTextStatus.getText().toString();
editTitle.setError(null);
editTextPrice.setError(null);
editTextDescription.setError(null);
editTextStatus.setError(null);
if (image.length() == 0) {
editTitle.setError(getString(R.string.error_field_empty));
return false;
} if (GetPrice.length() == 0) {
editTextPrice.setError(getString(R.string.error_field_empty));
return false;
} if (GetDescription.length() == 0) {
editTextDescription.setError(getString(R.string.error_field_empty));
return false;
} if (GetStatus.length() == 0) {
editTextStatus.setError(getString(R.string.error_field_empty));
return false;
}
return true;
}
public Boolean checkDesc() {
String GetDescription = editTextDescription.getText().toString();
editTextDescription.setError(null);
if (GetDescription.length() == 0) {
editTextDescription.setError(getString(R.string.error_field_empty));
return false;
}
return true;
}
public Boolean checkProductName() {
String GetTitle = editTitle.getText().toString();
editTitle.setError(null);
if (GetTitle.length() == 0) {
editTitle.setError(getString(R.string.error_field_empty));
return false;
}
return true;
}
public Boolean checkCategory() {
String GetStock = textView1.getText().toString();
textView1.setError(null);
if (GetStock.length() == 0) {
editTitle.setError(getString(R.string.error_field_empty));
return false;
}
return true;
}
#Override
public void onClick(View v) {
if(v == buttonChoose){
showFileChooser();
//imageFromGallery();
}
if(v == buttonUpload){
// checkUsername();
if (!ThisApplication.getInstance().isConnected()) {
Toast.makeText(getApplicationContext(), R.string.msg_network_error, Toast.LENGTH_SHORT).show();
} else if (!checkProductName() || !checkDesc() || !checkCategory()) {
} else {
uploadImage();
}
}
}
#Override
public void onBackPressed(){
finish();
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_new_item, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.sync:
Intent intent = getIntent();
finish();
startActivity(intent);
return true;
case R.id.action_post:
uploadImage();
default:
return super.onOptionsItemSelected(item);
}
}
}
Just copy this code and paste
package com.app.markeet;
public class ActivityPost extends AppCompatActivity implements View.OnClickListener {
private Button buttonUpload;
private Button buttonChoose;
EditText editTitle, editTextPrice, editTextDescription, editTextStatus, editTextAuthorsname, editTextAuthorsphone;
private ImageView imageView,choiceItemImg,choiceItemImg2,choiceItemImg3,choiceItemImg4;
public static final String KEY_TITLE = "name";
public static final String KEY_IMAGE = "image";
public static final String KEY_PRICE = "price";
public static final String KEY_DESCRIPTION = "description";
public static final String KEY_STOCK = "stock";
public static final String KEY_AUTHORSNAME = "authorsname";
public static final String KEY_AUTHORSPHONE = "authorsphone";
public static final String KEY_STATUS = "status";
public static final String UPLOAD_URL = "http://192.168.0.199/config/upload.php";
private int PICK_IMAGE_REQUEST = 1;
public static final int CREATE_POST_IMG = 5;
private Bitmap bitmap;
private Uri outputFileUri;
public static final int SELECT_POST_IMG = 3;
public static final String APP_TEMP_FOLDER = "kobobay";
String[] categories = { "Animals and Pets", "Electronics and Video",
"Fashion and Beauty", "Home, Furniture and Garden", "Mobile Phone and Tablets", "PC, Laptop and Accessories",
"Jobs and Services", "Real Estate and Roommate", "Hobbles, Art and Sport", "Books and Tutorial",
"Vehicles", "Other"};
int[] catevalue = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12};
Spinner spinner1;
TextView textView1;
private Toolbar toolbar;
private ActionBar actionBar;
private String selectedPostImg = "";
ImageView mChoiceItemImg, mLocationDelete;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_post);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeButtonEnabled(true);
actionBar.setTitle("");
buttonUpload = (Button) findViewById(R.id.buttonUpload);
buttonChoose = (Button) findViewById(R.id.buttonChooseImage);
editTitle = (EditText)findViewById(R.id.editTitle);
editTextPrice = (EditText)findViewById(R.id.editPrice);
editTextDescription = (EditText)findViewById(R.id.editDescription);
editTextStatus = (EditText)findViewById(R.id.editStatus);
editTextAuthorsname = (EditText)findViewById(R.id.editName);
editTextAuthorsphone = (EditText)findViewById(R.id.editPhone);
imageView = (ImageView) findViewById(R.id.imageView);
textView1 = (TextView)findViewById(R.id.text1);
spinner1 = (Spinner)findViewById(R.id.spinner1);
ArrayAdapter<String> adapter1 =
new ArrayAdapter<String>(ActivityPost.this,
android.R.layout.simple_spinner_item, categories);
adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner1.setAdapter(adapter1);
spinner1.setOnItemSelectedListener(onItemSelectedListener1);
buttonChoose.setOnClickListener(this);
buttonUpload.setOnClickListener(this);
choiceItemImg = (ImageView) findViewById(R.id.choiceItemImg);
choiceItemImg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showFileChooser();
}
});
mChoiceItemImg = (ImageView) findViewById(R.id.choiceItemImg2);
mChoiceItemImg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (selectedPostImg.length() == 0) {
imageFromGallery();
} else {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(ActivityPost.this);
alertDialog.setTitle(getText(R.string.action_remove));
alertDialog.setMessage(getText(R.string.label_delete_img));
alertDialog.setCancelable(true);
alertDialog.setNeutralButton(getText(R.string.action_cancel), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alertDialog.setPositiveButton(getText(R.string.action_remove), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
mChoiceItemImg.setImageResource(R.drawable.ic_camera);
selectedPostImg = "";
dialog.cancel();
}
});
alertDialog.show();
}
}
});
String URL = Constant.WEB_URL + "get/user_info.php";
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonResponse= new JSONObject(response);
//txtName.setText(jsonResponse.getString("fullname"));
editTextAuthorsname.setText(jsonResponse.getString("login"));
//txtEmail.setText(jsonResponse.getString("email"));
editTextAuthorsphone.setText(jsonResponse.getString("phone"));// you need to create this textView txtPoints.
} catch (Throwable t) {
Log.e("onResponse", "The response: " + response + " seems to not be json formatted.");
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(ActivityPost.this,error.toString(), Toast.LENGTH_SHORT).show();
}
}){
#Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<String, String>();
params.put("username",ThisApplication.getInstance().getUsername());
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
AdapterView.OnItemSelectedListener onItemSelectedListener1 =
new AdapterView.OnItemSelectedListener(){
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
String s1 = String.valueOf(catevalue[position]);
textView1.setText(s1);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {}
};
private void showFileChooser() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
}
public void imageFromGallery() {
Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(Intent.createChooser(intent, getText(R.string.label_select_img)), SELECT_POST_IMG);
}
public void imageFromCamera() {
try {
File root = new File(Environment.getExternalStorageDirectory(), APP_TEMP_FOLDER);
if (!root.exists()) {
root.mkdirs();
}
File sdImageMainDirectory = new File(root, "post.jpg");
outputFileUri = Uri.fromFile(sdImageMainDirectory);
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
startActivityForResult(cameraIntent, CREATE_POST_IMG);
} catch (Exception e) {
Toast.makeText(ActivityPost.this, "Error occured. Please try again later.", Toast.LENGTH_SHORT).show();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
Uri filePath = data.getData();
try {
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
choiceItemImg.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
if (requestCode == SELECT_POST_IMG && resultCode == RESULT_OK && data != null && data.getData() != null) {
Uri filePath = data.getData();
try {
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
choiceItemImg2.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
public String getStringImage(Bitmap bmp){
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] imageBytes = baos.toByteArray();
String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
return encodedImage;
}
public void uploadImage(){
final String GetAuthorsname = editTextAuthorsname.getText().toString();
final String GetAuthorsphone = editTextAuthorsphone.getText().toString();
final String GetTitle = editTitle.getText().toString().trim();
final String image = getStringImage(bitmap);
final String GetPrice = editTextPrice.getText().toString();
final String GetStock = textView1.getText().toString();
final String GetDescription = editTextDescription.getText().toString();
final String GetStatus = editTextStatus.getText().toString();
class UploadImage extends AsyncTask<Void,Void,String> {
ProgressDialog loading;
#Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(ActivityPost.this,"Please wait...","uploading",false,false);
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
Toast.makeText(ActivityPost.this,s, Toast.LENGTH_LONG).show();
}
#Override
protected String doInBackground(Void... params) {
RequestHandler rh = new RequestHandler();
HashMap<String,String> param = new HashMap<String,String>();
param.put(KEY_TITLE,GetTitle);
param.put(KEY_IMAGE,image);
param.put(KEY_PRICE,GetPrice);
param.put(KEY_STOCK,GetStock);
param.put(KEY_DESCRIPTION,GetDescription);
param.put(KEY_STATUS,GetStatus);
param.put(KEY_AUTHORSNAME,GetAuthorsname);
param.put(KEY_AUTHORSPHONE,GetAuthorsphone);
String result = rh.sendPostRequest(UPLOAD_URL, param);
return result;
}
}
UploadImage u = new UploadImage();
u.execute();
}
public Boolean checkPicture() {
String image = getStringImage(bitmap);
String GetPrice = editTextPrice.getText().toString();
String GetDescription = editTextDescription.getText().toString();
String GetStatus = editTextStatus.getText().toString();
editTitle.setError(null);
editTextPrice.setError(null);
editTextDescription.setError(null);
editTextStatus.setError(null);
if (image.length() == 0) {
editTitle.setError(getString(R.string.error_field_empty));
return false;
} if (GetPrice.length() == 0) {
editTextPrice.setError(getString(R.string.error_field_empty));
return false;
} if (GetDescription.length() == 0) {
editTextDescription.setError(getString(R.string.error_field_empty));
return false;
} if (GetStatus.length() == 0) {
editTextStatus.setError(getString(R.string.error_field_empty));
return false;
}
return true;
}
public Boolean checkDesc() {
String GetDescription = editTextDescription.getText().toString();
editTextDescription.setError(null);
if (GetDescription.length() == 0) {
editTextDescription.setError(getString(R.string.error_field_empty));
return false;
}
return true;
}
public Boolean checkProductName() {
String GetTitle = editTitle.getText().toString();
editTitle.setError(null);
if (GetTitle.length() == 0) {
editTitle.setError(getString(R.string.error_field_empty));
return false;
}
return true;
}
public Boolean checkCategory() {
String GetStock = textView1.getText().toString();
textView1.setError(null);
if (GetStock.length() == 0) {
editTitle.setError(getString(R.string.error_field_empty));
return false;
}
return true;
}
#Override
public void onClick(View v) {
if(v == buttonChoose){
showFileChooser();
//imageFromGallery();
}
if(v == buttonUpload){
// checkUsername();
if (!ThisApplication.getInstance().isConnected()) {
Toast.makeText(getApplicationContext(), R.string.msg_network_error, Toast.LENGTH_SHORT).show();
} else if (!checkProductName() || !checkDesc() || !checkCategory()) {
} else {
uploadImage();
}
}
}
#Override
public void onBackPressed(){
finish();
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_new_item, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.sync:
Intent intent = getIntent();
finish();
startActivity(intent);
return true;
case R.id.action_post:
uploadImage();
default:
return super.onOptionsItemSelected(item);
}
}
}