Application that worked yesterday does not work today. I'm still not understanding what I'm doing wrong. The problem is, I'm calling the following code fragment, but I can not activate it. What is the problem?
Edit1:
Toast works but why does not the particle in it work?
public class PermissionsActivity extends BaseActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_permissions);
}
#Override
protected void onStart() {
super.onStart();
initWidget();
}
private void initWidget() {
Button permission = (Button) findViewById(R.id.permission);
permission.setOnClickListener(this);
Button accessibility = (Button) findViewById(R.id.accessibility);
accessibility.setOnClickListener(this);
LinearLayout permissionLayout = (LinearLayout) findViewById(R.id.permission_layout);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
permissionLayout.setVisibility(View.GONE);
} else {
permissionLayout.setVisibility(View.VISIBLE);
}
}
private void goToPassword() {
if (SharedPreferenceUtil.readIsNumModel()) {
startActivity(new Intent(this, NumberCheckActivity.class));
finish();
} else {
startActivity(new Intent(this, GestureCheckActivity.class));
finish();
}
SharedPreferenceUtil.editIsFirst(false);
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode) {
case 2909: {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
ToastUtils.showToast("Permission allowed.");
} else {
ToastUtils.showToast("Please allow permission");
}
return;
}
}
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.permission:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (!Settings.System.canWrite(this)) {
requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 2909);
} else {
}
} else {
ToastUtils.showToast("Success");
}
break;
case R.id.accessibility:
if (!MyConstants.isPermissionOk(PermissionsActivity.this)) {
PermissionsActivity.this.startActivity(new Intent("android.settings.USAGE_ACCESS_SETTINGS"));
ToastUtils.showToast("Please find App Locker in this menu and enable it.");
} else {
ToastUtils.showToast("Accessibility enabled");
}
break;
default:
break;
}
}
protected void onResume() {
super.onResume();
goToNextScreen();
}
private void goToNextScreen() {
if (Build.VERSION.SDK_INT >= 23) {
if (MyConstants.isPermissionOk(PermissionsActivity.this) && Settings.System.canWrite(this)) {
goToPassword();
}
}
ToastUtils.showToast("onResume Working?");
}
}
Problem Fixed - Check it out best solution:
public class PermissionsActivity extends BaseActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_permissions);
}
#Override
protected void onStart() {
super.onStart();
initWidget();
}
private void initWidget() {
Button permission = (Button) findViewById(R.id.permission);
permission.setOnClickListener(this);
Button accessibility = (Button) findViewById(R.id.accessibility);
accessibility.setOnClickListener(this);
LinearLayout permissionLayout = (LinearLayout) findViewById(R.id.permission_layout);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
permissionLayout.setVisibility(View.GONE);
} else {
permissionLayout.setVisibility(View.VISIBLE);
}
}
private void goToPassword() {
if (SharedPreferenceUtil.readIsNumModel()) {
startActivity(new Intent(this, NumberCheckActivity.class));
finish();
} else {
startActivity(new Intent(this, GestureCheckActivity.class));
finish();
}
SharedPreferenceUtil.editIsFirst(false);
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode) {
case 2909: {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
ToastUtils.showToast("Permission allowed.");
} else {
ToastUtils.showToast("Please allow permission");
}
return;
}
}
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.permission:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (!Settings.System.canWrite(this)) {
requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 2909);
} else {
ToastUtils.showToast("Success");
}
} else {
ToastUtils.showToast("Success");
}
break;
case R.id.accessibility:
if (!MyConstants.isPermissionOk(PermissionsActivity.this)) {
PermissionsActivity.this.startActivity(new Intent("android.settings.USAGE_ACCESS_SETTINGS"));
ToastUtils.showToast("Please find App Locker in this menu and enable it.");
} else {
ToastUtils.showToast("Accessibility enabled");
}
break;
default:
break;
}
}
protected void onResume() {
super.onResume();
goToNextScreen();
}
private boolean checkIfAlreadyhavePermission() {
int result = ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
if (result == PackageManager.PERMISSION_GRANTED) {
return true;
} else {
return false;
}
}
private void goToNextScreen() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (MyConstants.isPermissionOk(PermissionsActivity.this) && checkIfAlreadyhavePermission() ) {
goToPassword();
}
}else{
goToPassword();
}
}
}
Related
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
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();
}
}
}
}
Button reqDeviceAdmin;
reqDeviceAdmin = (Button) findViewById(R.id.reqDeviceAdmin);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
if (!checkUsageStatsPermission(RequestPermission.this)) {
Intent intent = new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS);
startActivity(intent);
}
}
if (checkDeviceAdminPermission(RequestPermission.this)){
reqDeviceAdmin.setText(getString(R.string.uninstall_protect_is_active));
} else {
reqDeviceAdmin.setText(getString(R.string.uninstall_protect_is_not_active));
}
reqDeviceAdmin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (checkDeviceAdminPermission(RequestPermission.this)) {
} else {
requestDeviceAdmin();
}
}
});
#Override
public void onResume() {
super.onResume();
if (checkDeviceAdminPermission(RequestPermission.this)) {
reqDeviceAdmin.setText(getString(R.string.uninstall_protect_is_active));
} else {
reqDeviceAdmin.setText(getString(R.string.uninstall_protect_is_not_active));
}
}
This code is not checking for the if(checkDeviceAdminPermission(RequestPermission.this)) condition to be true. It's always returning else condition.It's always fetching the text uninstall_protect_is_not_active. This code is in RequestPermission.java. MIN_SDK=21.
I am using exactly same app and i am using this type:
#RequiresApi(api = Build.VERSION_CODES.M)
public void checkBTPermissions() {
if(Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP){
int permissionCheck =getActivity().checkSelfPermission("Manifest.permission.ACCESS_FINE_LOCATION");
permissionCheck += getActivity().checkSelfPermission("Manifest.permission.ACCESS_COARSE_LOCATION");
if (permissionCheck != 0) {
this.requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, 1001); //Any number
}
}else{
Log.d(TAG, "checkBTPermissions: No need to check permissions. SDK version < LOLLIPOP.");
}
}
If you call the checkBTpermission any where you can getting permission.
guys I need help with this code :
public View.OnClickListener btnGetLastLocationOnClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mGoogleApiClient != null) {
if (mGoogleApiClient.isConnected()) {
getMyLocation();
} else {
Toast.makeText(AddEditActivity.this,
"!mGoogleApiClient.isConnected()", Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(AddEditActivity.this,
"mGoogleApiClient == null", Toast.LENGTH_LONG).show();
}
}
};
so what I want to do is when I click on btnGetLocation this code should work, but instead the code works automatically when I start the activity so how can I make works only when I click on the button ?
I hope you guys understand the problem, I'm new Android developer so I'm still learning forgive me for my stupid question.
thank you
*** Update :
here is the whole code :
TextView txtmylink;
GoogleApiClient mGoogleApiClient;
Location mLastLocation;
Button getlastlocation;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtmylink = (TextView) findViewById(R.id.mylink);
getlastlocation = (Button) findViewById(R.id.getlastlocation);
getlastlocation.setOnClickListener(getlastlocationOnClickListener);
// Create an instance of GoogleAPIClient.
if (mGoogleApiClient == null) {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
}
View.OnClickListener getlastlocationOnClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mGoogleApiClient != null) {
if (mGoogleApiClient.isConnected()) {
getMyLocation();
} else {
Toast.makeText(MainActivity.this,
"!mGoogleApiClient.isConnected()", Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(MainActivity.this,
"mGoogleApiClient == null", Toast.LENGTH_LONG).show();
}
}
};
private void getMyLocation() {
try {
/* code should explicitly check to see if permission is available
(with 'checkPermission') or explicitly handle a potential 'SecurityException'
*/
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (mLastLocation != null) {
txtmylink.setText(String.valueOf("http://maps.google.com/maps?q=") +
String.valueOf(mLastLocation.getLatitude()) +
String.valueOf(",")+ String.valueOf(mLastLocation.getLongitude()));
} else {
Toast.makeText(MainActivity.this,
"mLastLocation == null",
Toast.LENGTH_LONG).show();
}
} catch (SecurityException e) {
Toast.makeText(MainActivity.this,
"SecurityException:\n" + e.toString(),
Toast.LENGTH_LONG).show();
}
}
#Override
protected void onStart() {
mGoogleApiClient.connect();
super.onStart();
}
#Override
protected void onStop() {
mGoogleApiClient.disconnect();
super.onStop();
}
#Override
public void onConnected(#Nullable Bundle bundle) {
getMyLocation();
}
#Override
public void onConnectionSuspended(int i) {
Toast.makeText(MainActivity.this,
"onConnectionSuspended: " + String.valueOf(i),
Toast.LENGTH_LONG).show();
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
Toast.makeText(MainActivity.this,
"onConnectionFailed: \n" + connectionResult.toString(),
Toast.LENGTH_LONG).show();
}
}
That's because you haven't associated the View.onClickListener object you've written to anything yet. Thus when the activity is started the listener's code gets executed. When you want a specific view say 'A' to respond to a click, you associate a View.onClickListener to it. So in your case add the following.
yourbutton.setOnClickListener(btnGetLastLocationOnClickListener)
Make sure you've bound the yourbutton to the Button view.
try this :
public void onClick(View v) {
if (view.getId() == R.id.btnGetLocation)
if (mGoogleApiClient != null) {
if (mGoogleApiClient.isConnected()) {
getMyLocation();
} else {
Toast.makeText(AddEditActivity.this,
"!mGoogleApiClient.isConnected()", Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(AddEditActivity.this,
"mGoogleApiClient == null", Toast.LENGTH_LONG).show();
}
}
If still not works write your code like this :
your activity must implement OnClickListener and
btnGetLocation.setOnClickListener(this)
and you will have the onClick like this
public void onClick(View v) {
if (view.getId() == R.id.btnGetLocation)
if (mGoogleApiClient != null) {
if (mGoogleApiClient.isConnected()) {
getMyLocation();
} else {
Toast.makeText(AddEditActivity.this,
"!mGoogleApiClient.isConnected()", Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(AddEditActivity.this,
"mGoogleApiClient == null", Toast.LENGTH_LONG).show();
}
}
You can accomplish it using the following code
btnGetLocation = (Button) findViewById(R.id.btnGetLocation); // or whatever you called the button
btnGetLocation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mGoogleApiClient != null) {
if (mGoogleApiClient.isConnected()) {
getMyLocation();
} else {
Toast.makeText(AddEditActivity.this,
"!mGoogleApiClient.isConnected()", Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(AddEditActivity.this,
"mGoogleApiClient == null", Toast.LENGTH_LONG).show();
}
}
}
Note that you can add this code in the onCreate() method to make it work
mTabHost = getTabHost();
mTabHost.addTab(mTabHost.newTabSpec(TAB_NEWS).setIndicator(TAB_NEWS).setContent(new Intent(this, NewsActivity1.class)));
mTabHost.addTab(mTabHost.newTabSpec(TAB_BBS).setIndicator(TAB_BBS).setContent(new Intent(this, BBSActivity.class)));
mTabHost.addTab(mTabHost.newTabSpec(TAB_CATEGORY).setIndicator(TAB_CATEGORY).setContent(new Intent(this, CategoryActivity.class)));
mTabHost.addTab(mTabHost.newTabSpec(TAB_DISCOVER).setIndicator(TAB_DISCOVER).setContent(new Intent(this, DiscoverActivity.class)));
mTabHost.addTab(mTabHost.newTabSpec(TAB_MINE).setIndicator(TAB_MINE).setContent(new Intent(this, MineActivity.class)));
Because a reason, i use the TabActivity, but the system's permission dialog can't show in targetSdk23.
for example: in NewsActivity, BBSActivity,CategoryActivity,DiscoverActivity,MineActivity, all cant show.
please help me, thanks~
for example DiscoverActivity:
public class DiscoverActivity extends BaseActivity implements View.OnClickListener{
private RelativeLayout near, plate, search, rate, oil, two_dimension_code, rl_activity, coupon;
private TextView tvActivityTitle;
private String url;
private LoadDialog dialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_discover);
GoogleAnalyticsUtil.doGoogleAnalytics();
initView();
initEvent();
}
private void initView() {
// TODO Auto-generated method stub
near = (RelativeLayout) findViewById(R.id.discover_near);
plate = (RelativeLayout) findViewById(R.id.discover_plate);
search = (RelativeLayout) findViewById(R.id.discover_search);
rate = (RelativeLayout) findViewById(R.id.discover_rate);
oil = (RelativeLayout) findViewById(R.id.discover_oil);
two_dimension_code = (RelativeLayout) findViewById(R.id.rl_twodimension_code);
rl_activity = (RelativeLayout) findViewById(R.id.rl_activity);
coupon = (RelativeLayout) findViewById(R.id.rl_coupon);
tvActivityTitle = (TextView) findViewById(R.id.tv_activity_title);
}
private void initEvent() {
near.setOnClickListener(this);
plate.setOnClickListener(this);
search.setOnClickListener(this);
rate.setOnClickListener(this);
oil.setOnClickListener(this);
two_dimension_code.setOnClickListener(this);
rl_activity.setOnClickListener(this);
coupon.setOnClickListener(this);
}
#Override
public void onClick(View v) {
final Intent intent = new Intent();
switch (v.getId()) {
case R.id.discover_near:
GoogleAnalyticsUtil.doGoogleActionAnalytics(GoogleAnalyticsConstant.ActionEvent.NEARPEOPLE_ACTION);
if (TextUtils.isEmpty(ShareProUtils.getUid(this))) {
intent.setClass(this, LoginActivity.class);
startActivity(intent);
} else {
intent.setClass(this, NearbyActivity.class);
startActivity(intent);
}
break;
case R.id.discover_plate:
intent.setClass(this, ForumActivity.class);
startActivity(intent);
break;
case R.id.discover_search:
intent.setClass(this, TopicSearchActivity.class);
startActivity(intent);
break;
case R.id.discover_rate:
intent.setClass(this, RateActivity.class);
startActivity(intent);
break;
case R.id.discover_oil:
intent.setClass(this, OilActivity.class);
startActivity(intent);
break;
case R.id.rl_twodimension_code:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
DialogUtil.getInstance().showPermissionDialog(this, "permission");
} else {
intent.setClass(DiscoverActivity.this, CaptureActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivityForResult(intent, 1);
}
} else {
intent.setClass(DiscoverActivity.this, CaptureActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivityForResult(intent, 1);
}
break;
case R.id.rl_activity:
intent.setClass(this, WebViewActivity.class);
intent.putExtra("url", url);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
break;
case R.id.rl_coupon:
intent.setClass(this, GroupBuyListActivity.class);
startActivity(intent);
break;
}
}
private void loadActivity() {
Map<String, String> mp = new HashMap<String, String>();
Okhttp.getIntance().post(Api.REAL_URL, Api.YORKBBS_CMS_TXTSETTING, mp, new StringCallback() {
#Override
public void onError(Call call, Exception e) {
}
#Override
public void onResponse(String response) {
if (!TextUtils.isEmpty(response)) {
String result = ParamUtils.ConvertData(response);
JsonObject jsonObject = new JsonParser().parse(result).getAsJsonObject();
if (jsonObject.has("list")) {
rl_activity.setVisibility(View.VISIBLE);
String list = jsonObject.get("list").toString();
List<Discoverac> listObj = new Gson().fromJson(list, new TypeToken<List<Discoverac>>() {
}.getType());
if (listObj != null && listObj.size() > 0) {
tvActivityTitle.setText(listObj.get(0).getTxt());
url = listObj.get(0).getUrl();
}
}
}
rl_activity.setVisibility(View.GONE);
}
});
}
private void check(String ticket) {
Map<String, String> mp = new HashMap<String, String>();
mp.put("sessionkey", ShareProUtils.getLoginSession(this));
mp.put("code", ticket);
mp.put("merchantid", ShareProUtils.getUid(this));
Okhttp.getIntance().post(Api.GROUPBUY_URL, Api.GROUPON_CHECK, mp, new StringCallback() {
#Override
public void onBefore(Request request) {
super.onBefore(request);
dialog = DialogUtil.getInstance().showLoadDialog(DiscoverActivity.this, "正在验证...");
}
#Override
public void onError(Call call, Exception e) {
}
#Override
public void onResponse(String response) {
if (!TextUtils.isEmpty(response)) {
String result = ParamUtils.ConvertData(response);
GrouponDetailResponse response1 = new Gson().fromJson(result,GrouponDetailResponse.class);
if (response1.getFlag().equals("0")){
Intent intent = new Intent(DiscoverActivity.this, TicketCheckSuccessActivity.class);
startActivity(intent);
}else {
Intent intent = new Intent(DiscoverActivity.this, TicketCheckFailActivity.class);
startActivity(intent);
}
} else {
TipsToast.show(DiscoverActivity.this, "error");
}
}
#Override
public void onAfter() {
DialogUtil.getInstance().dissMissDialog(dialog);
super.onAfter();
}
});
}
#Override
protected void onResume() {
super.onResume();
if (isNet()) {
loadActivity();
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK) {
if (requestCode == 1) {
Bundle bundle = data.getExtras();
String result = bundle.getString("result");
if (!TextUtils.isEmpty(result)) {
if (result.contains("code")) {
if (TextUtils.isEmpty(ShareProUtils.getUid(this))) {
Intent login = new Intent(this, LoginActivity.class);
startActivity(login);
return;
}
result = result.replaceAll("http://www.yorkbbs.ca\\?yorkbbscode=","");
check(result);
} else {
Intent intent = new Intent(this, WebViewActivity.class);
intent.putExtra("url", result);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
} else {
TipsToast.show(this, "scan error");
}
}
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
// NOTE: delegate the permission handling to generated method
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
// TODO Auto-generated method stub
return false;
}
}
TabActivity is now deprecated. To Create Tab you have to create it using Fragment and ViewPager.
Here is example to create Tab using Fragment and ViewPager .
see Exmaple here : http://www.truiton.com/2015/06/android-tabs-example-fragments-viewpager/