Install android studio with proxy

For the sdkmanager use the following extra options:

sdkmanager --list --verbose --no_https --proxy=http --proxy_host=<proxy_host> --proxy_port=<proxy_port>

Android Studio Dialog Buttons out of Screen when using Wrap Content as LayoutParams

I Have a Dialog with a Custom layout in my layouts Folder, which Wraps its Content. If I pu tin a large Text into one of the TextFields, the Buttons on the Bottom dissapear. The Text itself is scrollable and everything else works just fine. I want the Buttons to stick to the Bottom of the Dialog and not disappear if the text is Too Large.
Dialog without TextInput, Dialog with large Text. Icannot post Pictures directly, therefore i just included Links.

I have already tried to change the Layout so the Buttons stick to the Bottom of the Layout instead of the TextView above them. Setting a fixed size isnt really an Option.

Layout of the Dialog Layout:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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:background="@drawable/bg_layout_rounded_16">

    <EditText
        android:id="@+id/dialog_resource_title"
        style="@style/myEditTextStyle"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="8dp"
        android:hint="@string/general_title_hint"
        android:inputType="textMultiLine"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.498"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <EditText
        android:id="@+id/dialog_resource_description"
        style="@style/myEditTextStyle"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="16dp"
        android:layout_marginBottom="8dp"
        android:hint="@string/general_description_hint"
        android:inputType="textMultiLine"
        app:layout_constraintBottom_toTopOf="@+id/dialog_resource_cancel"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/dialog_resource_title" />

    <Button
        android:id="@+id/dialog_resource_cancel"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginEnd="4dp"
        android:layout_marginBottom="8dp"
        android:paddingBottom="8dp"
        android:text="@string/general_cancel"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toStartOf="@+id/dialog_resource_middle_line"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent" />

    <Button
        android:id="@+id/dialog_resource_save"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="4dp"
        android:layout_marginEnd="8dp"
        android:layout_marginBottom="8dp"
        android:text="@string/general_save"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="@+id/dialog_resource_middle_line" />

    <android.support.constraint.Guideline
        android:id="@+id/dialog_resource_middle_line"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        app:layout_constraintGuide_percent="0.5" />

</android.support.constraint.ConstraintLayout>


Initialisation of the Dialog:



        resourceDialog = new Dialog(context);

        View v = LayoutInflater.from(context).inflate(R.layout.dialog_resource, null);

        this.resourceDialogTitle = v.findViewById(R.id.dialog_resource_title);
        this.resourceDialogDescription = v.findViewById(R.id.dialog_resource_description);
        this.resourceDialogCancel = v.findViewById(R.id.dialog_resource_cancel);
        this.resourceDialogSave = v.findViewById(R.id.dialog_resource_save);

        resourceDialog.setContentView(v);
        // Set Color of Root View (Otherwise white Background in the Corners)
        resourceDialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);

        // Getting the Display Metrics to set Size of Dialog
        DisplayMetrics displayMetrics = getResources().getDisplayMetrics();
        int width = displayMetrics.widthPixels;

        // Setting the Size
        resourceDialog.getWindow().setLayout((width - 128), ViewGroup.LayoutParams.WRAP_CONTENT);

        resourceDialog.setCanceledOnTouchOutside(false);

Solution:

Put the buttons incide a linear layout and use a constraint option to constrain it to the bottom of the screen. For example

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_centerInParent="true"
    android:orientation="horizontal"
    app:layout_constraintBottom_toBottomOf="parent">

    <Button />

    <Button />
</LinearLayout>

–Edit–
I tried this and worked for me

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
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.support.v4.widget.NestedScrollView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:fillViewport="true"
    android:fitsSystemWindows="true"
    android:paddingBottom="120dp"
    android:scrollbars="horizontal"
    app:layout_constraintTop_toBottomOf="@+id/appBarLayout">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/appBarLayout"
        android:layout_marginLeft="10dp"
        android:layout_marginTop="14dp"
        android:layout_marginRight="10dp"
        android:orientation="vertical">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/address"
            android:textColor="@color/black_1"
            android:textSize="20sp"
            android:textStyle="bold" />


    </LinearLayout>

</android.support.v4.widget.NestedScrollView>

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_centerInParent="true"
    android:orientation="horizontal"
    app:layout_constraintBottom_toBottomOf="parent">

    <Button
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:layout_marginRight="4dp"
        android:textColor="@android:color/white" />

    <Button
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:layout_marginLeft="4dp"
        android:textColor="@android:color/white" />
</LinearLayout>

</android.support.constraint.ConstraintLayout>

Will SharedPreferences "commit()" be automatically changed to "apply()" in Androids code optimization?

So, I’m facing this weird problem right now. I HAVE to use SharedPreferences.Editor().commit() in my Android app, but, as the documentation here states,

