How to use lambda in Android Studio?

First of all, add following to build.gradle(app) file:

android {
    defaultConfig {
       ...
        jackOptions {
            enabled true
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
}

After that you can use lambda in your application:

        Button button = (Button) findViewById(R.id.button);
        button.setOnClickListener(v-> Toast.makeText(getApplicationContext(), "Hello Lambda", Toast.LENGTH_LONG).show());

instead of this:

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(getApplicationContext(), "Hello Lambda", Toast.LENGTH_LONG).show();
            }
        });

Android – RecyclerView adapter example

public class PeopleAdapter extends RecyclerView.Adapter<PeopleAdapter.ViewHolder> {

    List<Person> people;

    public PeopleAdapter(List<Person> people) {
        this.people = people;
    }

    @Override
    public PeopleAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.listitem_person, parent, false);
        ViewHolder holder = new ViewHolder(view);
        return holder;
    }

    public static class ViewHolder extends RecyclerView.ViewHolder {

        TextView name;
        TextView number;

        ViewHolder(View itemView) {
            super(itemView);
            name = (TextView) itemView.findViewById(R.id.name);
            number = (TextView) itemView.findViewById(R.id.number);
        }
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        Person person = people.get(position);
        holder.name.setText(person.getName());
        holder.number.setText(person.getNumber()+"");
    }

    @Override
    public int getItemCount() {
        return people.size();
    }

}

Android – what is android:supportsRtl=”true” for?

android:supportsRtl="true"

I always thought what is this for? Now I found what for. It is for supporting Arabic, Urdu, Hebrew languages. Because those languages are written from right to left. If you set supportsRtl true, your layout will be mirrored from right to left. So you do not have to create special layout for it. If you set false, your layout remain same no matter what language is used.

This is supported from API 17 – Android 4.2.

Android – How to load NavigationView menu item icon from URL using Picasso

    // this set prevents collecting targets by garbage collector
    final Set<Target> targets = new HashSet<>();

    private void loadMenuIcon(final MenuItem menuItem, String url) {

        Target target = new Target() {
            @Override
            public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom loadedFrom) {
                BitmapDrawable mBitmapDrawable = new BitmapDrawable(getResources(), bitmap);
                menuItem.setIcon(mBitmapDrawable);
            }

            @Override
            public void onBitmapFailed(Drawable drawable) {}

            @Override
            public void onPrepareLoad(Drawable drawable) {}
        };

        targets.add(target);

        Picasso.with(this).load(url).into(target);

    }

Usage:

            Menu menu = navigationView.getMenu();
            MenuItem item = menu.add(0, id, i, name);
            loadMenuIcon(item, url);

Android Studio 2.2

%d1%81%d0%bd%d0%b8%d0%bc%d0%be%d0%ba-%d1%8d%d0%ba%d1%80%d0%b0%d0%bd%d0%b0-2016-09-21-%d0%b2-1-16-51

New version of Android Studio published. Following improvements are made:

– New layout editor
– Constraint layout support
– Sample code search
– Instant Run improvement
– APK analyzer
– build cache
– Virtual sensors in emulator
– Espresso Test recorder
– GPU debugger

Happy Android coding =)

Android – How to get tweets JSON from Twitter API?

This code uses this library: Android Asynchronous Http Client

    String url = "https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=manutd";
    AsyncHttpClient client = new AsyncHttpClient();

    private void getTweets() {

        RequestParams requestParams = new RequestParams();
        requestParams.put("grant_type", "client_credentials");
        AsyncHttpClient httpClient = new AsyncHttpClient();
        httpClient.addHeader("Authorization", "Basic " + Base64.encodeToString((CONSUMER_KEY + ":" + CONSUMER_SECRET).getBytes(), Base64.NO_WRAP));
        httpClient.addHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
        httpClient.post("https://api.twitter.com/oauth2/token", requestParams, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                try {
                    JSONObject jsonObject = new JSONObject(new String(responseBody));
                    client.addHeader("Authorization", jsonObject.getString("token_type") + " " + jsonObject.getString("access_token"));
                    client.get(url, handler);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {

            }

        });
    }

    AsyncHttpResponseHandler handler = new AsyncHttpResponseHandler() {
        @Override
        public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
            String json = new String(responseBody);
            int length = json.length();
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {

        }
    };

Android – How to avoid runtime exception when implementing home button to navigate back?

I faced problem when I tried to implement home button as back button.

        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setHomeButtonEnabled(true);

That’s why I have removed these two lines, override onOptionsItemSelected method:

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            // Respond to the action bar's Up/Home button
            case android.R.id.home:
                onBackPressed();
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

Now it works without runtime exceptions!