Question Disable context menu Xiaomi MIUI - Xiaomi Mi 11

Hello! I need to disable the context menu of Xiaomi MIUI, because I made my own context menu. But the following standard solution doesn't work:
edt.setCustomSelectionActionModeCallback(new EmptyActionMode());
class EmptyActionMode implements ActionMode.Callback {
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
menu.clear();
return false;
}
public void onDestroyActionMode(ActionMode mode) { }
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
menu.clear();
return false;
}
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
return false;
}
}
Click to expand...
Click to collapse
How can I remove this context menu?

Related

[Q] Logging data from function

Hey.
I am not entirely sure how to log data from a function.
I am trying to log the accessed URL from the first of the 3 functions in the code pasted below.
I have found the method, but I don't know if It is possible to log the output
Code:
Method - name = HttpConnector.java:
package dk.inlogic.app.res;
private static String getAction(Context context, String action, String version) {
try {
String result = getURLaction(context, action, PreferenceConnector.readString(context, PreferenceConnector.USERNAME, ""), PreferenceConnector.readString(context, PreferenceConnector.PASSWORD, ""), version);
if (result != null) {
return result;
}
} catch (Exception e) {
Log.e("HttpConnector getAction Exception", "action = " + action + ", version = " + version + ", " + e.toString());
}
return "";
}
public static String getTimetable(Context context) {
return getAction(context, "timetable", "2");
}
File 2 - Name, TimetableFragment.java:
package dk.inlogic.app.timetable;
protected String doInBackground(String... args) {
try {
Log.i("TimetableFragment ProgressTask doInBackground", "check for new file");
if (AppInfo.instance().isLive() && HttpConnector.getUpdateNowIfOld("rss2.xml")) {
Log.i("TimetableFragment ProgressTask doInBackground", "Get new file");
saveFile(HttpConnector.getTimetable(this.context));
return "";
} else {
if (!AppInfo.instance().isLive()) {
new DemoDownloadThread(TimetableFragment.this.getActivity()).start();
}
return "";
}
} catch (Exception e) {
Log.e("TimetableFragment doInBackground Exception", e.toString());
}
}
If by "output" you mean result, then you can use param.getResult.
If that's not it, I don't understand what you're trying to do.

Erroe

i work with this guild: Android Uploading Camera Image, Video to Server with Progress Bar
and when i take image i got this error:
Unable to decode stream: java.io.FileNotFoundException: /storage/emulated/0/Pictures/profile_imagephoto.jpg: open failed: ENOENT (No such file or directory
What can i do to fix this?
Code:
//Upload Profile Image
profileImage.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v) {
pictureCheck = "to_profile";
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setIcon(R.drawable.ic_action_search);
builder.setMessage("Select What To Do:")
// Positive button functionality
.setPositiveButton("Camera",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int arg0) {
Toast.makeText(MainActivity.this, "Open Camera...", Toast.LENGTH_SHORT).show();
Intent cameraintent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraintent, IMAGE_CAPTURE);
}
})
// Negative button functionality
.setNegativeButton("Gallery",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int arg0) {
Toast.makeText(
MainActivity.this, "Open Gallery...", Toast.LENGTH_SHORT).show();
// Do more stuffs
Intent galleryIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
//dialog.cancel();
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
galleryIntent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
startActivityForResult(galleryIntent, RESULT_LOAD_INAGE);
}
});
// Create the Alert Dialog
AlertDialog alertdialog = builder.create();
// Show Alert Dialog
alertdialog.show();
}
});
/**
* Here we store the file url as it will be null after returning from camera
* app
*/
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
// save file url in bundle as it will be null on screen orientation
// changes
outState.putParcelable("file_uri", fileUri);
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
// get the file url
fileUri = savedInstanceState.getParcelable("file_uri");
}
@Override
public void onActivityResult(int requestCodeToProfile, int resultCodeToProfile, Intent dataToProfile) {
super.onActivityResult(requestCodeToProfile, resultCodeToProfile, dataToProfile);
launchUploadActivity(true);
}
private void launchUploadActivity(boolean isImage){
Intent i = new Intent(MainActivity.this, UploadActivity.class);
i.putExtra("filePath", fileUri.getPath());
i.putExtra("isImage", isImage);
startActivity(i);
}
/**
* Creating file uri to store image/video
*/
public Uri getOutputMediaFileUri(int type) {
return Uri.fromFile(getOutputMediaFile(type));
}
/**
* returning image / video
*/
private static File getOutputMediaFile(int type) {
// External sdcard location
File mediaStorageDir =
new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
"profile_image");
// Create the storage directory if it does not exist
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d(TAG, "Oops! Failed create "
+ "profile_image" + " directory");
return null;
}
}
// Create a media file name
java.util.Date date= new java.util.Date();
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
Locale.getDefault()).format(date.getTime());
File mediaFile;
if (type == MEDIA_TYPE_IMAGE) {
mediaFile = new File(mediaStorageDir.getPath() + "photo.jpg");
} else if (type == MEDIA_TYPE_VIDEO) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator
+ "VID_" + timeStamp + ".mp4");
} else {
return null;
}
return mediaFile;
}
This is a long shot, but the path of your image looks wrong. Are you missing a slash between the last dir and 'photo.jpg'. Should be this line:
mediaFile = new File(mediaStorageDir.getPath() + "photo.jpg");

