Pages

Tuesday, August 22, 2017

Working with Coordinator layout

The CoordinatorLayout is a new layout, introduced with the Android Design Support Library. The CoordinatorLayout is a super-powered FrameLayout  If you have used a FrameLayout before, you should be very comfortable using CoordinatorLayout. If you haven’t used a FrameLayout, do not worry, it is pretty straightforward.


==> activity_coordinatorlayout.xml

<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/main_content"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true">

    <android.support.design.widget.AppBarLayout
        android:id="@+id/MyAppbar"
        android:layout_width="match_parent"
        android:layout_height="250dp"
        android:fitsSystemWindows="true">

        <android.support.design.widget.CollapsingToolbarLayout
            android:id="@+id/collapse_toolbar"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="@color/material_deep_teal_500"
            android:fitsSystemWindows="true"
            app:layout_scrollFlags="scroll|exitUntilCollapsed">

            <ImageView
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:background="@drawable/profilepic"
                android:scaleType="centerCrop"
                app:layout_collapseMode="parallax" />

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

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

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

    <android.support.v4.widget.NestedScrollView
        android:layout_width="match_parent"
        android:visibility="gone"
        android:layout_height="match_parent"
        android:layout_gravity="fill_vertical"
        app:layout_behavior="@string/appbar_scrolling_view_behavior">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical"
            android:paddingTop="24dp">

            <android.support.v7.widget.CardView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginLeft="10dp"
                android:layout_marginRight="10dp"
                android:layout_marginTop="10dp">

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:orientation="vertical">

                    <TextView
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:text="This text is part of first Cardview\n\n"
                        android:textColor="@color/error_color"
                        android:textSize="20sp" />

                </LinearLayout>

            </android.support.v7.widget.CardView>

            <android.support.v7.widget.CardView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginLeft="10dp"
                android:layout_marginRight="10dp"
                android:layout_marginTop="10dp">

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:orientation="vertical">

                    <TextView
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:text="This text is part of second Cardview\n\n"
                        android:textColor="@color/abc_search_url_text"
                        android:textSize="20sp" />

                </LinearLayout>

            </android.support.v7.widget.CardView>

        </LinearLayout>

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


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


==> CoordinatorLayoutExample.java

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.graphics.Palette;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import butterknife.BindView;
import butterknife.ButterKnife;


public class CoordinatorLayoutExample extends AppCompatActivity {


    @BindView(R.id.MyToolbar)
    Toolbar MyToolbar;

    @BindView(R.id.collapse_toolbar)
    CollapsingToolbarLayout collapse_toolbar;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_coordinatorlayout);
        ButterKnife.bind(this);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            getWindow().setStatusBarColor(ContextCompat.getColor(this, R.color.colorPrimaryDark));
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            Window w = getWindow();
            w.setFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS, WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
        } else {
            getWindow().getDecorView().setSystemUiVisibility(
                    View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                            | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
        }
//        setSupportActionBar(MyToolbar);
//        getSupportActionBar().setTitle("All in One");
//        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        setSupportActionBar(MyToolbar);
        ActionBar actionBar = getSupportActionBar();
        actionBar.setTitle("All in One");
        actionBar.setDisplayHomeAsUpEnabled(true);

        dynamicToolbarColor();
        toolbarTextAppernce();
    }

    private void dynamicToolbarColor() {

        Bitmap bitmap = BitmapFactory.decodeResource(getResources(),
                R.drawable.profilepic);
        Palette.from(bitmap).generate(new Palette.PaletteAsyncListener() {

            @Override
            public void onGenerated(Palette palette) {
                collapse_toolbar.setContentScrimColor(palette.getMutedColor(getResources().getColor(R.color.colorPrimary)));
                collapse_toolbar.setStatusBarScrimColor(palette.getMutedColor(getResources().getColor(R.color.colorPrimaryDark)));
            }
        });
    }

    private void toolbarTextAppernce() {
        collapse_toolbar.setCollapsedTitleTextAppearance(R.style.collapsedappbar);
        collapse_toolbar.setExpandedTitleTextAppearance(R.style.expandedappbar);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                onBackPressed();
                break;
        }
        return true;
    }



}


Sunday, August 20, 2017

Dial USSD Code

We can handle ussd code at run time in android programatically for getting response of any ussd code.