As SharedPreferences instances are singletons within a process, it’s
safe to replace any instance of commit() with apply() if you were
already ignoring the return value.

You don’t need to worry about Android component lifecycles and their
interaction with apply() writing to disk. The framework makes sure
in-flight disk writes from apply() complete before switching states.

Basically it is safe to replace commit() with apply() if you’re not using the return value, BUT, the difference between two as mentioned here, and as warning in Android Studio states, is that commit() immediately writes the data, BUT apply() does that asynchronously.

So my problem here is, I’m changing the language in my app, and I want to restart my app after user chooses the language. But, when user chooses the language, the current chosen language is put in SharedPreferences.

Now, the problem:

Whenever I use apply() instead of commit() and restart my app using the code to restart the app here, the changes are not written on the disk, as, when the app restarts, it does not change the current language, as the value from SharedPreference is not changed, because it is not immediately written on the disk. But, whenever I use commit(), the changes are immediately written, and the language is successfully changed when the app is restarted.

So, the questions:

  1. How can people who wrote the code for commit() and apply() say that it is completely safe to use apply() instead of commit(), if there’s very big difference, as commit() writes the data immediately, but apply() does it in background?

  2. If I build my apk, will the commit() be replaced by apply() in code optimization if I’m not using the return value.(I know I can know this by building the release version of the app, but I still won’t be sure, because when I use apply(), it veeery frequently 1/10 times actually does change the value from SharedPreference)

A note:

  1. I know how I can use Apply() and still make my app work, maybe I’ll have to add some delay before restarting the app? But I’m not sure how it’ll work as it’ll still take some time to actually write the data on disk, and I don’t currently see any method to check if the SharedPreference value was actually changed, so that I can safely restart AFTER the value was changed.

Solution:

The problem is, that with Runtime.getRuntime().exit(0) or System.exit(0) you’ll kill the process and therefore no scheduled async task will execute after.

If you don’t intend to change your restart code, you should keep commit instead of apply for this instance and suppress the warning.

  1. It’s safe to assume that the statement is valid, because calling exit(0) is an edge-case you should not do normally.
  2. There’s no reason to assume that commit will be replaced with apply automatically. If you want to make sure of it, just use the return value.

displaying different messages depending on parameters

I’m new to android development. I have 10 different buttons and I want to display a toast for each one of them. The message is something like:

“This is the button: ” + numButton

Where numButton is a prop passed to the function. This is the function code:

public void displayMensaje(View v) {
        Toast.makeText(ActividadUno.this, "Test", Toast.LENGTH_SHORT).show();
    }

And this is the xml:

<Button
        android:id="@+id/button11"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="30dp"
        android:layout_marginLeft="30dp"
        android:layout_marginTop="400dp"
        android:text="churro"
        android:onClick="displayMensaje"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

Solution:

You can cast the View in Button and get the text of button.

Something like this:

public void displayMensaje(View v) {
    Button button = (Button) v;
    String title = button.getText();
    String message = "Test " + title;
    Toast.makeText(ActividadUno.this, message, Toast.LENGTH_SHORT).show();
}  

Edit:
According to my understanding from your comment below, you have multiple buttons in your activity, and you want to display different values on clicking different buttons.

You can have a Map with keys as button titles and values as nutrition values.

Below is a general example of how you can achieve this:

public class MyActivity extends Activity {
    // Your Message Format
    private static final String MSG_FORMAT = "Item Name: %s\n"
            + "Fat: %s\n"
            + "Protein: %s\n"
            + "Calories: %s";

    // A Map to hold info of all items
    // Key = button title
    // Value = Array containing item info
    private Map<String, String[]> info = new HashMap();

    // Assuming you have 3 buttons in your activity
    private Button btnMilk;
    private Button btnEggs;
    private Button btnChicken;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.my_activity);

        btnMilk = (Button) findViewById(R.id.btn_milk);
        btnEggs = (Button) findViewById(R.id.btn_eggs);
        btnChicken = (Button) findViewById(R.id.btn_chicken);

        // 0 = Fat, 1 = Protein, 2 = Calories
        String[] milkInfo = new String[]{"12", "20", "125"};
        String[] eggsInfo = new String[]{"10", "50", "205"};
        String[] chickenInfo = new String[]{"50", "5", "500"};

        // load your Map with the data
        info.put(btnMilk.getText(), milkInfo);
        info.put(btnEggs.getText(), eggsInfo);
        info.put(btnChicken.getText(), chickenInfo);

    }

    public void displayMessage(View v) {
        Button button = (Button) v;

        String title = button.getText();

        // Get item info from your Map
        String[] itemInfo = info.get(title);

        // Create message using the format and values from the array
        String message = String.format(MSG_FORMAT, title, itemInfo[0], itemInfo[1], itemInfo[2]);

        Toast.makeText(MyActivity.this, message, Toast.LENGTH_SHORT).show();
    }
}

