Categories
discuss

Firebase Realtime Database Update Data – Android Java

I’m making an edit page for the user profile in Firebase. I’ve tried a few different ways. But I could not update. Just a added as a new user to the database.

I am getting new values in the Alert Dialog. Please help me.

My Update Method Code’s :

public void editAlert() {
        LayoutInflater layoutInflater = LayoutInflater.from(ProfilePage.this);

        View design = layoutInflater.inflate(R.layout.edit_profile, null);

        final EditText editTextUserName = design.findViewById(R.id.username_editTextProfileEdit);

        final EditText editTextRealName = design.findViewById(R.id.realName_editTextProfileEdit);

        final EditText editTextSurname = design.findViewById(R.id.username_editTextProfileEdit);

        final EditText editTextEmail = design.findViewById(R.id.email_editTextProfileEdit);

        final EditText editTextPassword = design.findViewById(R.id.password_editTextProfileEdit);


        AlertDialog.Builder alertDialoga = new AlertDialog.Builder(ProfilePage.this);
        alertDialoga.setTitle("Edit Profile");
        alertDialoga.setView(design);
        alertDialoga.setPositiveButton("Finish", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                String username = editTextUserName.getText().toString().trim();
                String realName = editTextRealName.getText().toString().trim();
                String surname = editTextSurname.getText().toString().trim();
                String email = editTextEmail.getText().toString().trim();
                String password = editTextPassword.getText().toString().trim();
                String admin = "false";
                String url = "test_url";


                String key = myRef.push().getKey();

                Users user = new Users(key,username,realName,surname,email,password,url,admin);


                HashMap<String,Object> data = new HashMap<>();

                data.put("user_email", email);
                data.put("user_name", realName);
                data.put("user_password", password);
                data.put("user_surname", surname);
                data.put("username", username);

                myRef.child(user.getUser_id()).updateChildren(data);

                Toast.makeText(ProfilePage.this, "Uptaded!", Toast.LENGTH_SHORT).show();
            }
        });

        alertDialoga.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {

            }
        });

        alertDialoga.show();
    }

My Create User Code’s :

  // Sign Up Method
    // Kullanıcı Kayıt etme metodu
    public void signUp(View view) {
        UUID uuid = UUID.randomUUID();
        final String imageName = "ProfileImages/"+uuid+".jpg";
        final ProgressDialog dialog = new ProgressDialog(signupPage.this);
        dialog.setTitle("Creating user record.. ");
        dialog.setMessage("User registration is in progress..");
        dialog.show();
        StorageReference storageReference = mStorageRef.child(imageName);
        storageReference.putFile(image).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
            @Override
            public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                // Url

                StorageReference newReference = FirebaseStorage.getInstance().getReference(imageName);
                newReference.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
                    @Override
                    public void onSuccess(Uri uri) {

                        dowloadURL = uri.toString();

                        if (dowloadURL != null) {
                            mAuth.createUserWithEmailAndPassword(emailText.getText().toString(), passwordText.getText().toString())
                                    .addOnCompleteListener(signupPage.this, new OnCompleteListener<AuthResult>() {
                                        @Override
                                        public void onComplete(@NonNull Task<AuthResult> task) {
                                            if (task.isSuccessful()) /* Kullanıcı girişi başarılı ise bu çalışacak */ {
                                                Toast.makeText(signupPage.this, "User Created", Toast.LENGTH_SHORT).show();
                                                String userName = user_name.getText().toString();
                                                String userSurname = user_surname.getText().toString();
                                                String username = user_username.getText().toString();
                                                String user_email = emailText.getText().toString();
                                                String key = myRef.push().getKey();
                                                String password = user_password.getText().toString();
                                                String imageURL = dowloadURL;

                                                Users user = new Users(key, userName, username, userSurname, user_email, password,imageURL, admin);
                                                myRef.push().setValue(user);
                                                Intent homePage = new Intent(signupPage.this, ProfilePage.class);
                                                startActivity(homePage);
                                                finish();
                                                dialog.dismiss();

                                            } else /* Kullanıcı girişi başarısız ise bu çalışacak */ {
                                               /*Intent signBack = new Intent(signupPage.this, signupPage.class);
                                                startActivity(signBack);
                                                finish(); */
                                                dialog.dismiss();
                                            }



                                        }
                                    }).addOnFailureListener(signupPage.this, new OnFailureListener() {
                                @Override
                                public void onFailure(@NonNull Exception e) {
                                    Toast.makeText(signupPage.this, e.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
                                }
                            });
                        }


                    }
                });


            }
        }).addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                Toast.makeText(signupPage.this, e.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
            }
        });


    }