Thread crash on start itself

I am trying to create a thread in an android application to keep checking my firebase database to check if an otp value has been put in the child value of a node. But it keeps crashing as soon as I start the application. This is my code so far.
//Thread check otp
Thread t = new Thread() {
@override
public void run() {
while(!isInterrupted()) {
try {
Thread.sleep(5000);
runOnUiThread(new Runnable() {
@override
public void run() {
//check OTP if present on database
FirebaseDatabase.getInstance().getReference().child("Keys")
.addListenerForSingleValueEvent(new ValueEventListener() {
@override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
Subjects keys = snapshot.getValue(Subjects.class);
//System.out.println(user.email);
Intent i = new Intent(getApplicationContext(), markAttendance.class);
i.putExtra("otp",keys.otpcode);
i.putExtra("subid", keys.subjectId);
finish();
startActivity(i);
}
}
@override
public void onCancelled(DatabaseError databaseError) {
}
});
}
});
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
};
t.start();
Any help is much appreciated. Thnx in advance
To keep checking my firebase database to check if an otp value has been put
Click to expand...
Click to collapse
You don't need to create a background thread to do that, firebase listeners (and almost all operations, if not all of them) already run in a separated thread. You can safely register your ValueEventListener somewhere and let it there.
PS. You didn't post the logcat nor the structure of your database, so I can not help much about the crash.
pauljose97 said:
I am trying to create a thread in an android application to keep checking my firebase database to check if an otp value has been put in the child value of a node. But it keeps crashing as soon as I start the application. This is my code so far.
Code:
//Thread check otp
Thread t = new Thread() {
public void run() {
while(!isInterrupted()) {
try {
Thread.sleep(5000);
runOnUiThread(new Runnable() {
public void run() {
//check OTP if present on database
FirebaseDatabase.getInstance().getReference().child("Keys")
.addListenerForSingleValueEvent(new ValueEventListener() {
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
Subjects keys = snapshot.getValue(Subjects.class);
//System.out.println(user.email);
Intent i = new Intent(getApplicationContext(), markAttendance.class);
i.putExtra("otp",keys.otpcode);
i.putExtra("subid", keys.subjectId);
finish();
startActivity(i);
}
}
public void onCancelled(DatabaseError databaseError) {
}
});
}
});
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
};
t.start();
Any help is much appreciated. Thnx in advance
Click to expand...
Click to collapse
Starting using adb logcat to see why your app is crashing. If I had to start a thread, I would create an async background task instead
Code:
AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... params) {
while(!isInterrupted()) {
try {
Thread.sleep(5000);
runOnUiThread(new Runnable() {
public void run() {
//check OTP if present on database
FirebaseDatabase.getInstance().getReference().child("Keys")
.addListenerForSingleValueEvent(new ValueEventListener() {
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
Subjects keys = snapshot.getValue(Subjects.class);
//System.out.println(user.email);
Intent i = new Intent(getApplicationContext(), markAttendance.class);
i.putExtra("otp",keys.otpcode);
i.putExtra("subid", keys.subjectId);
finish();
startActivity(i);
}
}
public void onCancelled(DatabaseError databaseError) {
}
});
}
});
} catch (InterruptedException e) {
e.printStackTrace();
}
return null;
}
}
};
task.execute();

WebApp + sql. Can't make sql to work.

Hey guys.
So, I've spent the last two days watching every tutorial about working with sqlite, but I'm doing something wrong and can't find out what.
The app is done, only needs the SQLite part, Its basicly a webapp with favorites.
Altough I have changed the code several times, this is what I ended up with:
DBManager.java
<code>
package com.rjpf.mywebapps;
import android.content.ContentValues;
import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
public class DBManager
{
private DbHelper dbHelper;
private Context context;
private SQLiteDatabase database;
public DBManager(Context c)
{
context=c;
}
public DBManager open() throws SQLException
{
dbHelper = new DbHelper(context);
database = dbHelper.getWritableDatabase();
return this;
}
public void close()
{
dbHelper.close();
}
public void insert(String name, String url)
{
ContentValues contentValue = new ContentValues();
contentValue.put(DbHelper.CONTACTS_COLUMN_NAME, name);
contentValue.put(DbHelper.CONTACTS_COLUMN_URL, url);
database.insert(dbHelper.CONTACTS_TABLE_NAME, null, contentValue);
}
}
</code>
When I try to call it in the main activity with:
MainActivity.java
<code>
(...)
private LinearLayout Layout_Add;
private TextView TxT_add_nomE;
private TextView TxT_add_urL;
private Button Button_Add_to_DB;
private Button btn_BACK_Add;
DbHelper myDB;
(...)
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
myDB = new DbHelper(this);
(...)
Button_Add_to_DB.setOnClickListener(new View.OnClickListener() {
@override
public void onClick(View view) {
Add_ItemToDb();
}
});
(...)
public void Add_ItemToDb()
{
if (TxT_add_nomE.getText().toString().trim().length() == 0 || TxT_add_urL.getText().toString().trim().length() == 0)
{
TxT_add_nomE.setText("Please don't leave fields empty!");
return;
}
else
{
String addNome = TxT_add_nomE.getText().toString();
String addUrl = TxT_add_urL.getText().toString();
// ADD TO DB
DBManager DataManager = new DBManager(this);
DataManager.insert(addNome,addUrl); // This line is what gives the error, when I click the button to add the App craches
TxT_add_nomE.setText("Name");
TxT_add_urL.setText("Url");
}
}
</code>
Thanks in advance and sorry for the long post, This is my first app and also the first time in java

