Friday, April 29, 2016

SearchView Android

activity_layout
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
 android:id="@+id/sample_main_layout" 
 android:layout_width="match_parent" 
 android:layout_height="match_parent" 
 android:orientation="vertical">

    <SearchView 
 android:id="@+id/searchView" 
 android:layout_width="200dp" 
 android:layout_height="wrap_content" 
 android:layout_gravity="center_horizontal" />
</LinearLayout>
MainActivity
public class MainActivity extends AppCompatActivity {
    SearchView search;

    @Override 
 protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        search = (SearchView) findViewById(R.id.searchView);
        search.setQueryHint("Search...");
        search.setOnQueryTextFocusChangeListener(new View.OnFocusChangeListener() {

            @Override 
 public void onFocusChange(View v, boolean hasFocus) {
                Toast.makeText(getBaseContext(), String.valueOf(hasFocus),
                        Toast.LENGTH_SHORT).show();
            }
        });
        search.setOnQueryTextListener(new SearchView.OnQueryTextListener() {

            @Override 
 public boolean onQueryTextSubmit(String query) {
                Toast.makeText(getBaseContext(), query,
                        Toast.LENGTH_SHORT).show();
                return false;
            }

            @Override 
 public boolean onQueryTextChange(String newText) {
                Toast.makeText(getBaseContext(), newText,
                        Toast.LENGTH_SHORT).show();
                return false;
            }
        });
    }

} 

Android Download file from URL with DownloadManager

activity_layout
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
 android:id="@+id/sample_main_layout" 
 android:layout_width="match_parent" 
 android:layout_height="match_parent" 
 android:orientation="vertical">
    
    <Button 
 android:id="@+id/btnDownload" 
 android:layout_width="wrap_content" 
 android:layout_height="wrap_content" 
 android:layout_gravity="center_horizontal" 
 android:text="Start Download" />
</LinearLayout>
AndroidManifest
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
MainActivity
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    DownloadManager downloadManager;
    String _URL = "your URL";
    long refer;
    BroadcastReceiver downloadcomplete;
    BroadcastReceiver notificationClick;
    Button btnDownload;

    public void startdownload() {
        downloadManager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
        Uri uri = Uri.parse(_URL);
        DownloadManager.Request request = new DownloadManager.Request(uri);
        request.setDescription("My download").setTitle("Notification Title");
        request.setDestinationInExternalFilesDir(this, Environment.DIRECTORY_DOWNLOADS, "your filename");
        request.setVisibleInDownloadsUi(true);
        request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE);
        refer = downloadManager.enqueue(request);
        IntentFilter filter = new IntentFilter(DownloadManager.ACTION_NOTIFICATION_CLICKED);
        notificationClick = new BroadcastReceiver() {
            @Override 
              public void onReceive(Context context, Intent intent) {
                String extraID = DownloadManager.EXTRA_NOTIFICATION_CLICK_DOWNLOAD_IDS;
                long[] references = intent.getLongArrayExtra(extraID);
                for (long r : references) {
                    if (r == refer) {
                        // do something with download file                    }
                }
            }
        };
        registerReceiver(notificationClick, filter);

        IntentFilter intentFilter = new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
        downloadcomplete = new BroadcastReceiver() {
            @Override 
              public void onReceive(Context context, Intent intent) {
                long r = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
                if (refer == r) {
                    DownloadManager.Query query = new DownloadManager.Query();
                    query.setFilterById(r);
                    Cursor cursor = downloadManager.query(query);
                    cursor.moveToFirst();
                    //get status of the download 
                    int columnIndex = cursor.getColumnIndex(DownloadManager.COLUMN_STATUS);
                    int status = cursor.getInt(columnIndex);
                    int filenameIndex = cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_FILENAME);
                    String saveFilePath = cursor.getString(filenameIndex);
                    int columnReason = cursor.getColumnIndex(DownloadManager.COLUMN_REASON);
                    int reason = cursor.getInt(columnReason);
                    switch (status) {
                        case DownloadManager.STATUS_SUCCESSFUL:
                            Toast.makeText(getApplicationContext(), "STATUS_SUCCESSFUL", Toast.LENGTH_SHORT).show();
                            break;
                        case DownloadManager.STATUS_FAILED:
                            // do something                            break;
                        case DownloadManager.STATUS_PAUSED:
                            // do something                            break;
                        case DownloadManager.STATUS_PENDING:
                            // do something                            break;
                        case DownloadManager.STATUS_RUNNING:
                            // do something                            break;
                    }
                }
            }
        };
        registerReceiver(downloadcomplete, intentFilter);
    }

    @Override 
 protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btnDownload = (Button) findViewById(R.id.btnDownload);
        btnDownload.setOnClickListener(this);
        // demo download file from URL
    }

    @Override 
 public void onClick(View v) {
        if (v == btnDownload)
            startdownload();
    }

    @Override 
 protected void onPause() {
        super.onPause();
        unregisterReceiver(downloadcomplete);
        unregisterReceiver(notificationClick);
    }
} 