Hope this helps

OnActivityResult not getting called

In Activity A, I want to open a dialog (CustomDialog). Inside CustomDialog, it has a button to open a camera. But the onActivityResult not getting called after I pick an image from gallery. No toast is getting displayed.

Activity A

private void openDialog() {
        CustomDialog alert = new CustomDialog();
        alert.showDialog(this);
    }

CustomDialog

public class CustomDialog extends Activity{

    Activity activity;
    ImageView imageView;

    public void showDialog(Activity activity) {
        this.activity = activity;
        final Dialog dialog = new Dialog(activity);
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog.setCancelable(false);
        dialog.setContentView(R.layout.custom_dialog);
        dialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
        dialog.setCanceledOnTouchOutside(true);

        imageView = (ImageView) dialog.findViewById(R.id.logoApp);

        Button galleryBtn = (Button) dialog.findViewById(R.id.galleryBtn);

        galleryBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                galleryIntent();
            }
        });
        dialog.show();
    }

    private void galleryIntent() {
        Intent intent = new Intent();
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);//
        activity.startActivityForResult(Intent.createChooser(intent, "Select File"), 1);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Toast.makeText(activity,"sdddddsss",Toast.LENGTH_LONG).show();
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == 1) {
                onSelectFromGalleryResult(data);
            }else{
              // ...
            }
        }
    }

    @SuppressWarnings("deprecation")
    private void onSelectFromGalleryResult(Intent data) {
        Bitmap bm=null;
        if (data != null) {
            try {
                bm = MediaStore.Images.Media.getBitmap(getApplicationContext().getContentResolver(), data.getData());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        imageView.setImageBitmap(bm);
    }
}

I follow this http://www.theappguruz.com/blog/android-take-photo-camera-gallery-code-sample

Solution:

When you show dialog in Activity A, you set reference to Activity A as param:
alert.showDialog(this);
Then inside CustomDialog, you save this reference as activity variable:

public void showDialog(Activity activity) {
this.activity = activity;
...}

This means, that this.activity is instance of Activity A. Later in your galleryIntent(), you start activity for result like this:

private void galleryIntent() {
...
activity.startActivityForResult(Intent.createChooser(intent, "Select File"), 1);
}

This means that onActivityResult will be called in Activity A, not your Custom dialog, because you’ve used activity variable.

You have 2 options for fix:

1) replace activity.startActivityForResult with CustomDialog.this.startActivityForResult

2) move your onActivityResult code from CustomDialog into Activity A

About special characters in java

In my application about World of Warcraft mythic dungeons i have to do some queries into the raiderio Public API. I having a big issue when the players name it’s something like this :

https://raider.io/api/v1/characters/profile?region=US&realm=https://raider.io/characters/us/zuljin/Børomìr&name=&fields=mythic_plus_best_runs%3Aall

this name : Børomìr

In the API this query doesn’t work because it manages special characters like this:

https://raider.io/api/v1/characters/profile?region=us&realm=zuljin&name=B%C3%B8rom%C3%ACr&fields=mythic_plus_best_runs%3Aall

becomes this : B%C3%B8rom%C3%ACr

where:

ø becomes %C3%B8

ì becomes %C3%AC

which tool do i need to generate this conversion in java?

Heres is the URL request code:

            String body = "";
            URL url = new URL("https://raider.io/api/v1/characters/profile?region="+region.toString()+"&realm="+realm+"&name="+name+"&fields=mythic_plus_best_runs%3Aall");
            System.out.println(url.toString());
            URLConnection uc = url.openConnection();
            uc.addRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)");
            InputStream in = uc.getInputStream();
            String encoding = uc.getContentEncoding();
            encoding = encoding == null ? "UTF-8"
                    // "windows-1251"
                    // "Cp1251"
                    : encoding;
            body = IOUtils.toString(in, encoding);

Solution:

You would use Java’s URLEncoder As in URLEncoder.encode("Børomìr", "UTF-8");

Java / Kotlin equivalent of Swift [String : [String : Any]]

What is the equivalent of [String : [String : Any]] from Swift in Kotlin or Java language?

I need to retrieve from database a structure that looks like this:

Key:
    Key : Value
    Key : Value
    Key : Value
Key :
    Key : Value
    Key : Value
    Key : Value

Solution:

It can be represented by a Map<String, Map<String, Any>>. The Kotlin code for creating such a type:

val map: Map<String, Map<String, Any>> = mapOf(
    "Key1" to mapOf("KeyA" to "Value", "KeyB" to "Value"),
    "Key2" to mapOf("KeyC" to "Value", "KeyD" to "Value")
)

