public class userListActivity extends AppCompatActivity {
public void getPhoto() {
Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, 1);
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == 1) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
getPhoto();
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.share_menu, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.share) {
if (checkSelfPermission(android.Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{android.Manifest.permission.READ_EXTERNAL_STORAGE}, 1);
} else {
getPhoto();
}
} else if (item.getItemId() == R.id.logout) {
ParseUser.logOut();
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_list);
setTitle("User Feed");
final ListView listView = findViewById(R.id.listView);
final ArrayList<String> usernames = new ArrayList<String>();
final ArrayAdapter arrayAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, usernames);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Intent intent = new Intent(getApplicationContext(), userFeedActivity.class);
intent.putExtra("username", usernames.get(i));
startActivity(intent);
}
});
ParseQuery<ParseUser> query = ParseUser.getQuery();
query.whereNotEqualTo("username",ParseUser.getCurrentUser().getUsername());
query.addAscendingOrder("username");
query.findInBackground(new FindCallback<ParseUser>() {
#Override
public void done(List<ParseUser> objects, ParseException e) {
if (e == null) {
if (objects.size() > 0) {
for (ParseUser user : objects) {
usernames.add(user.getUsername());
}
listView.setAdapter(arrayAdapter);
}
} else {
e.printStackTrace();
}
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Uri selectedImage = data.getData();
if (requestCode == 1 && resultCode == RESULT_OK && data != null) {
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), selectedImage);
Log.i("Image Selected", "Good work");
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
byte[] byteArray = stream.toByteArray();
ParseFile file = new ParseFile("image.png", byteArray);
ParseObject object = new ParseObject("Image");
object.put("image", file);
object.put("username", ParseUser.getCurrentUser().getUsername());
object.saveInBackground(new SaveCallback() {
#Override
public void done(ParseException e) {
if (e == null) {
Toast.makeText(userListActivity.this, "Image has been shared!", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(userListActivity.this, "There has been an issue uploading the image :(", Toast.LENGTH_SHORT).show();
}
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
public class MainActivity extends AppCompatActivity implements View.OnClickListener, View.OnKeyListener {
Boolean signUpModeActive = true;
TextView loginTextView;
EditText usernameEditText;
EditText passwordEditText;
public void showUserList() {
Intent intent = new Intent(getApplicationContext(), userListActivity.class);
startActivity(intent);
}
#Override
public boolean onKey(View view, int i, KeyEvent keyEvent) {
if (i == KeyEvent.KEYCODE_ENTER && keyEvent.getAction() == KeyEvent.ACTION_DOWN) {
signUpClicked(view);
}
return false;
}
#Override
public void onClick(View view) {
if (view.getId() == R.id.loginTextView) {
Button signUpButton = findViewById(R.id.signUpButton);
if (signUpModeActive) {
signUpModeActive = false;
signUpButton.setText("Login");
loginTextView.setText("or, Sign Up");
} else {
signUpModeActive = true;
signUpButton.setText("Sign Up");
loginTextView.setText("or, Login");
}
} else if (view.getId() == R.id.logoimageView || view.getId() == R.id.backgroudLayout) {
InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),0);
}
}
public void signUpClicked(View view) {
if (usernameEditText.getText().toString().matches("") || passwordEditText.getText().toString().matches("")) {
Toast.makeText(this, "A username and a password are required.",Toast.LENGTH_SHORT).show();
} else {
if (signUpModeActive) {
ParseUser user = new ParseUser();
user.setUsername(usernameEditText.getText().toString());
user.setPassword(passwordEditText.getText().toString());
user.signUpInBackground(new SignUpCallback() {
#Override
public void done(ParseException e) {
if (e == null) {
Log.i("Signup", "Success");
showUserList();
} else {
Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
} else {
// Login
ParseUser.logInInBackground(usernameEditText.getText().toString(), passwordEditText.getText().toString(), new LogInCallback() {
#Override
public void done(ParseUser user, ParseException e) {
if (user != null) {
Log.i("Login","ok!");
showUserList();
} else {
Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
}
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setTitle("Instagram");
loginTextView = findViewById(R.id.loginTextView);
loginTextView.setOnClickListener(this);
usernameEditText = findViewById(R.id.usernameEditText);
passwordEditText = findViewById(R.id.passwordEditText);
ImageView logoImageView = findViewById(R.id.logoimageView);
ConstraintLayout backgroundLayout = findViewById(R.id.backgroudLayout);
logoImageView.setOnClickListener(this);
backgroundLayout.setOnClickListener(this);
passwordEditText.setOnKeyListener(this);
if (ParseUser.getCurrentUser() != null) {
showUserList();
}
ParseAnalytics.trackAppOpenedInBackground(getIntent());
}
public class userFeedActivity extends AppCompatActivity {
LinearLayout linLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_feed);
Intent intent = getIntent();
String username = intent.getStringExtra("username");
setTitle(username + "'s Photos");
linLayout = findViewById(R.id.linLayout);
ParseQuery<ParseObject> query = new ParseQuery<ParseObject>("Image");
query.whereEqualTo("username", username);
query.orderByDescending("createdAt");
query.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> objects, ParseException e) {
if (e == null && objects.size() > 0) {
for (ParseObject object : objects) {
ParseFile file = (ParseFile) object.get("image");
file.getDataInBackground(new GetDataCallback() {
#Override
public void done(byte[] data, ParseException e) {
if (e == null && data != null) {
Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0,data.length);
ImageView imageView = new ImageView(getApplicationContext());
imageView.setLayoutParams(new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT
));
imageView.setImageBitmap(bitmap);
linLayout.addView(imageView);
}
}
});
}
}
}
});
}
I EDITED IT
THIS I MY WHOLE CODE NOW
PLEASE HELP
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
Hi in the below code displaying the devices near by via bluetooth.
The below code was working fine for every device except one plus 6 phone.
I found a bug in the one plus 6 phone. If we turn on bluetooth and location then list of the near devices are listed.
can any one help me how to reslove the bug especially on one plus phones.
public class DeviceScanActivity extends AppCompatActivity {
private static final String TAG = DeviceScanActivity.class.getSimpleName();
private static final int PERMISSION_REQUEST_COARSE_LOCATION = 1;
#Bind(R.id.back)
TextView mBack;
#Bind(R.id.refresh)
TextView mRefresh;
#Bind(R.id.toolBar)
Toolbar mToolBar;
#Bind(R.id.scan_status)
TextView mScanStatus;
#Bind(R.id.deviceListView)
RecyclerView mDeviceListView;
#Bind(R.id.scanningProgress)
ProgressBar mScanningProgress;
private DeviceListAdapter mAdapter;
private BleService mBleService;
private List<BluetoothDevice> mBleDevices;
private SharedPreferences mPref;
private ProgressDialog mProgressDialog;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scan_device);
ButterKnife.bind(this);
mProgressDialog = new ProgressDialog(this);
mPref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
initToolBar();
mBleDevices = new ArrayList<>();
mAdapter = new DeviceListAdapter(this);
mDeviceListView.setAdapter(mAdapter);
LinearLayoutManager manager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
mDeviceListView.setLayoutManager(manager);
mDeviceListView.addOnItemTouchListener(new RecyclerItemClickListener(this, new RecyclerItemClickListener.OnItemClickListener() {
#Override
public void onItemClick(View view, int position) {
showProgressDialog();
List<BluetoothDevice> bluetoothDevices = mAdapter.getBluetoothDevices();
if (bluetoothDevices != null) {
if (bluetoothDevices.size() > position) {
BluetoothDevice bluetoothDevice = bluetoothDevices.get(position);
if (bluetoothDevice != null) {
String address = bluetoothDevice.getAddress();
mBleService.connect(address);
}
}
}
}
}));
final IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(BleService.ACTION_DEVICE_FOUND);
intentFilter.addAction(BleService.ACTION_GATT_CONNECTED);
intentFilter.addAction(BleService.ACTION_GAT_CONNECTING);
intentFilter.addAction(BleService.ACTION_GATT_DISCONNECTED);
intentFilter.addAction(BleService.ACTION_GAT_SERVICE_DISCOVERED);
registerReceiver(mGattUpdateReceiver, intentFilter);
if (ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.BLUETOOTH,Manifest.permission.ACCESS_FINE_LOCATION
, Manifest.permission.BLUETOOTH_ADMIN, Manifest.permission.ACCESS_FINE_LOCATION}, PERMISSION_REQUEST_COARSE_LOCATION);
}
} else {
if (mServiceConnection != null) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, 101);
}
Intent intent = new Intent(this, BleService.class);
bindService(intent, mServiceConnection, Context.BIND_AUTO_CREATE);
}
}
private void showProgressDialog() {
if (mProgressDialog == null) {
mProgressDialog = new ProgressDialog(this);
}
mProgressDialog.setMessage(getString(R.string.loading));
mProgressDialog.setCanceledOnTouchOutside(false);
mProgressDialog.show();
}
private ServiceConnection mServiceConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
mBleService = ((BleService.LocalBinder) iBinder).getLeService();
if (mBleService != null) {
mBleService.scanLeDevice(true);
mScanStatus.setVisibility(View.VISIBLE);
mScanStatus.setText(R.string.scanning_device);
}
}
#Override
public void onServiceDisconnected(ComponentName componentName) {
}
};
#Override
protected void onResume() {
super.onResume();
}
#Override
protected void onStart() {
super.onStart();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 101) {
if (mBleService != null) {
mBleService.scanLeDevice(true);
}
}
}
private BroadcastReceiver mGattUpdateReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
switch (action) {
case BleService.ACTION_DEVICE_FOUND:
BluetoothDevice device = (BluetoothDevice) intent.getParcelableExtra(BleService.EXTRA_DEVICE);
if (mBleDevices != null) {
if (!mBleDevices.contains(device)) {
mBleDevices.add(device);
mAdapter.udpateBluetoothDevices(mBleDevices);
mAdapter.notifyDataSetChanged();
}
}
break;
case BleService.ACTION_GATT_CONNECTED:
Log.d(TAG, "!Action gat connected...");
mBleService.scanLeDevice(false);
mScanStatus.setVisibility(View.VISIBLE);
mScanStatus.setText(getString(R.string.connected));
break;
case BleService.ACTION_GAT_CONNECTING:
mScanStatus.setVisibility(View.VISIBLE);
mScanStatus.setText(getString(R.string.connecting));
Log.d(TAG, "!Action Gat Connecting..");
break;
case BleService.ACTION_GATT_DISCONNECTED:
mScanStatus.setVisibility(View.VISIBLE);
mScanStatus.setText(getString(R.string.disconnected));
mScanningProgress.setVisibility(View.GONE);
mRefresh.setVisibility(View.VISIBLE);
if (mProgressDialog != null) {
mProgressDialog.dismiss();
}
Log.d(TAG, "!Action Gat Disconnected..");
break;
case BleService.ACTION_GAT_SERVICE_DISCOVERED:
boolean isOperator = mPref.getBoolean(Constants.IS_OPERATOR, false);
if (mProgressDialog != null) {
mProgressDialog.dismiss();
}
if (isOperator) {
Intent homeIntent = new Intent(DeviceScanActivity.this, HomeScreenActivity.class);
startActivity(homeIntent);
finish();
} else {
Intent lightControllIntent = new Intent(DeviceScanActivity.this, LightConfigurationActivity.class);
startActivity(lightControllIntent);
finish();
}
mScanStatus.setText(getString(R.string.discoveringService));
Log.d(TAG, "!Action Gat Discovering..");
break;
}
}
};
private void initToolBar() {
mRefresh.setVisibility(View.VISIBLE);
}
#OnClick(R.id.refresh)
public void onClick() {
mScanStatus.setVisibility(View.VISIBLE);
mRefresh.setVisibility(View.GONE);
mScanningProgress.setVisibility(View.VISIBLE);
mBleDevices.clear();
mAdapter.udpateBluetoothDevices(new ArrayList<BluetoothDevice>());
mAdapter.notifyDataSetChanged();
}
#Override
protected void onDestroy() {
if (mServiceConnection != null) {
unbindService(mServiceConnection);
}
if (mGattUpdateReceiver != null) {
unregisterReceiver(mGattUpdateReceiver);
}
super.onDestroy();
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
if (requestCode == PERMISSION_REQUEST_COARSE_LOCATION) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if (mServiceConnection != null) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, 101);
}
Intent intent = new Intent(this, BleService.class);
bindService(intent, mServiceConnection, Context.BIND_AUTO_CREATE);
} else {
finish();
}
}
}
}
I am building an app. One of the features I have is a paid option in which the user has access to an additional layout. Right now, the user can get there by clicking a button. Instead, I would like to have a swiping motion- if the user swipes down, it will ask for permission for the paid layout. If they do pay, when they swipe up, they can access the original layout.
Here is my main activity :
public class MainActivity extends AppCompatActivity {
EditText editText2;
Button btn_purchase;
ImageView imageView2;
String skuId;
SessionManager sessionManager;
// create new Person
private BillingClient mBillingClient;
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sessionManager=new SessionManager(MainActivity.this);
if(sessionManager.getPurchased()){
Intent intent = new Intent(MainActivity.this, PaidActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish();
}
btn_purchase=findViewById(R.id.btn_purchase);
imageView2 = (ImageView) findViewById(R.id.imageView2);
mBillingClient = BillingClient.newBuilder(MainActivity.this).setListener(new PurchasesUpdatedListener() {
#Override
public void onPurchasesUpdated(int responseCode, #Nullable List<Purchase> purchases) {
if (responseCode == BillingClient.BillingResponse.OK
&& purchases != null) {
for (Purchase purchase : purchases) {
//TODO: Handle purchase
// handlePurchase(purchase);
Log.e("Main", "handle Purchase ");
Log.e("MainAct", "onPurchasesUpdated() response: " + responseCode);
Log.e("dev", "successful purchase...");
String purchasedSku = purchase.getSku();
Log.e("dev", "Purchased SKU: " + purchasedSku);
String purchaseToken = purchase.getPurchaseToken();
sessionManager.savePurchased(true);
Intent intent = new Intent(MainActivity.this, PaidActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish();
}
} else if (responseCode == BillingClient.BillingResponse.USER_CANCELED) {
// Handle an error caused by a user cancelling the purchase flow.
} else {
// Handle any other error codes.
}
}
}).build();
List<String> skuList = new ArrayList <> ();
skuList.add("appsubscription2018");
SkuDetailsParams.Builder params = SkuDetailsParams.newBuilder();
params.setSkusList(skuList).setType(BillingClient.SkuType.INAPP);
mBillingClient.querySkuDetailsAsync(params.build(),
new SkuDetailsResponseListener() {
#Override
public void onSkuDetailsResponse(int responseCode, List<SkuDetails> skuDetailsList) {
// Process the result.
if (responseCode == BillingClient.BillingResponse.OK && skuDetailsList != null) {
Log.e("MainActivity", "onSkuDetailsResponse: success");
for (SkuDetails skuDetails : skuDetailsList) {
Log.e("MainActivity", "products: "+skuDetailsList);
String sku = skuDetails.getSku();
skuId = skuDetails.getSku();
String price = skuDetails.getPrice();
if ("appsubscription2018 ".equals(sku)) {
Log.e("MainActivity", "product is appsubscription2018 ");
// mPremiumUpgradePrice = price;
}
}
}
}
});
btn_purchase.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mBillingClient.startConnection(new BillingClientStateListener() {
#Override
public void onBillingSetupFinished(#BillingClient.BillingResponse int billingResponseCode) {
if (billingResponseCode == BillingClient.BillingResponse.OK) {
// The billing client is ready. You can query purchases here.
// The billing client is ready. You can query purchases here.
BillingFlowParams flowParams = BillingFlowParams.newBuilder()
.setSku("appsubscription2018")
.setType(BillingClient.SkuType.INAPP)
.build();
int responseCode = mBillingClient.launchBillingFlow(MainActivity.this, flowParams);
if (responseCode != BillingClient.BillingResponse.OK) {
Log.e("Main", "launchBillingFlow ok");
}
}
}
#Override
public void onBillingServiceDisconnected() {
// Try to restart the connection on the next request to
// Google Play by calling the startConnection() method.
}
});
}
});
imageView2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (checkFilePermission(MainActivity.this)){
getPhoto();
}
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode ==1 && resultCode == RESULT_OK && data != null) {
Uri selectedImage = data.getData();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), selectedImage);
imageView2.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
#TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public static boolean checkFilePermission(final Context context) {
int currentAPIVersion = Build.VERSION.SDK_INT;
if(currentAPIVersion>= Build.VERSION_CODES.M)
{
if (ContextCompat.checkSelfPermission(context, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale((Activity) context, Manifest.permission.READ_EXTERNAL_STORAGE)) {
AlertDialog.Builder alertBuilder = new AlertDialog.Builder(context);
alertBuilder.setCancelable(true);
alertBuilder.setTitle("Permission necessary");
alertBuilder.setMessage("External storage permission is necessary");
alertBuilder.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
#TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public void onClick(DialogInterface dialog, int which) {
ActivityCompat.requestPermissions((Activity) context, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 1);
}
});
AlertDialog alert = alertBuilder.create();
alert.show();
} else {
ActivityCompat.requestPermissions((Activity) context, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 1);
}
return false;
} else {
return true;
}
} else {
return true;
}
}
public void getPhoto() {
Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent,1);
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode ==1){
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED);{
getPhoto();
}
}
}
}
Another class calls the GridView class below that is populated with images from a parse server, if a user clicks on a grid item, it starts the same GridView class with different bundled strings so it can pull from a different parse database class. Now at this point, when a user clicks an GridView item (from the 2nd gridview that was set up), I want it to start a different activity class.
I tried doing an if/else if statement in the onItemClick that takes the "PARSE_CLASS" bundled string but I can't seem to get that to work. I'm relatively new to android programming so I don't know the best way to do this.
public class DisplayGrid extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
GridView gridView = null;
List<ParseObject> obj;
ProgressDialog loadProgress;
GridViewAdapter adapter;
Bundle extras = new Bundle();
GridViewAdapter itemGridAdapter;
private List<ImageList> imageArrayList = null;
private List<String> categoryNameArrayList = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.ws_display_grid);
imageArrayList = new ArrayList<ImageList>();
categoryNameArrayList = new ArrayList<String>();
gridView = (GridView) findViewById(R.id.gridView);
itemGridAdapter = new GridViewAdapter(DisplayGrid.this, imageArrayList);
gridView.setAdapter(itemGridAdapter);
new RemoteDataTask().execute();
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
Intent i = getIntent();
Bundle itemExtras = i.getExtras();
final String activeSupplier = itemExtras.getString("SUPPLIER");
String parseClass = extras.getString("PARSE_CLASS");
#Override
public void onItemClick(AdapterView<?> arg0, View v, int position,
long arg3) {
Intent t = new Intent(getApplicationContext(), DisplayGrid.class);
extras.putString("SUPPLIER", activeSupplier);
extras.putString("PARSE_CLASS", "Items");
t.putExtras(extras);
startActivity(t);
}
});
}//end onCreate method
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
#Override
public void onStart() {
super.onStart();
}
#Override
public void onStop() {
super.onStop();
}
//RemoteDataTask
private class RemoteDataTask extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
loadProgress = new ProgressDialog(DisplayGrid.this);
loadProgress.setTitle("Images");
loadProgress.setMessage("Loading...");
loadProgress.setIndeterminate(false);
loadProgress.show();
}
#Override
protected Void doInBackground(Void... params) {
try {
Intent i = getIntent();
Bundle extras = i.getExtras();
String parseClass = extras.getString("PARSE_CLASS");
String activeSupplier = extras.getString("SUPPLIER");
String category;
ParseQuery<ParseObject> query = new ParseQuery<>(parseClass);
query.whereEqualTo("username", activeSupplier);
obj = query.find();
if (parseClass == "Items") {
category = extras.getString("CATEGORY");
query.whereEqualTo("category", category);
}
for (ParseObject categories : obj) {
//get image
ParseFile image = (ParseFile) categories.get("image");
ImageList gridBlock = new ImageList();
gridBlock.setImage(image.getUrl());
imageArrayList.add(gridBlock);
Log.i("AppInfo", "image sent to imageArrayList");
String categoryName = null;
//get category name
if (categoryName == null) {
} else {
categoryName = categories.getString("categoryName");
categoryNameArrayList.add(categoryName);
Log.i("AppInfo", categoryName);
}
}
} catch (ParseException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
gridView = (GridView) findViewById(R.id.gridView);
adapter = new GridViewAdapter(DisplayGrid.this, imageArrayList);
gridView.setAdapter(adapter);
loadProgress.dismiss();
Log.i("AppInfo", "CategoryGrid Populated");
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1 && resultCode == RESULT_OK && data != null) {
Uri selectedImage = data.getData();
try {
Bitmap bitmapImage =
MediaStore.Images.Media.getBitmap
(this.getContentResolver(), selectedImage);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmapImage.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
//convert to parse file
ParseFile file = new ParseFile("Img.png", byteArray);
ParseObject object = new ParseObject("Categories");
object.put("username", ParseUser.getCurrentUser().getUsername());
object.put("image", file);
object.saveInBackground(new SaveCallback() {
#Override
public void done(ParseException e) {
if (e == null) {
Toast.makeText(getApplication().getBaseContext(), "Your image has been saved", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplication().getBaseContext(), "Upload failed, please try again", Toast.LENGTH_SHORT).show();
}
}
});
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(getApplication().getBaseContext(), "Upload failed, please try again", Toast.LENGTH_SHORT).show();
}
}
}
//begin getTitle method
//begin createMenu
#Override
public boolean onCreateOptionsMenu(Menu menu) {
new MenuInflater(getApplication())
.inflate(R.menu.options, menu);
return (super.onCreateOptionsMenu(menu));
}
//end createMenu
//begin onOptionsItemSelected
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.manufacturers) {
Intent i = new Intent(getApplicationContext(), SupplierList.class);
startActivity(i);
return true;
} else if (item.getItemId() == R.id.add) {
Intent i = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, 1);
return true;
} else if (item.getItemId() == R.id.sign_out) {
ParseUser.logOut();
Intent i = new Intent(getApplicationContext(), MainActivity.class);
startActivity(i);
return true;
}
return (super.onOptionsItemSelected(item));
}
//end onOptionsItemSelected
}
This is what I tried. When I tried this, the second GridView wouldn't load. So I'm guessing I'm unable to retrieve the "PARSE_CLASS" bundled string the second time around.
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
Intent i = getIntent();
Bundle itemExtras = i.getExtras();
final String activeSupplier = itemExtras.getString("SUPPLIER");
String parseClass = extras.getString("PARSE_CLASS");
#Override
public void onItemClick(AdapterView<?> arg0, View v, int position,
long arg3) {
if (parseClass == "Categories") {
Intent t = new Intent(getApplicationContext(), DisplayGrid.class);
extras.putString("SUPPLIER", activeSupplier);
extras.putString("PARSE_CLASS", "Items");
t.putExtras(extras);
startActivity(t);
} else if(parseClass == "Items"){
Intent t = new Intent(getApplicationContext(), ItemDisplay.class);
//extras.putString("SUPPLIER", activeSupplier);
//extras.putString("PARSE_CLASS", "Items");
//t.putExtras(extras);
startActivity(t);
}
}
});
ANSWER
Someone on reddit's learn programming was nice enough to point out that I had an issue with string comparisons. had to use
if(parseClass.equals("Categories")){}
instead of
if(parseClass == "Categories"){}
I feel like an idiot, hopefully someone else benefits from this long disastrous effort.
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
Intent t = getIntent();
Bundle itemExtras = t.getExtras();
String activeSupplier = itemExtras.getString("SUPPLIER");
String parseClass = itemExtras.getString("PARSE_CLASS");
#Override
public void onItemClick(AdapterView<?> arg0, View v, int position,
long arg3) {
Log.i("AppInfo", parseClass);
if (parseClass.equals("Categories")) {
Log.i("AppInfo", parseClass);
Intent t = new Intent(getApplicationContext(), DisplayGrid.class);
String categoryName = categoryNameArrayList.get(position);
itemExtras.putString("SUPPLIER", activeSupplier);
itemExtras.putString("PARSE_CLASS", "Items");
itemExtras.putString("CATEGORY_NAME", categoryName);
t.putExtras(itemExtras);
startActivity(t);
} else if (parseClass.equals("Items")) {
Intent t = new Intent(getApplicationContext(), ItemDisplay.class);
//extras.putString("SUPPLIER", activeSupplier);
//extras.putString("PARSE_CLASS", "Items");
//t.putExtras(extras);
startActivity(t);
}
}
});
public class DisplayGrid extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
GridView gridView = null;
List<ParseObject> obj;
ProgressDialog loadProgress;
GridViewAdapter adapter;
Bundle extras = new Bundle();
GridViewAdapter itemGridAdapter;
private List<ImageList> imageArrayList = null;
private List<String> categoryNameArrayList = null;
String activeSupplier;
String parseClass;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.ws_display_grid);
imageArrayList = new ArrayList<ImageList>();
categoryNameArrayList = new ArrayList<String>();
Intent i = getIntent();
if (null != i) {
Bundle itemExtras = i.getExtras();
activeSupplier = itemExtras.getString("SUPPLIER");
parseClass = itemExtras.getString("PARSE_CLASS");
}
RemoteDataTask remoteDataAsync = new RemoteDataTask();
remoteDataAsync.execute();
if(remoteDataAsync.getStatus() == AsyncTask.Status.PENDING){
// My AsyncTask has not started yet
}
if(remoteDataAsync.getStatus() == AsyncTask.Status.RUNNING){
// My AsyncTask is currently doing work in doInBackground()
}
if(remoteDataAsync.getStatus() == AsyncTask.Status.FINISHED){
// My AsyncTask is done and onPostExecute was called
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View v, int position,
long arg3) {
Intent t = new Intent(getApplicationContext(), DisplayGrid.class);
extras.putString("SUPPLIER", activeSupplier);
extras.putString("PARSE_CLASS", parseClass);
t.putExtras(extras);
startActivity(t);
}
});
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
#Override
public void onStart() {
super.onStart();
}
#Override
public void onStop() {
super.onStop();
}
//RemoteDataTask
private class RemoteDataTask extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
loadProgress = new ProgressDialog(DisplayGrid.this);
loadProgress.setTitle("Images");
loadProgress.setMessage("Loading...");
loadProgress.setIndeterminate(false);
loadProgress.show();
}
#Override
protected Void doInBackground(Void... params) {
try {
Intent i = getIntent();
Bundle extras = i.getExtras();
String parseClass = extras.getString("PARSE_CLASS");
String activeSupplier = extras.getString("SUPPLIER");
String category;
ParseQuery<ParseObject> query = new ParseQuery<>(parseClass);
query.whereEqualTo("username", activeSupplier);
obj = query.find();
if (parseClass == "Items") {
category = extras.getString("CATEGORY");
query.whereEqualTo("category", category);
}
for (ParseObject categories : obj) {
//get image
ParseFile image = (ParseFile) categories.get("image");
ImageList gridBlock = new ImageList();
gridBlock.setImage(image.getUrl());
imageArrayList.add(gridBlock);
Log.i("AppInfo", "image sent to imageArrayList");
String categoryName = null;
//get category name
if (categoryName == null) {
} else {
categoryName = categories.getString("categoryName");
categoryNameArrayList.add(categoryName);
Log.i("AppInfo", categoryName);
}
}
} catch (ParseException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
adapter = new GridViewAdapter(DisplayGrid.this, imageArrayList);
gridView.setAdapter(adapter);
loadProgress.dismiss();
Log.i("AppInfo", "CategoryGrid Populated");
}//end onCreate method
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1 && resultCode == RESULT_OK && data != null) {
Uri selectedImage = data.getData();
try {
Bitmap bitmapImage =
MediaStore.Images.Media.getBitmap
(this.getContentResolver(), selectedImage);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmapImage.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
//convert to parse file
ParseFile file = new ParseFile("Img.png", byteArray);
ParseObject object = new ParseObject("Categories");
object.put("username", ParseUser.getCurrentUser().getUsername());
object.put("image", file);
object.saveInBackground(new SaveCallback() {
#Override
public void done(ParseException e) {
if (e == null) {
Toast.makeText(getApplication().getBaseContext(), "Your image has been saved", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplication().getBaseContext(), "Upload failed, please try again", Toast.LENGTH_SHORT).show();
}
}
});
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(getApplication().getBaseContext(), "Upload failed, please try again", Toast.LENGTH_SHORT).show();
}
}
}
//begin getTitle method
//begin createMenu
#Override
public boolean onCreateOptionsMenu(Menu menu) {
new MenuInflater(getApplication())
.inflate(R.menu.options, menu);
return (super.onCreateOptionsMenu(menu));
}
//end createMenu
//begin onOptionsItemSelected
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.manufacturers) {
Intent i = new Intent(getApplicationContext(), SupplierList.class);
startActivity(i);
return true;
} else if (item.getItemId() == R.id.add) {
Intent i = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, 1);
return true;
} else if (item.getItemId() == R.id.sign_out) {
ParseUser.logOut();
Intent i = new Intent(getApplicationContext(), MainActivity.class);
startActivity(i);
return true;
}
return (super.onOptionsItemSelected(item));
}
//end onOptionsItemSelected
}
i have bluetooth Fragment.
I have my first Activity in which the BT connection is established. There is an option presented to the user and, based on their selection, a different Activity will load.
public class BluetoothFragment extends Fragment {
private NameMappingDataSource mName;
private DeviceAutoConnectDataSource deviceAutoConnect;
private ActivateDatasource activateDatasource;
List<DisplayNameMapping> dataItemsdevice = new ArrayList<DisplayNameMapping>();
private static final String TAG = "BluetoothChatFragment";
private static final int REQUEST_CONNECT_DEVICE_SECURE = 1;
private static final int REQUEST_CONNECT_DEVICE_INSECURE = 2;
private static final int REQUEST_ENABLE_BT = 3;
private ListView mConversationView;
private EditText mOutEditText;
private Button mSendButton;
private String mConnectedDeviceName = null;
private String mConnectedDeviceAddress = null;
private ArrayAdapter<String> mConversationArrayAdapter;
private StringBuffer mOutStringBuffer;
private BluetoothAdapter mBluetoothAdapter = null;
private BluetoothService mMessage = null;
private Context context;
boolean mBound = false;
#Override
public Context getContext() {
return context;
}
public void setContext(Context context) {
this.context = context;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mName = new NameMappingDataSource(getActivity());
deviceAutoConnect = new DeviceAutoConnectDataSource(getActivity());
activateDatasource = new ActivateDatasource(getActivity());
setHasOptionsMenu(true);
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter == null) {
FragmentActivity activity = getActivity();
Toast.makeText(activity, "Bluetooth is not available", Toast.LENGTH_LONG).show();
activity.finish();
}
}
#Override
public void onStart() {
super.onStart();
if (!mBluetoothAdapter.isEnabled()) {
Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
} else if (mMessage == null) {
setupChat();
}
}
#Override
public void onDestroy() {
super.onDestroy();
if (mMessage != null) {
mMessage.stop();
}
}
#Override
public void onResume() {
super.onResume();
if (mMessage != null) {
if (mMessage.getState() == BluetoothService.STATE_NONE) {
mMessage.start();
}
}
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container,
#Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_bluetooth_chat, container, false);
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
mConversationView = (ListView) view.findViewById(R.id.in);
mOutEditText = (EditText) view.findViewById(R.id.edit_text_out);
mSendButton = (Button) view.findViewById(R.id.button_send);
}
private void setupChat() {
mConversationArrayAdapter = new ArrayAdapter<String>(getActivity(), R.layout.message);
mConversationView.setAdapter(mConversationArrayAdapter);
mOutEditText.setOnEditorActionListener(mWriteListener);
mSendButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
View view = getView();
if (null != view) {
TextView textView = (TextView) view.findViewById(R.id.edit_text_out);
String message = textView.getText().toString();
sendMessage(message.getBytes());
}
}
});
final Button testButton = (Button) getActivity().findViewById(R.id.button1);
testButton.setTag(1);
testButton.setBackgroundResource(R.drawable.open);
testButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final int status = (Integer) v.getTag();
if (status == 1) {
v.setTag(0);
} else {
testButton.setBackgroundResource(R.drawable.open);
v.setTag(1);
}
}
});
mMessage = new BluetoothService(getActivity(), mHandler);
mOutStringBuffer = new StringBuffer("");
}
private void ensureDiscoverable() {
if (mBluetoothAdapter.getScanMode() !=
BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE) {
Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
startActivity(discoverableIntent);
}
}
public void sendMessage(byte[] message) {
if (mMessage.getState() != BluetoothService.STATE_CONNECTED) {
Toast.makeText(getActivity(), R.string.not_connected, Toast.LENGTH_SHORT).show();
return;
}
if (message.length > 0) {
mMessage.write(message);
mOutStringBuffer.setLength(0);
mOutEditText.setText(mOutStringBuffer);
}
}
private TextView.OnEditorActionListener mWriteListener
= new TextView.OnEditorActionListener() {
public boolean onEditorAction(TextView view, int actionId, KeyEvent event) {
// If the action is a key-up event on the return key, send the message
if (actionId == EditorInfo.IME_NULL && event.getAction() == KeyEvent.ACTION_UP) {
String message = view.getText().toString();
sendMessage(message.getBytes());
}
return true;
}
};
private void setStatus(int resId) {
FragmentActivity activity = getActivity();
if (null == activity) {
return;
}
final ActionBar actionBar = activity.getActionBar();
if (null == actionBar) {
return;
}
actionBar.setSubtitle(resId);
}
private void setStatus(CharSequence subTitle) {
FragmentActivity activity = getActivity();
if (null == activity) {
return;
}
final ActionBar actionBar = activity.getActionBar();
if (null == actionBar) {
return;
}
actionBar.setSubtitle(subTitle);
}
private final Handler mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
int t = 0;
FragmentActivity activity = getActivity();
switch (msg.what) {
case Constants.MESSAGE_STATE_CHANGE:
switch (msg.arg1) {
case BluetoothService.STATE_CONNECTED:
setStatus(getString(R.string.title_connected_to, mConnectedDeviceName));
mConversationArrayAdapter.clear();
break;
case BluetoothService.STATE_CONNECTING:
setStatus(R.string.title_connecting);
break;
case BluetoothService.STATE_LISTEN:
case BluetoothService.STATE_NONE:
setStatus(R.string.title_not_connected);
break;
}
break;
case Constants.MESSAGE_WRITE:
byte[] writeBuf = (byte[]) msg.obj;
mConversationArrayAdapter.add("Me: " + writeBuf);
break;
case Constants.MESSAGE_READ:
byte[] readBuf = (byte[]) msg.obj;
String readMessage = new String(readBuf, 0, msg.arg1);
mConversationArrayAdapter.add(mConnectedDeviceName + ": " + readMessage);
break;
case Constants.MESSAGE_DEVICE_NAME:
mConnectedDeviceName = msg.getData().getString(Constants.DEVICE_NAME);
mConnectedDeviceAddress = msg.getData().getString(Constants.DEVICE_ADDRESS);
if (null != activity) {
Toast.makeText(activity, "Connected to "
+ mConnectedDeviceName, Toast.LENGTH_SHORT).show();
}
break;
case Constants.MESSAGE_TOAST:
if (null != activity) {
Toast.makeText(activity, msg.getData().getString(Constants.TOAST),
Toast.LENGTH_SHORT).show();
mConnectedDeviceAddress=null;
}
break;
}
}
};
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case REQUEST_CONNECT_DEVICE_SECURE:
if (resultCode == Activity.RESULT_OK) {
connectDevice(data, true);
}
break;
case REQUEST_CONNECT_DEVICE_INSECURE:
if (resultCode == Activity.RESULT_OK) {
connectDevice(data, false);
}
break;
case REQUEST_ENABLE_BT:
if (resultCode == Activity.RESULT_OK) {
setupChat();
} else {
Log.d(TAG, "BT not enabled");
Toast.makeText(getActivity(), R.string.bt_not_enabled_leaving,
Toast.LENGTH_SHORT).show();
getActivity().finish();
}
}
}
private void connectDevice(Intent data, boolean secure) {
String address = data.getExtras()
.getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
mMessage.connect(device, secure);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.bluetooth_chat, menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.secure_connect_scan: {
Intent serverIntent = new Intent(this.context, DeviceListActivity.class);
startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE_SECURE);
return true;
}
case R.id.insecure_connect_scan: {
Intent serverIntent = new Intent(this.context, DeviceListActivity.class);
startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE_INSECURE);
return true;
}
case R.id.discoverable: {
ensureDiscoverable();
return true;
}
case R.id.menu_user: {
if(mConnectedDeviceAddress!=null) {
mName.open();
List<DisplayNameMapping> str = mName.getDisplayNameMappingLiked(mConnectedDeviceAddress);
mName.close();
String setname = str.get(0).getDisplay_name();
showInputDialogCheckPWAdminUser(setname, mConnectedDeviceAddress);
}
return true;
}
case R.id.menu_history: {
Intent userIntent = new Intent(getActivity(),UserListActivity.class);
userIntent.putExtra("addressdevice", mdeviceaddress);
startActivity(userIntent);
}
}
return false;
}
}
How to send message to here used connection of bletoothfragment.class
Please help me. I don't know
public class UserListActivity extends Activity implements UserListAdapter.customButtonListener {
Button btnadduser,btnconfig;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context=this;
getActionBar().setDisplayHomeAsUpEnabled(true);
userdata = new UserDataSource(this);
namedata = new NameMappingDataSource(this);
userdevicedata=new UserDeviceDatasource(this);
setContentView(R.layout.activity_user_list);
btnconfig=(Button) findViewById(R.id.btnconfig);
btnconfig.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
'How to send message to here used connection of bletoothfragment.class '
} catch (Exception ex) {
}
}
});
}
public void onButtonClickListner(int position, String value) {
}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
this.finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
You can save last connected device address and then you can use it.
String address = intent.getExtras()
.getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
// Get the BluetoothDevice object
BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
// Attempt to connect to the device
mChatService.connect(device, secure);