Android Don't execute anything until location variable exists

Goodmorning, I've tried to implement the method that request permission first and than execute something but without success ...
Here is my MainActivity code:
Code:
public class MainActivity extends AppCompatActivity {
public static String latitudineCorrente = ""; //current Latitude
public static String longitudineCorrente = ""; //current Longitude
private SharedPreferences sharedPreferences; //shared preferences
private SharedPreferences.Editor mEditor; // shared preferences editor
/* Variable for getting location */
private FusedLocationProviderClient fusedLocationProviderClient;
private LocationRequest locationRequest;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String appLanguage = "ita";
LanguageUtil.setAppLanguage(getApplicationContext(), appLanguage);
/* .... other code.... */
sharedPreferences = this.getSharedPreferences("appname", MODE_PRIVATE);
mEditor = sharedPreferences.edit(); // set edit sharedpreferences
richiamaPermessi(); //permission request
requestLocationUpdates(); // function requestlocationupdates();
CaricamentoInizialeApplicazione(); // function for presetting configurations
}
private void CaricamentoInizialeApplicazione() {
boolean configIniziale = sharedPreferences.getBoolean("configurazioneinizialeok", false);
if(!configIniziale)
{
/* can't execute this because Double.parseDouble(this.latitudineCorrente), Double.parseDouble(this.longitudineCorrente) */
ApiMarkers.getMarkers(MainActivity.this, 0, 400,
Double.parseDouble(this.latitudineCorrente), Double.parseDouble(this.longitudineCorrente),
0, 0,0,1, 0,0,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
/* response elaborations */
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
dialog.dismiss();
Toast.makeText(MainActivity.this, "" + error.getMessage(), Toast.LENGTH_LONG).show();
error.printStackTrace();
}
});
mEditor.putBoolean("configurazioneinizialeok", true);
mEditor.commit();
}
}
/* Function for requist location updates */
public void requestLocationUpdates() {
if(ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) ==
PermissionChecker.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) ==
PermissionChecker.PERMISSION_GRANTED) {
fusedLocationProviderClient = new FusedLocationProviderClient(this);
locationRequest = new LocationRequest();
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locationRequest.setFastestInterval(1500);
locationRequest.setInterval(3000);
fusedLocationProviderClient.requestLocationUpdates(locationRequest, new LocationCallback() {
@Override
public void onLocationResult(LocationResult locationResult) {
super.onLocationResult(locationResult);
mEditor = sharedPreferences.edit();
mEditor.putString("latitudine", String.valueOf(locationResult.getLastLocation().getLatitude()));
mEditor.putString("longitudine", String.valueOf(locationResult.getLastLocation().getLongitude()));
MainActivity.latitudineCorrente = String.valueOf(locationResult.getLastLocation().getLatitude());
MainActivity.longitudineCorrente = String.valueOf(locationResult.getLastLocation().getLongitude());
Log.d("coordinate", "MAIN ACTIVITY: Latitudine: " + MainActivity.latitudineCorrente + "/"
+ "Longitudine: " + MainActivity.longitudineCorrente);
}
}, getMainLooper());
} else richiamaPermessi();
}
/* Function for requesting access */
public void richiamaPermessi()
{
Permissions.check(this, new String[] { Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.ACCESS_FINE_LOCATION},
"Permessi di locazione obbligatori per determinare la propria posizione!",
new Permissions.Options().setSettingsDialogTitle("Avviso").setRationaleDialogTitle("Permessi locazione"),
new PermissionHandler() {
@Override
public void onGranted() {
requestLocationUpdates();
}
@Override
public void onDenied(Context context, ArrayList<String> deniedPermissions) {
super.onDenied(context, deniedPermissions);
richiamaPermessi();
}
});
}
}
The problem is executing function ApiMarkers.getMarkers(.... with latitude and longitude filled ...) but can't execute because latitude and longitude are not loaded... I spent two nights without solution Thanks for any help! Cristian
Up! I tried to follow this video on youtube youtube.com/watch?v=gEcFf2Mv4L0 and in any case I could not understand where or when I can call the method "CaricamentoInizialeApplicazione ()" in order to call a method that uses the location coordinates! What I want is to make sure that I don't call the method already said until the location coordinates are loaded into the variables indicated in the code! Is it possible that someone is not able to solve the problem? Thank you
Oh thanks for any help!

Categories

Resources