==> activity_ussdcode.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">


    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/colorPrimary"
        android:titleTextColor="@color/white"
        app:titleTextColor="@color/white"></android.support.v7.widget.Toolbar>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_gravity="center"
        android:layout_margin="20dp"
        android:layout_marginTop="50dp"
        android:orientation="vertical">

        <EditText
            android:id="@+id/edt_ussdcode"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="Enter USSD Code like *111*2" />


        <Button
            android:id="@+id/btn_dial"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Dial" />
    </LinearLayout>

</LinearLayout>

==> USSDCodeActivity.java

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.zealous.demoapps.R;
import com.zealous.demoapps.service.USSDMainService;

import butterknife.BindView;
import butterknife.ButterKnife;
public class USSDCodeActivity extends AppCompatActivity {


    @BindView(R.id.btn_dial)
    Button btn_dial;

    @BindView(R.id.edt_ussdcode)
    EditText edt_ussdcode;

    @BindView(R.id.toolbar)
    Toolbar toolbar;

    @Override    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ussdcode);
        ButterKnife.bind(this);
        setSupportActionBar(toolbar);
        getSupportActionBar().setTitle("Dial USSD code");
        startService(new Intent(this, USSDMainService.class));
        clickEvent();
    }

    private void clickEvent() {
        btn_dial.setOnClickListener(new View.OnClickListener() {
            @Override            public void onClick(View view) {

                if (!edt_ussdcode.getText().toString().equalsIgnoreCase("")) {
//                    dailNumber("*111*2");                    dailNumber(edt_ussdcode.getText().toString());
                } else {
                    Toast.makeText(USSDCodeActivity.this, "Please Enter USSD code", Toast.LENGTH_LONG).show();
                }
            }
        });
    }

    private void dailNumber(String code) {
        String ussdCode = "*" + code + Uri.encode("#");
        startActivity(new Intent("android.intent.action.CALL", Uri.parse("tel:" + ussdCode)));
    }
}

Working with Retrofit 2.0 library and learn how to use it.

Retrofit is a REST Client for Android and Java by Square. It makes it relatively easy to retrieve and upload JSON (or other structured data) via a REST based webservice.

First of All Add Gradle dependency to your app build.gradle file
//Retrofit
compile 'com.google.code.gson:gson:2.8.0'
compile 'com.squareup.retrofit2:retrofit:2.1.0'
compile 'com.squareup.retrofit2:converter-gson:2.1.0'
compile 'com.squareup.okhttp3:logging-interceptor:3.3.1'

//Butter Knief
compile 'com.jakewharton:butterknife:8.8.1'
annotationProcessor 'com.jakewharton:butterknife-compiler:8.8.1'

//Optional if required
useLibrary 'org.apache.http.legacy'

Step 1) Create ServiceGenerator.java class

import java.io.IOException;
import java.util.concurrent.TimeUnit;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class ServiceGenerator {

    public static final String API_BASE_URL = "http://XXX.XXXX.com/";

    private static OkHttpClient.Builder httpClient = new OkHttpClient.Builder();

    private static Retrofit.Builder builder =
            new Retrofit.Builder()
                    .baseUrl(API_BASE_URL)
                    .addConverterFactory(GsonConverterFactory.create());

    public static <S> S createService(Class<S> serviceClass) {
        return createService(serviceClass, null);
    }

    public static <S> S createService(Class<S> serviceClass, final String authToken) {
        if (authToken != null) {
            httpClient.addInterceptor(new Interceptor() {
                @Override
                public Response intercept(Interceptor.Chain chain) throws IOException {
                    Request original = chain.request();

                    // Request customization: add request headers
                    Request.Builder requestBuilder = original.newBuilder()
                            .header("Authorization", authToken)
                            .method(original.method(), original.body());

                    Request request = requestBuilder.build();
                    return chain.proceed(request);
                }
            });
        }

        OkHttpClient client = httpClient.readTimeout(60, TimeUnit.SECONDS)
                .connectTimeout(60, TimeUnit.SECONDS)
                .build();
        Retrofit retrofit = builder.client(client).build();
        return retrofit.create(serviceClass);

    }
}

Step 2) Create Model Class

public class Category{
     public String id;
     public String category;
}


Step 3) Create Interface with api declaration inside it.

public interface Webservicecall {
   
    @GET("api/v1.0/categories")
    Call<Category> getCategory();

}





Step 4) Now call the api using retrofit


//Webservicecall webservicecall = ServiceGenerator.createService(Webservicecall.class,token);