Check permission in Android 6 (Marshmallow)

activity_main
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
     android:id="@+id/sample_main_layout" 
 android:layout_width="match_parent" 
 android:layout_height="match_parent" 
 android:orientation="vertical">


    <Button
        android:layout_width="wrap_content" 
 android:layout_height="wrap_content" 
 android:text="Get deviceId" 
 android:id="@+id/btn_deviceId" 
 android:layout_gravity="center_horizontal" />

    <TextView 
 android:layout_width="wrap_content"  
 android:layout_height="wrap_content" 
 android:text="deviceId" 
 android:id="@+id/tv_deviceId" 
 android:layout_gravity="center_horizontal" />
</LinearLayout>

Android_Manifest
 
<?xml version="1.0" encoding="utf-8"?> 
<manifest xmlns:android="http://schemas.android.com/apk/res/android" 
 package="map.conghuy.com.myapplication">

    <!-- BEGIN_INCLUDE(manifest) -->
    <!-- Note that all required permissions are declared here in the Android manifest. 
 On Android M and above, use of these permissions is only requested at run time. --> 
 <uses-permission android:name="android.permission.READ_PHONE_STATE"/>

    <!-- END_INCLUDE(manifest) --> 
 <application 
 android:allowBackup="true" 
 android:icon="@mipmap/ic_launcher" 
 android:label="@string/app_name" 
 android:supportsRtl="true" 
 android:theme="@style/AppTheme">
        <activity 
 android:name=".MainActivity" 
 android:label="@string/app_name" 
 android:theme="@style/AppTheme.NoActionBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>
 
MainActivity
 
public class MainActivity extends SampleActivityBase
        implements ActivityCompat.OnRequestPermissionsResultCallback {
    public static final String TAG = "MainActivity";
    private final int MY_PERMISSIONS_REQUEST_CODE = 1;
    Button btn_deviceId;
    TextView tv_deviceId;
    TelephonyManager telephonyManager;

    private boolean checkPermissions() {
        if (ActivityCompat.checkSelfPermission(this,
 Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
            return false;
        }
        return true;
    }

    @Override 
 public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode != MY_PERMISSIONS_REQUEST_CODE) {
            return;
        }
        boolean isGranted = true;
        for (int result : grantResults) {
            if (result != PackageManager.PERMISSION_GRANTED) {
                isGranted = false;
                break;
            }
        }

        if (isGranted) {
            startApplication();
        } else {
            Toast.makeText(this, "permission denied", Toast.LENGTH_LONG).show();

        }
    }

    private void setPermissions() {
        ActivityCompat.requestPermissions(this, new String[]{
                Manifest.permission.READ_PHONE_STATE        }, MY_PERMISSIONS_REQUEST_CODE);
    }

    public void startApplication() {
        btn_deviceId = (Button) findViewById(R.id.btn_deviceId);
        tv_deviceId = (TextView) findViewById(R.id.tv_deviceId);
        telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
        String deviceId = telephonyManager.getDeviceId();
        tv_deviceId.setText(deviceId);
    }

    @Override 
 protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        if (checkPermissions()) {
            startApplication();
        } else {
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setMessage("msg");
            builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                @Override 
 public void onClick(DialogInterface dialog, int which) {
                    setPermissions();
                }
            });
            builder.show();
        }

    }
} 

Sunday, April 24, 2016

Android Color Space

Android Color Space MonoChromacy, Deuteranomaly, red green, protanomaly, Tritanomaly, blue yellow option

Friday, April 15, 2016

GridLayoutManager With Recyclerview

 
activity layout

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
 xmlns:tools="http://schemas.android.com/tools" 
 android:layout_width="match_parent" 
 android:layout_height="match_parent" 
 tools:context=".MainActivity">

    <android.support.v7.widget.RecyclerView 
 android:id="@+id/recycler_view" 
 android:layout_width="match_parent" 
 android:layout_height="match_parent" 
 android:clipToPadding="false" 
 android:paddingBottom="80dp" 
 android:scrollbars="vertical" />