In Java, as of JDK 9, it can be expressed like this:

Map<String, Map<String, Object>> map = Map.of(
    "Key1", Map.of("KeyA", "Value", "KeyB", "Value"),
    "Key2", Map.of("KeyC", "Value", "KeyD", "Value")
);

Note that Any from the Kotlin snippet became Object in Java.

how to change the colour of a cardview when selected?clicked

im trying out card view instead of a button i love the amount of info you can add to them. but im trying to make it so if they press the card it changes colour. i want it to change back once they release. so that it works in a similar way to my buttons.

i can get it so that it changes on click but it stay like that untill the activity is destroyed,

this is the code i use for changing the colour at the moment.

public void setSingleEvent(GridLayout maingrid) {
    for (int i = 0; i < maingrid.getChildCount(); i++) {
        final CardView cardView = (CardView) maingrid.getChildAt(i);
        final int finalI = i;
        cardView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Toast.makeText(mcontext, "Button: " + finalI, Toast.LENGTH_SHORT).show();
                cardView.setCardBackgroundColor(mcontext.getResources().getColor(R.color.buttonPressed));
                if (finalI == 0) {
                    mcontext.startActivity(new Intent(mcontext, Genre_Streaming.class));
                }
            }
        });

Solution:

You can try using OnTouchListener with ACTION_DOWN and ACTION_UP to handle Press/Release events instead of OnClickListener.

Modified Code:

public void setSingleEvent(GridLayout maingrid) {
    for (int i = 0; i < maingrid.getChildCount(); i++) {
        final CardView cardView = (CardView) maingrid.getChildAt(i);
        final int finalI = i;

        cardView.setOnTouchListener(new OnTouchListener () {
          public boolean onTouch(View view, MotionEvent event) {
            if (event.getAction() == android.view.MotionEvent.ACTION_DOWN) {
              Toast.makeText(mcontext, "Button: " + finalI, Toast.LENGTH_SHORT).show();
              cardView.setCardBackgroundColor(mcontext.getResources().getColor(R.color.buttonPressed));
              if (finalI == 0) {
                  mcontext.startActivity(new Intent(mcontext, Genre_Streaming.class));
              }
            } else if (event.getAction() == android.view.MotionEvent.ACTION_UP) {
              /* Reset Color */
              cardView.setCardBackgroundColor(mcontext.getResources().getColor(R.color.red));
            }
            return true;
          }
        }
}

Link: http://developer.android.com/reference/android/view/MotionEvent.html#ACTION_UP

Parameter type of method to correspond to inner class which extends super's inner class

I have some classes structured as follows:

class A {
    inner class B {}

    void func(B param) {}
}

class Asub extends A {
    inner class B extends A.B {}

    @Override
    void func(B param) {}      // problematic line
}

But the compiler doesn’t allow it as a proper override and only allows it if I change (in Asub)

void func(B param)

to

void func(A.B param)

However I do not want to do that as I have some overriden functionality defined in Asub.B that I want to make use of but if I change the param type to A.B instead of B, the linter tells me that Asub.B is unused

I would appreciate any help in solving this issue or if it is not possible, a possible alternate approach to accomplish the functionality that I want

The actual context of this question has to do with Android RecyclerView.Adapters and ViewHolders but I don’t think the problem resides there

Solution:

I believe your best shot here is using generics.

Something along the lines of

abstract class A<T extends A.B> {
    class B {
      // ...
    }

    abstract void func(T param) {
      //..
    }
}

class Asub<Asub.B> extends A {
    class B extends A.B {
      // ...
    }


    @Override
    void func(Asub.B param) {
      // ...
    }
}

should probably do the job.

Trying to modify a kernel

I’m a noob in linux/android, yet I have to modify a kernel.

For one specific reason I’m using this guide (it’s somewhat understandable when translated to english using google).

The problem is that I’m stuck at part where you have to “enter the following command to view the address of these two functions”. The only addresses I get when entering those commands are 00000000, which doesn’t seem quite right.

I don’t really understand why is that happening. It may be because the guy who created a guide is using adb for getting addresses, while I’m trying to get them using terminal in android. I can’t quite use adb, because I’m running MEmu emulator and that’s where I need addresses from.

Solution:

The address is not being shown because you are not running the command under the root user.
This issue has been explained in this answer.

In your case, you need to obtain super-admin rights using either the sudo -s or su command. Once admin, your shell prompt should end with a #. On my one plus, the prompt looks like this when I am admin: A0001:/ #

If it does not work, be sure that the file /proc/sys/kernel/kptr_restrict contains a 0. You can do so by executing the command cat /proc/sys/kernel/kptr_restrict.

To set its value to 0, you should execute the command echo 0 > /proc/sys/kernel/kptr_restrict with administrative rights.

Hope it helps!