Webservicecall webservicecall = ServiceGenerator.createService(Webservicecall.class);

Call<Category> getCategory_call = webservicecall.getCategory();

showProgressDialog();

getCategory_call.enqueue(new Callback<Category>() {

            @Override
            public void onResponse(Call<Category> call, Response<Category> response) {

            hideProgressDialog();

            }


            @Override
            public void onFailure(Call<Category> call, Throwable t) {
                hideProgressDialog();
            }

        }); 

Step 5) Show Progress dialog

ProgressDialogFragment progressDialogFragment = null;

public void showProgressDialog() {
        progressDialogFragment = new ProgressDialogFragment("");
        progressDialogFragment.show(getFragmentManager(), "");
        progressDialogFragment.setCancelable(false);
    }

public void hideProgressDialog() {
      try {
           if (progressDialogFragment != null) {
               progressDialogFragment.dismiss();
           }
        } catch (Exception e) {
        }
    }

Step 6) ProgressDialogFragment.java


import android.annotation.SuppressLint;
import android.app.Dialog;
import android.app.DialogFragment;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.view.View;
import android.widget.RelativeLayout;

@SuppressLint("ValidFragment")
public class ProgressDialogFragment extends DialogFragment {
 private String message;

 public ProgressDialogFragment() {
  this.message = "";
 }

 public ProgressDialogFragment(String message) {
  this.message = message;
 }

 @Override
 public Dialog onCreateDialog(Bundle savedInstanceState) {
  // TODO Auto-generated method stub
  Dialog loading = new Dialog(getActivity());
  loading.setContentView(R.layout.layout_progress);
  loading.setCancelable(false);

  loading.getWindow().setBackgroundDrawable(
    new ColorDrawable(Color.TRANSPARENT));
  loading.getWindow().setLayout(RelativeLayout.LayoutParams.FILL_PARENT, RelativeLayout.LayoutParams.FILL_PARENT);
  int divierId = loading.getContext().getResources()
    .getIdentifier("android:id/titleDivider", null, null);
  View divider = loading.findViewById(divierId);
  if(divider!=null) {
   divider.setBackgroundColor(Color.TRANSPARENT);
  }

  loading.show();
  return loading;
 }
}



==>layout_progress.xml

<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:wheel="http://schemas.android.com/apk/res-auto"
    android:id="@+id/RelativeLayout1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:background="@color/whitebackground"
    android:gravity="center_vertical"
    android:orientation="horizontal">

</RelativeLayout>

Wednesday, August 19, 2015

Make Image Blur

Display Image into Blur effect


1) Edit MainActivity.Java in your project

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.renderscript.Allocation;
import android.renderscript.Element;
import android.renderscript.RenderScript;
import android.renderscript.ScriptIntrinsicBlur;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ImageView;
import android.widget.TextView;


public class MainActivity extends ActionBarActivity {
    private ImageView android;
    private ImageView resultimg;
    private TextView text;
    private TextView statusText;
    Uri source;
    Bitmap bitmapMaster;
    Canvas canvasMaster;
    RenderScript _rs;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        android = (ImageView) findViewById(R.id.android1);
        resultimg = (ImageView) findViewById(R.id.resultimage);

        Bitmap bm = BitmapFactory.decodeResource(getResources(), R.drawable.android1);
        Bitmap resultbm = blurImage(bm, 10);
        resultimg.setImageBitmap(resultbm);


    }

private Bitmap blurImage(Bitmap sentBitmap, int radius) {
        if (Build.VERSION.SDK_INT > 16) {
            Bitmap bitmap = sentBitmap.copy(sentBitmap.getConfig(), true);
           
            RenderScript rs = RenderScript.create(this);
            Allocation input = Allocation.createFromBitmap(rs, sentBitmap, Allocation.MipmapControl.MIPMAP_NONE,
                    Allocation.USAGE_SCRIPT);
            Allocation output = Allocation.createTyped(rs, input.getType());
            ScriptIntrinsicBlur script = ScriptIntrinsicBlur.create(rs, Element.U8_4(rs));
            script.setRadius(radius /* e.g. 3.f */);
            script.setInput(input);
            script.forEach(output);
            output.copyTo(bitmap);
            return bitmap;
        } else {
            return sentBitmap;
        }

    }
}