</RelativeLayout>
 
content_main layout
 
<?xml version="1.0" encoding="utf-8"?>
 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
 android:layout_width="match_parent" 
 android:layout_height="wrap_content" 
 android:orientation="vertical">

    <RelativeLayout 
 android:layout_width="match_parent" 
 android:layout_height="match_parent">

        <ImageView 
 android:id="@+id/country_photo" 
 android:layout_width="wrap_content" 
 android:layout_height="wrap_content" 
 android:contentDescription="@string/action_settings" 
 android:scaleType="centerCrop" />

        <TextView 
 android:id="@+id/country_name" 
 android:layout_width="match_parent" 
 android:layout_height="wrap_content" 
 android:layout_alignParentBottom="true" 
 android:layout_below="@+id/country_photo" 
 android:gravity="center" 
 android:paddingBottom="8dp" 
 android:paddingTop="8dp" 
 android:textSize="13sp" />

    </RelativeLayout>
</LinearLayout>
 
ItemObject class 
 
public class ItemObject {
    String name;
    int photo;

    public ItemObject(String name, int photo) {
        this.name = name;
        this.photo = photo;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getPhoto() {
        return photo;
    }

    public void setPhoto(int photo) {
        this.photo = photo;
    }
}
 
RecyclerViewHolders class
 
public class RecyclerViewHolders extends RecyclerView.ViewHolder implements View.OnClickListener {
    public TextView countryName;
    public ImageView countryPhoto;

    // add event  click 
 public RecyclerViewHolders(View itemView) {
        super(itemView);
        itemView.setOnClickListener(this);
        countryName = (TextView) itemView.findViewById(R.id.country_name);
        countryPhoto = (ImageView) itemView.findViewById(R.id.country_photo);
    }

    @Override 
 public void onClick(View v) {
        Toast.makeText(v.getContext(), "pos:" + getPosition(), Toast.LENGTH_SHORT).show();
    }
}
 
RecyclerViewAdapter
 
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewHolders> {

    private List<ItemObject> itemList;
    private Context context;

    public RecyclerViewAdapter(Context context, List<ItemObject> itemList) {
        this.itemList = itemList;
        this.context = context;
    }

    @Override 
 public RecyclerViewHolders onCreateViewHolder(ViewGroup parent, int viewType) {

        View layoutView = LayoutInflater.from(parent.getContext()).inflate(R.layout.content_main, null);
        RecyclerViewHolders rcv = new RecyclerViewHolders(layoutView);
        return rcv;
    }

    @Override 
 public void onBindViewHolder(RecyclerViewHolders holder, int position) {
        holder.countryName.setText(itemList.get(position).getName());
        holder.countryPhoto.setImageResource(itemList.get(position).getPhoto());
    }

    @Override 
 public int getItemCount() {
        return this.itemList.size();
    }
}
 
MainActivity class
 
public class MainActivity extends AppCompatActivity {
    private GridLayoutManager lLayout;

    @Override 
 protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        List<ItemObject> rowListItem = getAllItemList();
        lLayout = new GridLayoutManager(MainActivity.this, 4);// 4->columns 
        RecyclerView rView = (RecyclerView) findViewById(R.id.recycler_view);
        rView.setHasFixedSize(true);
        rView.setLayoutManager(lLayout);
        RecyclerViewAdapter rcAdapter = new RecyclerViewAdapter(this, rowListItem);
        rView.setAdapter(rcAdapter);
    }

    private List<ItemObject> getAllItemList() {

        List<ItemObject> allItems = new ArrayList<ItemObject>();
        allItems.add(new ItemObject("United States", R.drawable.ic_launcher));
        allItems.add(new ItemObject("Canada", R.drawable.ic_launcher));
        allItems.add(new ItemObject("United Kingdom", R.drawable.ic_launcher));
        allItems.add(new ItemObject("Germany", R.drawable.ic_launcher));
        allItems.add(new ItemObject("Sweden", R.drawable.ic_launcher));
        allItems.add(new ItemObject("United Kingdom", R.drawable.ic_launcher));
        allItems.add(new ItemObject("Germany", R.drawable.ic_launcher));
        allItems.add(new ItemObject("Sweden", R.drawable.ic_launcher));
        allItems.add(new ItemObject("United States", R.drawable.ic_launcher));
        allItems.add(new ItemObject("Canada", R.drawable.ic_launcher));
        allItems.add(new ItemObject("United Kingdom", R.drawable.ic_launcher));
        allItems.add(new ItemObject("Germany", R.drawable.ic_launcher));
        allItems.add(new ItemObject("Sweden", R.drawable.ic_launcher));
        allItems.add(new ItemObject("United Kingdom", R.drawable.ic_launcher));
        allItems.add(new ItemObject("Germany", R.drawable.ic_launcher));
        allItems.add(new ItemObject("Sweden", R.drawable.ic_launcher));

        return allItems;
    }

}
 

