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.

DAO:

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

Entity:

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

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

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

ViewModel

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 {
            mLDQuestion.setValue(question);
        }
    }
}

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

public class LiveDataIntegerTypeConverter {

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

    @TypeConverter
    public static MutableLiveData<Integer> toObservable(int value) {
        MutableLiveData<Integer> liveData = new MutableLiveData<>();
        liveData.postValue(value);
        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

Code-

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() {
    super.viewDidLoad()

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

    collectionView.refreshControl = refreshControl
    self.extendedLayoutIncludesOpaqueBars = true

    fetchData()
}

var movieDays: [MoviesByScheduleByDay]? = []

fileprivate func fetchData() {

    let dispatchGroup = DispatchGroup()

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

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

    dispatchGroup.notify(queue: .main) {
        print("complete dispatch")
        self.collectionView.reloadData()
        self.collectionView.refreshControl?.endRefreshing()
    }
}

@objc func handleRefresh()    {
    fetchData()
}

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?

Typeface.create(Typeface.MONOSPACE,Typeface.NORMAL)

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)
                .requestServerAuthCode("MyCID")
                .build();

        mAuth = FirebaseAuth.getInstance();
        super.onCreate(savedInstanceState);
        final FirebaseAuth auth = FirebaseAuth.getInstance();
        AuthCredential credential = PlayGamesAuthProvider.getCredential("MyCID");
        auth.signInWithCredential(credential)
                .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.",
                                    Toast.LENGTH_SHORT).show();
                        }
                    }
                });
        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".

MyCID

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.setTitle("Uploading");
        progress.setMessage("Please wait...");
        progress.show();

        Thread t = new Thread(new Runnable() {
            @Override
            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()
                        .setType(MultipartBody.FORM)
//                        .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)
                        .build();
                okhttp3.Request request = new okhttp3.Request.Builder()
                        .url("https://abanob-read.000webhostapp.com/uplode.php")
                          .post(request_body2)
                        .build();

                try {

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

                    if(!response.isSuccessful()){
                        throw new IOException("Error : "+response);
                    }
                     else {
                         System.out.println("+++++result++++"+response);
                    }
                    progress.dismiss();

                } catch (IOException e) {
                    e.printStackTrace();
                    System.out.println("+++++result+8+++"+e.getLocalizedMessage());
                    System.out.println("+++++result+8+++"+e.getMessage());

                    progress.dismiss();

                }


            }
        });

        t.start();

    }

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?

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

    //#2
    val j1 = JSONObject() //org.json
    j1.put("foo", getBar())
    val jString1 = j1.toString()
    Log.d(TAG,jString1)


    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);
    navigationView.setNavigationItemSelectedListener(this);
    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);
    drawerLayout.addDrawerListener(toogle);
    toogle.setDrawerIndicatorEnabled(true);
    toogle.syncState();
    if(savedInstanceState == null) {
        getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
                new ArtFragment()).commit();
        navigationView.setCheckedItem(R.id.nav_art);
    }

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

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

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

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

                navUsername.setText(user.getUsername());
                navEmail.setText(user.getEmail());


                }

            }



        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {
        }
    });
}

Firebase json example:

users
   uid
     email: ""
     password:""
     username:""

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:

<xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:context="com.mkurbanov.lebap_kwartira.ScrollingActivity">

    <android.support.design.widget.AppBarLayout
        android:id="@+id/app_bar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:fitsSystemWindows="true"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.design.widget.CollapsingToolbarLayout
            android:id="@+id/toolbar_layout"
            android:layout_width="match_parent"
            android:layout_height="256dp"
            android:fitsSystemWindows="true"
            app:contentScrim="?attr/colorPrimary"
            app:layout_collapseMode="parallax"
            app:layout_scrollFlags="scroll|exitUntilCollapsed"
            app:titleEnabled="false">

            <com.daimajia.slider.library.SliderLayout
                android:id="@+id/header_slider"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:autofillHints="true"
                android:background="@color/colorPrimary"
                android:fitsSystemWindows="true"
                app:layout_collapseMode="parallax" />

            <android.support.v7.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                app:layout_collapseMode="pin"
                app:popupTheme="@style/AppTheme.PopupOverlay" />

        </android.support.design.widget.CollapsingToolbarLayout>
    </android.support.design.widget.AppBarLayout>


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

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="@dimen/fab_margin"
        android:src="@drawable/ic_share_black_48dp"
        android:tint="@color/colorPrimary"
        app:backgroundTint="@color/white"
        app:layout_anchor="@id/app_bar"
        app:layout_anchorGravity="bottom|end"
        app:rippleColor="@color/colorPrimary" />

    <Button
        android:id="@+id/button_call"
        android:layout_width="match_parent"
        android:layout_height="35dp"
        android:layout_alignParentBottom="true"
        android:layout_gravity="bottom|center"
        android:layout_margin="10dp"
        android:background="@drawable/btn_empty_solid"
        android:foreground="?attr/selectableItemBackground"
        android:paddingLeft="10dp"
        android:paddingRight="10dp"
        android:text="@string/call"
        android:textAppearance="?android:attr/textAppearanceSmall"
        android:textColor="@color/white"
        android:textSize="@dimen/text_size" />

</android.support.design.widget.CoordinatorLayout>

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)
bottom_navigation.inflateMenu(R.menu.bottom_navigation_menu)
bottom_navigation.setupWithNavController(navController)

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() {
            @Override
            public void run() {
                FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
                fragmentTransaction.replace(R.id.frame, fragment);
                fragmentTransaction.commitAllowingStateLoss();
            }
        };

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:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="@dimen/widget_margin"
    android:id="@+id/widget" >

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

<ImageView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/imageView_port"
    android:visibility="gone"
    android:layout_alignParentTop="true"
    android:layout_alignParentLeft="true"
    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.