2)Edit activity_main.xml file 

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <ImageView
            android:id="@+id/android1"
            android:layout_width="200dp"
            android:layout_height="200dp"
            android:layout_marginBottom="10dp"
            android:scaleType="centerCrop"
            android:src="@drawable/android1" />

        <ImageView
            android:id="@+id/resultimage"
            android:layout_width="200dp"
            android:layout_height="200dp"
            android:scaleType="centerCrop" />

    </LinearLayout>
</ScrollView>

Output







Post Data to google form

Here we have to learn how to post data from android app to google form



Download libraries : okhttp

1) Edit MainActivity.Java in your project


import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.squareup.okhttp.MediaType;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.Response;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;


public class MainActivity extends AppCompatActivity {

    //Post Data to Google Docs
    public static final MediaType FORM_DATA_TYPE
            = MediaType.parse("application/x-www-form-urlencoded; charset=utf-8");
    public static final String URL = "https://docs.google.com/forms/d/1_lR63RGcUzpu5qUAFJ0VTdMFMacasT8VHuCHXg8KzLg/formResponse";
    public static final String EMAIL_KEY = "entry_1382470853";
    public static final String SUBJECT_KEY = "entry_994168354";
    public static final String MESSAGE_KEY = "entry_1197258696";
    private Context mContext;
    private EditText emailEditText;
    private EditText subjectEditText;
    private EditText messageEditText;
    private Button sendButton;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mContext = this;
        emailEditText = (EditText) findViewById(R.id.edt_email);
        subjectEditText = (EditText) findViewById(R.id.edt_subject);
        messageEditText = (EditText) findViewById(R.id.edt_message);
        sendButton = (Button) findViewById(R.id.btn_send);
        sendButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtils.isEmpty(emailEditText.getText().toString()) ||
                        TextUtils.isEmpty(subjectEditText.getText().toString()) ||
                        TextUtils.isEmpty(messageEditText.getText().toString())) {
                    Toast.makeText(mContext, "All fields are mandatory.", Toast.LENGTH_LONG).show();
                    return;
                }
                if (!android.util.Patterns.EMAIL_ADDRESS.matcher(emailEditText.getText().toString()).matches()) {
                    Toast.makeText(mContext, "Please enter a valid email.", Toast.LENGTH_LONG).show();
                    return;
                }
                PostDataTask postDataTask = new PostDataTask();

                //execute asynctask
                postDataTask.execute(URL, emailEditText.getText().toString(),
                        subjectEditText.getText().toString(),
                        messageEditText.getText().toString());

            }
        });
    }

    private class PostDataTask extends AsyncTask<String, Void, Boolean> {

        @Override
        protected Boolean doInBackground(String... contactData) {
            Boolean result = true;
            String url = contactData[0];
            String email = contactData[1];
            String subject = contactData[2];
            String message = contactData[3];
            String postBody = "";

            try {
                //all values must be URL encoded to make sure that special characters like & | ",etc.
                //do not cause problems
                postBody = EMAIL_KEY + "=" + URLEncoder.encode(email, "UTF-8") +
                        "&" + SUBJECT_KEY + "=" + URLEncoder.encode(subject, "UTF-8") +
                        "&" + MESSAGE_KEY + "=" + URLEncoder.encode(message, "UTF-8");
            } catch (UnsupportedEncodingException ex) {
                result = false;
            }

            /*
            //If you want to use HttpRequest class from http://stackoverflow.com/a/2253280/1261816
            try {
HttpRequest httpRequest = new HttpRequest();
httpRequest.sendPost(url, postBody);
}catch (Exception exception){
result = false;
}
            */

            try {
                //Create OkHttpClient for sending request
                OkHttpClient client = new OkHttpClient();
                //Create the request body with the help of Media Type
                RequestBody body = RequestBody.create(FORM_DATA_TYPE, postBody);
                Request request = new Request.Builder()
                        .url(url)
                        .post(body)
                        .build();
                //Send the request
                Response response = client.newCall(request).execute();
            } catch (IOException exception) {
                result = false;
            }
            return result;
        }

        @Override
        protected void onPostExecute(Boolean result) {
            //Print Success or failure message accordingly
            Toast.makeText(mContext, result ? "Message successfully sent!" : "There was some error" +
                    " in sending message. Please try again after some time.", Toast.LENGTH_LONG).show();
        }

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

2) Add Internet permission to Manifest.xml

  <uses-permission android:name="android.permission.INTERNET" />