I'm trying to get text from db then update text in my textView of recyclerView adapter class . Although I'm getting text from db without any problem but my textview is not updating text everytime . Sometimes it's updating and sometimes it's not I wonder what's the problem . I tried to refer a lot of SO questions but none of them could solve my issue . I even tried to use textView.invalidate() but it was of no use . Could anyone please help me to solve this issue.
Code:
#Override
public void onBindViewHolder( CustomRecyclerViewHolder holder, int position) {
JSONObject ov=new JSONObject();
try {
ov.put("prof_email",timelineData.getEmail());
socket.disconnect();
socket.connect();
socket.emit("data",ov);
socket.on("name_full", new Emitter.Listener() {
#Override
public void call(Object... args) {
final JSONObject ob = (JSONObject)args[0];
try {
final String st = ob.getString("fullname");
Needle.onMainThread().execute(new Runnable() {
#Override
public void run() {
if (st.length() > 0) {
//I'm toasting just to test that text is alright or not but it's alright
Toast.makeText(context,st,Toast.LENGTH_SHORT).show();
holder.userName.invalidate();//here not useful
holder.userName.setText(st);
holder.userName.invalidate();//even here also not useful
socket.disconnect();
}
}
});
}catch (Exception e){
e.printStackTrace();
}
}
});
} catch (JSONException e) {
e.printStackTrace();
}
}
OnBindViewHolder will be called every time when user scroll the recyclerview.
So corresponding to your source code, socket connection and disconnection is done many times when user scroll the list. (This seems not a good way)
So I recommend to remove socket related code from onBindViewHolder.
After that just listening to the socket. When data changed, replace old data with new one from your collection and call Adapter#notifyDatasetChanged().
I am trying billow Code from this answer to check if the permission is enabled. but it is returning false even when the permission is enabled from the settings.
public static boolean canDrawOverlayViews(Context con){
if(Build.VERSION.SDK_INT< Build.VERSION_CODES.LOLLIPOP){return true;}
try {
return Settings.canDrawOverlays(con);
}
catch(NoSuchMethodError e){
return canDrawOverlaysUsingReflection(con);
}
}
public static boolean canDrawOverlaysUsingReflection(Context context) {
try {
AppOpsManager manager = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE);
Class clazz = AppOpsManager.class;
Method dispatchMethod = clazz.getMethod("checkOp", new Class[] { int.class, int.class, String.class });
//AppOpsManager.OP_SYSTEM_ALERT_WINDOW = 24
int mode = (Integer) dispatchMethod.invoke(manager, new Object[] { 24, Binder.getCallingUid(), context.getApplicationContext().getPackageName() });
return AppOpsManager.MODE_ALLOWED == mode;
} catch (Exception e) { return false; }
}
Recently I've also faced the same issue and got the following workaround .
Referenced from
https://code.google.com/p/android/issues/detail?id=198671#c7
public boolean getWindoOverLayAddedOrNot2() {
String sClassName = "android.provider.Settings";
try {
Class classToInvestigate = Class.forName(sClassName);
if (context == null)
context = activity;
Method method = classToInvestigate.getDeclaredMethod("isCallingPackageAllowedToDrawOverlays", Context.class, int.class, String.class, boolean.class);
Object value = method.invoke(null, context, Process.myUid(), context.getPackageName(), false);
Log.i("Tag", value.toString());
// Dynamically do stuff with this class
// List constructors, fields, methods, etc.
} catch (ClassNotFoundException e) {
// Class not found!
} catch (Exception e) {
// Unknown exception
e.printStackTrace();
}
return false;
}
does the check involves the device admin?
I have encountered this problem when disabling device admin, I have checked this permission in the DeviceAdminReceiver->onDisabled() and on some devices, and canDrawOverlays returned false, despite the fact i had the permission.
The above answer helped sometimes but not all the time. the thing that did work is Thread.sleep before the check.
try {
Thread.sleep(20);
} catch (InterruptedException e) {
// some exception here
}
The minimal time that worked for me was 20 millis. than canDrawOverlays returned true
Note: this is not a good practice however this is the only thing that worked for me
Based on BennyP's answer, I've made a Runnable run the required code after 500ms and that worked very well. The feedback is a bit delayed, but the user won't even notice the delay.
This is the code I've added to my onResume()
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
if(!Settings.canDrawOverlays(ControllerActivity.this)){
//Handle overlay permission not given here
}
else{
//Handle overlay permission given here
}
}
}, 500);
Hope it helps!
I tried restarting the activity after the user accessed the setting . This is code :
public static void restartActivity(Activity act){
Intent intent = getIntent();
finish();
startActivity(intent);
}
First of all, I am really very surprised with this strange behaviour of
Settings.canDrawOverlays(this);
I also faced the same issue with its usage, it was returning false even if the permission is already assigned.
What I noticed that, I was using this check in my onStart() method, where it was creating this wired behavior. To resolve this, I searched over internet and no result was there that can satisfy me and the one I can use.
Solution
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
Log.e("Overlay Permission", "" + Settings.canDrawOverlays(this));
if (!Settings.canDrawOverlays(this)) {
MyPreferences.saveBoolean(HomeScreen.this, "showOverlayPermissionDialog", true);
} else {
MyPreferences.saveBoolean(HomeScreen.this, "showOverlayPermissionDialog", false);
}
}
I did something lake this, in my onCreate(). Here I saved the values accordingly in my SharedPreferences, and according to these Shared Preference values, I created a check for showing an overlay dialog in my onStart(). This worked fine!
You can try this solution, and mark this answer useful if your problem is solved.
Thanks
Im making an apps that mock location and executing set ALLOW_MOCK_LOCATION turned on and off on runtime, so i hopes the other apps which detecting the ALLOW_MOCK_LOCATION flag will never get the ALLOW_MOCK_LOCATION as 1(true).
I read from here that it was possible and said to be fast enough, so other apps can hardly detect the change of ALLOW_MOCK_LOCATION. But what i am get is the other apps still sometimes reed ALLOW_MOCK_LOCATION as 1(true).
Please note that my devices already rooted and i can confirm it does mocked the location well. I also tried move it into /system/app, but still also encounter this problem.
This is the periodical loop which dispatch a asyntask with timeout(I even set the timeout 3 millis !!).
while(RUNNING){
fakeLocation.setAltitude(65.0);
fakeLocation.setAccuracy(Criteria.ACCURACY_FINE);
fakeLocation.setSpeed(0.0f);
fakeLocation.setTime(System.currentTimeMillis());
if(Build.VERSION.SDK_INT > Build.VERSION_CODES.JELLY_BEAN) {
fakeLocation.setElapsedRealtimeNanos(SystemClock.elapsedRealtimeNanos());
if(locationJellyBeanFixMethod!=null){
try {
locationJellyBeanFixMethod.invoke(fakeLocation);
}catch(Exception ex){}
}
}
new Thread(new Runnable() {
#Override
public void run() {
try {
new MockTask().execute().get(3, TimeUnit.MILLISECONDS);
}catch(TimeoutException e){
changeMockLocationSettings(0);
//Log.d(GLOBAL_VAR.TAG_DEBUG,"Mock location timeout:");
}catch(Exception e){}
}
}).start();
try {Thread.sleep(1500);} catch (InterruptedException e) {}
}
Below is the Asyntask
private class MockTask extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... param) {
try {
changeMockLocationSettings(1);
locationManager.setTestProviderLocation(GLOBAL_VAR.PROVIDER_NAME, fakeLocation);
changeMockLocationSettings(0);
//Log.d(GLOBAL_VAR.TAG_DEBUG,"location mocked -> "+fakeLocation);
} catch (Exception ex) {
//Log.d(GLOBAL_VAR.TAG_DEBUG,"Failed to mock location:"+ex.toString());
}
return null;
}
#Override
protected void onPostExecute(Void loc) {}
}
And lastly, the method to change ALLOW_MOCK_LOCATION
private boolean changeMockLocationSettings(int value) {
try {
return Settings.Secure.putInt(getApplicationContext().getContentResolver(),Settings.Secure.ALLOW_MOCK_LOCATION, value);
} catch (Exception e) {
Log.d(GLOBAL_VAR.TAG_DEBUG,"Setting allow mock location to "+value+" failed :"+e.toString());
e.printStackTrace();
return false;
}
}
Please help and correct me, and even suggest a better solution if any, and thanks in Advance
public String newUser = "false";
public double lat = 0.0, lon = 0.0;
I have the following function in my android app (called when a Button is clicked) which starts a thread:
public void SignUpFunction(View view) {
assignValues();
String filledAll = checkIfFilled();
if (filledAll.equals("true")) {
Log.d("LIFECYCLE", "calling thread..");
//my thread
new validateThread().start();
Log.d("After thread start","This log call does not occur");
if (newUser.equals("true")) {
Toast.makeText(this, "Please wait as we obtain your location", Toast.LENGTH_SHORT).show();
getMyLocationFunction();
} else {
return;
}
}
}
validateThread:
class validateThread extends Thread {
public void run() {
Log.d("LIFECYCLE", "validateThread entered...");
try {
newUser = "true";
Log.d("validateThread", "Validated and found new user");
} catch (Exception e) {
Log.d("validateThread", "Exception in validateThread: " + e.getMessage());
}
}
}
The thread runs correctly...but after the last line, it does not go back to its point of start. I don't understand why this is happening because I've used threads before and they all work correctly.
I know I can just give the getMyLocation function inside the thread but I really need it this way.
I've searched for similar questions but none helped.. What am I doing wrong here?
Thanks in advance.
It's a race. SignUpFunction should wait until validateThread decides whether or not to set newUser = "true". Even with the race your code may work sometimes, but that is by accident.
im trying to make bluetooth connection from android to NXT LeJos Droid. It works fine in other project, but when i need it for another project , it doesnt want to resolved the getSingleton()
public void onConnectionClicked(View view) {
boolean on = ((ToggleButton) view).isChecked();
// turning it on just sets the flag
if(on) {
conn = MainActivity.connect(CASE_TYPE.LEGO_LCP);
NXTCommand.getSingleton().setNXTComm(conn.getNXTComm());
NXTInfo info = conn.getNXTInfo();
if (info.connectionState== NXTConnectionState.LCP_CONNECTED)
{
isConnected = true;
}
}
// turning it off captures one more frame and starts processing
if(!on) {
try {
conn.getNXTComm().close();
} catch (Exception e) {} finally {
conn = null;
}
}
}
it said unresolved
i tried to fix it by checking the permission and library. I even change attached source inside lejos.nxt.remote.NXTCommand to the path where pccomm.jar located , but it doesnt work. I'd tried clean project .
is there any other way to fix this?