RecycleView Android

activity_main layout

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
 xmlns:tools="http://schemas.android.com/tools" 
 android:layout_width="match_parent" 
 android:layout_height="match_parent"     
tools:context=".MainActivity">

    <android.support.v7.widget.RecyclerView 
 android:id="@+id/list" 
 android:layout_width="match_parent" 
 android:layout_height="match_parent" 
 android:clipToPadding="false" 
 android:paddingBottom="80dp" 
 android:scrollbars="vertical" />
</RelativeLayout>
 
content_main layout
 
<?xml version="1.0" encoding="utf-8"?>
 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
 android:layout_width="match_parent" 
 android:layout_height="wrap_content" 
 android:orientation="vertical">

    <TextView 
 android:id="@+id/textView" 
 android:layout_width="match_parent" 
 android:layout_height="wrap_content" 
 android:layout_marginBottom="8dp" 
 android:layout_marginLeft="12dp" 
 android:layout_marginRight="12dp" 
 android:layout_marginTop="8dp" 
 android:textSize="22sp" />
</LinearLayout>
 
RecyclerViewAdapter class 
 
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> {
    private Context mContext;
    private String[] mList;

    public RecyclerViewAdapter(Context contexts, String[] list) {
        this.mContext = contexts;
        this.mList = list;
    }

    @Override 
 public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        LayoutInflater inflater = LayoutInflater.from(parent.getContext());
        View itemView = inflater.inflate(R.layout.content_main, parent, false);
        return new ViewHolder(itemView);
    }

    @Override 
 public void onBindViewHolder(ViewHolder holder, int position) {
        holder.titleTextView.setText(mList[position]);
        // setonclick here 
            holder.setClickListener(new ItemClickListener() {
            @Override 
              public void onClick(View view, int position, boolean isLongClick) {
                if (isLongClick)
                    Toast.makeText(mContext, "pos:" + position + " isLongClick", Toast.LENGTH_SHORT).show();
                else 
                    Toast.makeText(mContext, "pos:" + position, Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Override 
 public int getItemCount() {
        return mList.length;
    }

    public static class ViewHolder extends RecyclerView.ViewHolder
            implements View.OnClickListener, View.OnLongClickListener {
        private TextView titleTextView;
        private ItemClickListener clickListener;

        public ViewHolder(View itemView) {
            super(itemView);
            titleTextView = (TextView) itemView.findViewById(R.id.textView);
            itemView.setTag(itemView);
            itemView.setOnClickListener(this);
            itemView.setOnLongClickListener(this);
        }

        public void setClickListener(ItemClickListener itemClickListener) {
            this.clickListener = itemClickListener;
        }

        @Override 
 public void onClick(View view) {
            clickListener.onClick(view, getPosition(), false);
        }

        @Override 
 public boolean onLongClick(View view) {
            clickListener.onClick(view, getPosition(), true);
            return true;
        }
    }
}
 
ItemClickListener interface
 
public interface ItemClickListener {
    void onClick(View view, int position, boolean isLongClick);
} 
 

MainActivity class
 
public class MainActivity extends AppCompatActivity {
    private RecyclerView mRecyclerView;
    private StaggeredGridLayoutManager mGridLayoutManager;
    private RecyclerViewAdapter mAdapter;
    private String[] mList = {"a", "b", "c", "d", "e", "f"};

    @Override 
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mRecyclerView = (RecyclerView) findViewById(R.id.list);
        mGridLayoutManager = new StaggeredGridLayoutManager(1, StaggeredGridLayoutManager.VERTICAL);
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
        mRecyclerView.setLayoutManager(mGridLayoutManager);
        mAdapter = new RecyclerViewAdapter(getApplicationContext(), mList);
        mRecyclerView.setAdapter(mAdapter);
    }

    @Override 
     public boolean onCreateOptionsMenu(Menu menu) {
     getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override 
    public boolean onOptionsItemSelected(MenuItem item) {
          int id = item.getItemId();
           if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}