I am using Room, ViewModel and two-way databinding. In this simple example I need to select data from database and validate it. If data are valid then expose it to databinding. In the other case I have to select other data from database.


public interface IDAOQuestion {
    @Query("SELECT * FROM Question WHERE questionId = :questionId")
    Question selectQuestion(long qeustionId);


public class Question {
    @PrimaryKey(autoGenerate = true)
    private long questionId;

    private MutableLiveData<Integer> correct = new MutableLiveData<>();

    public int getCorrectValue() {
        return correct.getValue() == null ? 0 : correct.getValue();


public class QuestionViewModel extends AndroidViewModel {
    public LiveData<Question> mLDQuestion = new MutableLiveData<>();

    public void getQuestion(int questionId) {
        //pseudo DAO access
        Question question = IDAOQuestion.selectQuestion(questionId);

        //here it is always true (question.getCorrectValue() returns 0)
        if(question.getCorrectValue() == 0) {
            getQuestion(questionId + 1);
        } else {

Also I have type converter to convert int from database to LiveData of entity.

public class LiveDataIntegerTypeConverter {

    public static int toInteger(LiveData<Integer> value) {
        if (value == null || value.getValue() == null) {
            return 0;
        } else {
            return value.getValue();

    public static MutableLiveData<Integer> toObservable(int value) {
        MutableLiveData<Integer> liveData = new MutableLiveData<>();
        return liveData;

In ViewModel in the function getQuestion I have some "validation". It dowsn't work right. the code question.getCorrectValue() always returns 0. It is because of using MutableLiveData.postValue in TypeConverter and not existing observer on the property.

As workaround I can create another entity (POJO class) without LiveData and use it for validation. After that I can reselect data or map it to "LiveData version" of object. But this seems to be crazy and too complicated. What is the right approach to solve this?

This is just simple example. The logic is just for illustration. I understand why this is happening. Also I can't solve this by changing my SELECT query. Also I have to use the live data on my attributes because I am using it with two way databinding with depending attributes.

Whenever I use any of the other regular simulator iPhones from the 5S - 8+ there are no problems, everything is fine, I touch a button and the action happens. I have an iPhone 7+ and the buttons work fine using the actual device.

But whenever I use the simulator and I choose any of the iPhone X series devices when I touch any button in any view controller I always get a crash

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[_UIBackButtonContainerView titleLabel]: unrecognized selector sent to instance 0x7fdd99c759e0'

whatever this is causes the problem in the X series [_UIBackButtonContainerView titleLabel]

I'm running Xcode in Debug Mode:

enter image description here

What could be the problem?

enter image description here


lazy var loginButton: UIButton = {
    let button = UIButton(type: .system)
    button.translatesAutoresizingMaskIntoConstraints = false
    button.setTitle("Login", for: .normal)
    button.setTitleColor(UIColor.white, for: .normal)
    button.titleLabel?.font = UIFont(name: "ArialRoundedMTBold", size: 19)
    // I also tried commenting out button.titleLabel?.font = UIFont(name: "ArialRoundedMTBold", size: 19)
    button.backgroundColor = UIColor.lightGray
    button.addTarget(self, action: #selector(loginButtonPressed), for: .touchUpInside)
    button.clipsToBounds = true
    button.layer.cornerRadius = 5

@objc func loginButtonPressed() {
    // do something

I'm currently having issues refreshing my collectionview feed using UIRefreshControl. The refresh works fine, however it duplicates the number of cells and continues to append more items to the movieDays array and sort of randomly rearranges the order of the items. I've also tried setting the array to nil each time it refreshes, but then I get a fatal error saying the indexPath is out of range. Does anyway know the correct way to set this up?

Thanks a lot

override func viewDidLoad() {

    let refreshControl = UIRefreshControl()
    refreshControl.addTarget(self, action: #selector(handleRefresh), for: .valueChanged)

    collectionView.refreshControl = refreshControl
    self.extendedLayoutIncludesOpaqueBars = true


var movieDays: [MoviesByScheduleByDay]? = []

fileprivate func fetchData() {

    let dispatchGroup = DispatchGroup()

    Service.shared.fetchMoviesBySchedule { (movieDays, err) in
        if let err = err    {
            print("Failed to fetch movies", err)
        self.movieDays = movieDays?.data

    Service.shared.fetchFeaturedMovies { (movies, err) in
        if let err = err    {
            print("Failed to fetch featured movies", err)
        self.headerMovies = movies?.data ?? []

    dispatchGroup.notify(queue: .main) {
        print("complete dispatch")

@objc func handleRefresh()    {

i'm only getting random even number for value 1 . i need it for both value 1 and 2. Can anyone teach me how to solve it?

i'm using threadlocalrandom for it

 public void setQuestion(){
    Random rand = new Random();
    int value1 = ThreadLocalRandom.current().nextInt(10,100);
    int value2 = ThreadLocalRandom.current().nextInt(2,20);

    int randomquestion = rand.nextInt(2);
 if (randomquestion == 1){
        question.setText("What is"+ value1 + "+" + value2 +" ? ");
        expected= "" + (value1 + value2);
    }else if (randomquestion == 2){
        question.setText("What is"+value1 +"-" + value2 +" ? ");
        expected="" + (value1 - value2);
    }else if (randomquestion == 3){
        question.setText("What is"+value1+ "*" + value2 +" ? ");
        expected ="" + (value1*value2);
    }else {
        question.setText("What is"+value1+"/" + value2 +"?");
        expected="" + (value1/value2);
    sumanswer.setText("Total Score ="+ correctanswer +"Correct and"+ wronganswer + "Wrong");

i expect it can be in random even number for both value

Im looking for an android c++ ide that I can use on Android with library support I want the ones that let you install any libraries you want and it has to be free as long as I can use any libraries that I want

you can also tell me a way to import libraries on any c++ ide

thats all

As you can see in the screenshot below the two different strings with the same length not drawn with the same width on the canvas. I'm using a monospaced typeface, so isn't it promised to be drawn with the same width? Is that because of the kerning?


enter image description here

I am creating a game for android. Each user needs to be authenticated.

Currently, when a new user launches the game, it requests an identification code from my server, and stores it to SharedPreferences. Next time user launches the game, it uses this stored identification code to authenticate. The problem is, when user clears data of this app, there's no way he can get his ID back, so he lost his progress forever.

Is there a way how to generate something like Identification code which is unique and always the same for one player using Firebase Play games auth method?

GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_GAMES_SIGN_IN)

        mAuth = FirebaseAuth.getInstance();
        final FirebaseAuth auth = FirebaseAuth.getInstance();
        AuthCredential credential = PlayGamesAuthProvider.getCredential("MyCID");
                .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                    public void onComplete(@NonNull Task<AuthResult> task) {
                        if (task.isSuccessful()) {
                            currentUser = auth.getCurrentUser();
                        } else {
                            Toast.makeText(MainActivity.this, "Authentication failed.",
        if (currentUser == null) {
            cu = "NO UID";
        } else {
            cu = currentUser.getUid();

I tried this code (Where is MyCID: I used the CID from the image below), but no Google Play Games pop-up is shown, I get Authentication Failed toast and cu is set to "NO UID".


Can someone explain how does this work please?

I've created a CV building app and the last Activity displays all the information in the form of ListViews. Each ListView has layout_height=wrap_content which means that once the user enters more than one previous job, the data falls off the screen and is unscrollable.

I've already tried to limit the space used by the ListView, making it's own data scrollable however this doesn't look right on the screen. I'd much prefer to have all data displayed and the whole screen scrollable. Any suggestions?

Also, I don't want the user to have to move across to other Activities to view the data they've entered.

How to create a notification that displays an entire view in the unlock menu before the user enters their code. As does the basic "Clock" app when an alarm sounds ?

I need to add dependency RESTMock, but I get this error in Gradle.

 project :app > com.github.andrzejchm.RESTMock:android:0.3.3 > com.github.andrzejchm.RESTMock:core:0.3.3 > com.squareup.okhttp3:okhttp-tls:3.13.1

but I use com.squareup.okhttp3:okhttp-tls:3.12.1 in project.

I need version 3.12.1 and RESTMock together, anyway can I have together?

When I upload a picture on the server by okhttp3 or retrofit2 it raises the image but the response is {protocol = h2, code = 200, message =, url = } or not Upload the image from the base and the response is {protocol = h2, code = 422, message = Is it a helper Thank you ......

    private void Registration(){
         final ProgressDialog progress = new ProgressDialog(this);
        progress.setMessage("Please wait...");

        Thread t = new Thread(new Runnable() {
            public void run() {

                String content_type  = getMimeType(f.getPath());
                String file_path = f.getAbsolutePath();
                OkHttpClient client = new OkHttpClient();
                RequestBody file_body = RequestBody.create(MediaType.parse(content_type),f);

                RequestBody request_body2 = new MultipartBody.Builder()
//                        .addFormDataPart("name", getText(name))
//                         .addFormDataPart("email", getText(email))
//                        .addFormDataPart("phone", getText(numberPhone))
//                        .addFormDataPart("password", getText(password))
//                        .addFormDataPart("password_confirmation",getText(password))
                        .addFormDataPart("uploaded_file",file_path.substring(file_path.lastIndexOf("/")+1), file_body)
                okhttp3.Request request = new okhttp3.Request.Builder()

                try {

                    okhttp3.Response response = client.newCall(request).execute();

                        throw new IOException("Error : "+response);
                     else {

                } catch (IOException e) {






Will #1 and #2 always produce the same output? What are the advantages of using one solution over the other one?

Solution #2 looks cleaner and simpler to me, is it faster also?

    val gson = Gson()
    val j = JsonObject() //com.google.gson
    j.add("foo", gson.fromJson(getBar(), JsonElement::class.java))
    val jString = gson.toJson(j)

    val j1 = JSONObject() //org.json
    j1.put("foo", getBar())
    val jString1 = j1.toString()

    fun getBar() : String {
        //do stuff and return a string

Thanks in advance

I try to retrieve data from firebase and setText to TextViews, but it does not work. I tried different methods. I get no error, the strings are not null, but the text does not display. I used these methods and in another projects and they worked. What am I doing wrong?

Here is the code:

drawerLayout = findViewById(R.id.drawer_layout);
    NavigationView navigationView = findViewById(R.id.nav_view);
    View headerView = navigationView.getHeaderView(0);
    navUsername = headerView.findViewById(R.id.navUsername);
    navEmail = headerView.findViewById(R.id.navEmail);

    ActionBarDrawerToggle toogle = new ActionBarDrawerToggle(this, drawerLayout, toolbar,
            R.string.navigation_drawer_open, R.string.navigation_drawer_close);
    if(savedInstanceState == null) {
                new ArtFragment()).commit();

    auth = FirebaseAuth.getInstance();
    currentUser = auth.getCurrentUser();
    String uid = currentUser.getUid();

    refUsername = FirebaseDatabase.getInstance().getReference().child("users").child(uid);

    refUsername.addListenerForSingleValueEvent(new ValueEventListener() {
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            if (dataSnapshot.exists()) {

                User user = dataSnapshot.getValue(User.class);




        public void onCancelled(@NonNull DatabaseError databaseError) {

Firebase json example:

     email: ""

This is User.class:

public class User {
String username, email, password;

public User(String username, String email, String password){
    this.username = username;
    this.email = email;
    this.password = password;
public User(){}

public void setUsername(){
    this.username = username;
public String getUsername(){
    return username;
public void setEmail(){
    this.email = email;
public String getEmail(){
    return email;
public void setPassword(){
    this.password = password;
public String getPassword(){
    return password;


Why OnClicklistener not working inside CollapsingToolbarLayout?

i use:

compile 'com.android.support:appcompat-v7:27.0.0'
compile 'com.android.support:design:27.0.0'
compile 'com.android.support:support-v4:27.0.0'

My Layout:




                app:layout_collapseMode="parallax" />

                app:popupTheme="@style/AppTheme.PopupOverlay" />


    <include layout="@layout/content_dug" />

        app:rippleColor="@color/colorPrimary" />

        android:textSize="@dimen/text_size" />


Some Words. Some Words. Some Words. Some Words. Some Words. Some Words. Some Words. Some Words. Some Words. Some Words. Some Words. Some Words. Some Words. Some Words. Some Words. Some Words. Some Words. Some Words. Some Words. Some Words. Some Words. Some Words. Some Words. Some Words.

I am working with navigation component and bottom navigation

val navController = indNavController(R.id.nav_host_fragment)

and I am facing the next issue:

When an item is selected in the bottom navigation, then a fragment is loaded. The problem comes when I press again the same item, then a new fragment will be loaded, which it does not make sense at all.

Example: 1- User selects menu item A, then FragmentA is loaded. 2- User selects again menu item A, then a new FragmentA will be loaded,

I was trying to use

bottom_navigation.setOnNavigationItemSelectedListener {  }

But then the bottom navigation will not work with the navController.

So the question is: there is a way to handle this situation in order to load again a new fragment when the user is in that screen already?

After I remove a marker from Google Map, using marker.remove(), I want to add the same marker again. I dont want to create MarkerOptions every time. Is there a simple way? though there should have been an intuitive way to do this simple thing.

The full stack includes only android core code:

java.lang.NullPointerException: Attempt to invoke virtual method 'boolean androidx.fragment.app.FragmentManagerImpl.isDestroyed()' on a null object reference
    at androidx.fragment.app.Fragment.performDetach(Fragment.java:2844)
    at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManagerImpl.java:1033)
    at androidx.fragment.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManagerImpl.java:1237)
    at androidx.fragment.app.BackStackRecord.executeOps(BackStackRecord.java:434)
    at androidx.fragment.app.FragmentManagerImpl.executeOps(FragmentManagerImpl.java:2075)
    at androidx.fragment.app.FragmentManagerImpl.executeOpsTogether(FragmentManagerImpl.java:1865)
    at androidx.fragment.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManagerImpl.java:1820)
    at androidx.fragment.app.FragmentManagerImpl.execPendingActions(FragmentManagerImpl.java:1726)
    at androidx.fragment.app.FragmentManagerImpl$2.run(FragmentManagerImpl.java:150)
    at android.os.Handler.handleCallback(Handler.java:873)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loop(Looper.java:193)
    at android.app.ActivityThread.main(ActivityThread.java:6669)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)

It happens when replacing the fragment in main activity:

Runnable mPendingRunnable = new Runnable() {
            public void run() {
                FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
                fragmentTransaction.replace(R.id.frame, fragment);

I want to know how to design software which have modules which can be enabled or disabled. I have been developing software like HRMS,etc, but my approach is mostly structural and just event driven code blocks. I want to learn how to write modular easily editable code. I have read the design patterns book but am confused as to which pattern should be used in which situation. Now i understand illustrator is mega complex but my question is regarding the modular design of the software not the specialized application of illustrator. You can replace illustrator with corel etc. but all of them have a contextual modular design. how do i begin to write some software like those?

I am currently building a web api. The authentication is based on keys which are set in the database.

However, these keys could be changed someday, e.g. when a user should be banned from the system. Currently the data is read once on startup of the server/application.

My question is, how I can reset this data without the need to restart the application?

The data itself is a private backing-field which is only initialized when not set (as on startup). I now want to reset the data by just setting the data to null which will reload it from the database on the next call/access.

What would be the correct method in terms of REST?

As far as I have understood, none of the methods are "correct" as I don't create, update or delete a resource.

For me DELETE would be the choice as I delete the internal data.

Any thoughts?

That seems like a stupid question, but I can't find a proper name for "code that tests another code". The most of literature names that kind of code just "tests" but it's way to general in my understanding (obviously I am not an English native speaker so I might be wrong) - code might be tested by people, some external machine that is not "code" at all. The same applies to "code tests".

I was thinking about "testing code" but this seems to be a bit confusing as it looks more like a verb than noun.

Since I'm not quite sure when, I'm getting a lint warning when viewing my layout file of "Unknown attribute android:padding"...

The layout file starts:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/widget" >

I'm getting similar warnings for android:layout_alignParentTop etc in the following:

    android:layout_alignParentStart="true" />

Furthermore, I'm finding now that when an image is loaded into the ImageView that is the correct aspect ratio but not the right pixel size (smaller), the image is being shown in the ImageView at its actual (too small) size rather than being stretched out to fit the ImageView (like it used to do, and like I want it to do).

I'm not sure when these warnings started to appear. And I'm confused because it appears that at least android:padding is still a valid attribute according to the docs.

Other warnings I'm getting include for android:tag... which is also a pretty basic attribute and still "legal" according to the above docs.