The download url comes from a separate image selection method, by the way. My user creation codes are like this.

Answer

Your problem is that instead of storing a constant and valid key in your firebase database, every time you change your profile you create a new node. How so? Well, you do this:

String key = myRef.push().getKey();

Which every time creates a new node(that is why the push is there) and you get the key of that node. That is also why you create a new user, instead of updating your account profile. The correct way to do it is the following.

When creating your user get the key with this:

String key = FirebaseAuth.getInstance().getCurrentUser().getUid();

After you create your User Object with this key, do the following:

myRef.child(key).setValue(user);

When you want to update your user, you can access the key the same way you created it. After getting all the update information and the key, then do:

myRef.child(key).setValue(data); //For updating

or

myRef.child(key).updateChildren(data); //For updating
Categories
discuss

Find all the same numbers in the array

I have an array with numbers in the range of 0 – 100. I need to find all the same numbers and add 1 to them.

my code worked well with arrays like [100, 2, 1, 1, 0]

const findAndChangeDuplicates = (arr: any) => {
    for (let i = arr.length - 1; i >= 0; i--) {
        if (arr[i + 1] === arr[i] && arr[i] <= 5) {
            arr[i] += 1;
        } else if (arr[i - 1] === arr[i] && arr[i] >= 5) {
            arr[i] -= 1;

            findAndChangeDuplicates(arr);
        }
    }

    return arr;
};

but when I came across this [100, 6, 6, 6, 5, 5, 5, 5, 5, 4, 4, 4, 3, 3, 2, 2, 2, 2, 1, 1, 0, 0]

my code let me down.

Expected Result: [100, 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

Have any ideas?

Answer

An approach by using at least one loop from the end to adjust the values and if necessary another loop from the beginning to set the largest value to 100.

Both loops feature a value variable v. In the first loop, it starts with the last value of the array and increments its value and check is the item is smaller than this value.

If smaller, then the value is assigned, otherwise the actual value is taken for the next item.

if necessary, the other loop works in opposite direction and with a start value of 100 and checks if the item is greater than wanted and takes the smaller value, or the value is taken from the item.

The result is an array which has a gereatest value of 100 at start and goes until zero or greater to the end of the array.

function update(array) {
    var i = array.length,
        v = array[--i];

    while (i--) if (array[i] < ++v) array[i] = v; else v = array[i];
    if (array[0] > 100) {
        v = 100;
        for (i = 0; i < array.length; i++) {
            if (array[i] > v) array[i] = v; else v = array[i];
            v--;
        }
    }
    return array;
}

console.log(update([100, 2, 1, 1, 0]));
console.log(update( [100, 100, 99, 86, 6, 5, 5, 5, 5, 5, 4, 4, 4, 3, 3, 2, 2, 2, 2, 1, 1, 0, 0]))
.as-console-wrapper { max-height: 100% !important; top: 0; }
Categories
discuss

Android Studio – What is the use of attributes having the wrench icon?

I have seen many attributes like text, targetApi etc in Design mode of Android Studio that has the following icon on the left side:

enter image description here

Some of them are more than once for example one text attribute without wrench icon and one with wrench icon. What is the purpose and use? Any examples would be appreciated. Thanks!!!

Answer

The one with the wrench icon controls the tools: attribute, whereas the one without the wrench controls an android: or app: attribute. Attributes in the tools: namespace are only used by development tools and have no runtime effects. So, tools:text says “show this text in this widget in the IDE”, while android:text says “show this text in this widget on the device”. This is particularly useful in cases where you cannot provide android:text, as the text is not knowable until the app runs — tools:text lets you provide sample text to help with setting up the UI design.

Categories
discuss

ndk r20 ld : ld: error: cannot find -lpthread

I’m trying to build tesseract for android arm with vcpkg and ndk r20 I had to edit CMakeLists.txt and add glob.c and glob.h because they weren’t in the ndk

I also made fileio.cpp include glob.h

then I had to bypass pkg-config because ndk doesn’t have it I replace this :

if(NOT EXISTS ${PROJECT_SOURCE_DIR}/.cppan)
    if (NOT Leptonica_DIR AND NOT MSVC)
        find_package(PkgConfig REQUIRED)
        pkg_check_modules(Leptonica REQUIRED lept>=${MINIMUM_LEPTONICA_VERSION})
        #link_directories(${Leptonica_LIBRARY_DIRS})
    else()
        find_package(Leptonica ${MINIMUM_LEPTONICA_VERSION} REQUIRED CONFIG)
    endif()
else()
    if (STATIC)
        set(CPPAN_BUILD_SHARED_LIBS 0)
    else()
        set(CPPAN_BUILD_SHARED_LIBS 1)
    endif()
    add_subdirectory(.cppan)
endif()

with this :

if(NOT EXISTS ${PROJECT_SOURCE_DIR}/.cppan)
    if (NOT Leptonica_DIR AND NOT MSVC)
        find_package(Leptonica CONFIG REQUIRED)
        #link_libraries(tesseract leptonica) causes errors , tried tesseractlib instead of tesseract
    else()
        find_package(Leptonica ${MINIMUM_LEPTONICA_VERSION} REQUIRED CONFIG)
    endif()
else()
    if (STATIC)
        set(CPPAN_BUILD_SHARED_LIBS 0)
    else()
        set(CPPAN_BUILD_SHARED_LIBS 1)
    endif()
    add_subdirectory(.cppan)
endif()

after this I tried to build the library with this command :

vcpkg install tesseract[core]:arm-android

the build process exits due to error near the end the libtesseract.a library is built but not the binary tesseract

there is a long log in install-arm-android-rel-out.log and this is the error at the end :

[240/242] cmd.exe /C "cd . && E:programsvcpkgdownloadstoolscmake-3.14.0-windowscmake-3.14.0-win32-x86bincmake.exe -E remove libtesseract.a && E:programsndkandroid-ndk-r20toolchainsllvmprebuiltwindows-x86_64binarm-linux-androideabi-ar.exe qc libtesseract.a  @CMakeFileslibtesseract.rsp && E:programsndkandroid-ndk-r20toolchainsllvmprebuiltwindows-x86_64binarm-linux-androideabi-ranlib.exe libtesseract.a && cd ."
[241/242] cmd.exe /C "cd . && E:programsndkandroid-ndk-r20toolchainsllvmprebuiltwindows-x86_64binclang++.exe --target=armv7-none-linux-androideabi21 --gcc-toolchain=E:/programs/ndk/android-ndk-r20/toolchains/llvm/prebuilt/windows-x86_64 --sysroot=E:/programs/ndk/android-ndk-r20/toolchains/llvm/prebuilt/windows-x86_64/sysroot  -g -DANDROID -fdata-sections -ffunction-sections -funwind-tables -fstack-protector-strong -no-canonical-prefixes -fno-addrsig -march=armv7-a -mthumb -Wa,--noexecstack -Wformat -Werror=format-security -frtti -fexceptions  --std=c++11 -Oz -DNDEBUG  -Wl,--exclude-libs,libgcc.a -Wl,--exclude-libs,libatomic.a -static-libstdc++ -Wl,--build-id -Wl,--warn-shared-textrel -Wl,--fatal-warnings -Wl,--exclude-libs,libunwind.a -Wl,--no-undefined -Qunused-arguments -Wl,-z,noexecstack -Wl,--gc-sections CMakeFiles/tesseract.dir/src/api/tesseractmain.cpp.o  -o bintesseract  libtesseract.a -lpthread E:/programs/vcpkg/installed/arm-android/lib/libleptonica.a E:/programs/vcpkg/installed/arm-android/lib/libgif.a E:/programs/vcpkg/installed/arm-android/lib/libjpeg.a E:/programs/vcpkg/installed/arm-android/share/png/../../lib/libpng16.a E:/programs/vcpkg/installed/arm-android/lib/libtiff.a E:/programs/vcpkg/installed/arm-android/lib/liblzma.a E:/programs/vcpkg/installed/arm-android/lib/libjpeg.a E:/programs/vcpkg/installed/arm-android/share/png/../../lib/libpng16.a E:/programs/vcpkg/installed/arm-android/lib/libtiff.a E:/programs/vcpkg/installed/arm-android/lib/liblzma.a E:/programs/vcpkg/installed/arm-android/lib/libz.a -lm E:/programs/vcpkg/installed/arm-android/lib/libz.a -lm -latomic -lm && cd ."
FAILED: bin/tesseract 
cmd.exe /C "cd . && E:programsndkandroid-ndk-r20toolchainsllvmprebuiltwindows-x86_64binclang++.exe --target=armv7-none-linux-androideabi21 --gcc-toolchain=E:/programs/ndk/android-ndk-r20/toolchains/llvm/prebuilt/windows-x86_64 --sysroot=E:/programs/ndk/android-ndk-r20/toolchains/llvm/prebuilt/windows-x86_64/sysroot  -g -DANDROID -fdata-sections -ffunction-sections -funwind-tables -fstack-protector-strong -no-canonical-prefixes -fno-addrsig -march=armv7-a -mthumb -Wa,--noexecstack -Wformat -Werror=format-security -frtti -fexceptions  --std=c++11 -Oz -DNDEBUG  -Wl,--exclude-libs,libgcc.a -Wl,--exclude-libs,libatomic.a -static-libstdc++ -Wl,--build-id -Wl,--warn-shared-textrel -Wl,--fatal-warnings -Wl,--exclude-libs,libunwind.a -Wl,--no-undefined -Qunused-arguments -Wl,-z,noexecstack -Wl,--gc-sections CMakeFiles/tesseract.dir/src/api/tesseractmain.cpp.o  -o bintesseract  libtesseract.a -lpthread E:/programs/vcpkg/installed/arm-android/lib/libleptonica.a E:/programs/vcpkg/installed/arm-android/lib/libgif.a E:/programs/vcpkg/installed/arm-android/lib/libjpeg.a E:/programs/vcpkg/installed/arm-android/share/png/../../lib/libpng16.a E:/programs/vcpkg/installed/arm-android/lib/libtiff.a E:/programs/vcpkg/installed/arm-android/lib/liblzma.a E:/programs/vcpkg/installed/arm-android/lib/libjpeg.a E:/programs/vcpkg/installed/arm-android/share/png/../../lib/libpng16.a E:/programs/vcpkg/installed/arm-android/lib/libtiff.a E:/programs/vcpkg/installed/arm-android/lib/liblzma.a E:/programs/vcpkg/installed/arm-android/lib/libz.a -lm E:/programs/vcpkg/installed/arm-android/lib/libz.a -lm -latomic -lm && cd ."
E:/programs/ndk/android-ndk-r20/toolchains/llvm/prebuilt/windows-x86_64/lib/gcc/arm-linux-androideabi/4.9.x/../../../../arm-linux-androideabi/binld: error: cannot find -lpthread
clang++: error: linker command failed with exit code 1 (use -v to see invocation)
ninja: build stopped: subcommand failed.

as you can see the linker can’t find pthread !

this is my arm-android.cmake used by vcpkg :

set(VCPKG_TARGET_ARCHITECTURE arm)
set(VCPKG_CRT_LINKAGE dynamic)
set(VCPKG_LIBRARY_LINKAGE static)

set(VCPKG_CMAKE_SYSTEM_NAME Android)
set(VCPKG_BUILD_TYPE release)

and I set these variables :

set "ANDROID_NDK=E:programsndkandroid-ndk-r20"
set "ANDROID_NDK_HOME=E:programsndkandroid-ndk-r20"

Answer

You don’t need glob. After all, you are building for a mobile device, where you won’t perform training. The file fileio.cpp that refers to glob, is only used in training.

Android NDK is special in that it does not have libpthread, the pthread implementation is inside libc. The easy hack is to copy libc.a to libpthread.a, or create an empty libpthread.a with ar command.

You may find the preconfigured docker build environment helpful. If you prefer an ndk-build version, fully integrated into Android Studio, have a look at my fork: https://github.com/alexcohn/tess-two.

Categories
discuss

“adb” can’t be opened because Apple cannot check it for malicious software

I faced the following problem: when I try to make a RN project as in tutorial, I have the next window: “adb” can’t be opened because Apple cannot check it for malicious software.

Yes, I know that when I have such window I should open the app in finder, click the right button of the mouse and then click “open”.
But in this situation I cannot do it, as there’s no way to open adb in finder, so, how can I solve this problem?

Answer

open “Settings” -> “Security & Privacy” -> “General”,

under “Allow apps downloaded from:” click “Allow Anyway” on adb, then try again. at least this works to me

Source: stackoverflow
Text is available under the Creative Commons Attribution-ShareAlike License; additional terms may apply. By using this site, you agree to the Privacy Policy, and Copyright Policy. Content is available under CC BY-SA 3.0 unless otherwise noted. The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 © No Copyrights, All Questions are retrived from public domain..