Skip to main content

Posts

Showing posts from 2014

Get the Size of display in android

To get the current screen's width and height, just using DisplayMetrics and WindowManager

DisplayMetrics displayMetrics = new DisplayMetrics();
WindowManager wm = (WindowManager) getApplicationContext().getSystemService(Context.WINDOW_SERVICE);
wm.getDefaultDisplay().getMetrics(displayMetrics);
int screenWidth = displayMetrics.widthPixels;
int screenHeight = displayMetrics.heightPixels;


Email Address Validation

Lot of peoples validate their field by using field length or Regular Expressions.

In this way, Email Addresses validation has been difficult some times.

Format of Email Address:
The format of email addresses is local-part@domain where the local-part may be up to 64 characters long and the domain name may have a maximum of 253 characters - but the maximum 256 characters length of a forward or reverse path restricts the entire email address to be no more than 254 characters.<sup id="cite_ref-0">[1]</sup> The formal definitions are in RFC 5322 (sections 3.2.3 and 3.4.1) and RFC 5321 - with a more readable form given in the informational RFC 3696<sup id="cite_ref-1">[2]</sup> and the associated errata.

Supported Characters:
The local-part of the email address may use any of these ASCII characters RFC 5322 Section 3.2.3:

Uppercase and lowercase English letters (a–z, A–Z) (ASCII: 65-90, 97-122)Digits 0 to 9 (ASCII: 48-57)Characters !#$%&'*+-…

Float Label Edit Text in android

Last few days, i search some new UI on Edittext. Finally i found it  and its very awesome.

Float Label EditText

Meanwhile, some of jquery components only do this, but now android achieved it.


 In android, such big form shows the hint text, but after text changed it will be disappear. Using TextView with EditText makes more screen space.

Float Label Edit Text solves your problem. It's Support from version 2.2. It's also the one of best pluses.

In XML:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:floatlabel="http://schemas.android.com/apk/res-auto" 
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

<com.ind.floatlabeleditext.FloatLabelEditText
    android:id="@+id/username"
    android:layout_width="match_parent"
    android:layout_height="…

Clear the app data programmatically in android

Clear the App Data Programmatically in Android

Application data has been created due to use shared preference data, databases and network caches data. This data has been manually clear on Settings -- > Apps (or) Application Manager --> Select the app you want to clear the data. --> Then click button clear data to erase the app from the Phone and SDCARD.

Applications like facebook, google+, gmail and some games captures more data on phone and SDCARD.

Once you clear the data of your app, all passwords and saved settings in app has been lost. So carefull to use this method.

Create the Class MyApplication

public class MyApplication extends Application {
 private static MyApplication instance;
 @Override
 public void onCreate() {
  super.onCreate();
  instance = this;
 }
 public static MyApplication getInstance(){
  return instance;
 }
 public void clearApplicationData() {
  File cache = getCacheDir();
  File appDir = new File(cache.getParent());
  if(appDir.exists()){
   String[] children = app…

Image Downloading Library - Picasso

Picasso is best image downloading and caching library using in android.

It's very fast to show the image from the URL.

Using picasso is very simple to do it.

From Gradle

      compile 'com.squareup.picasso:picasso:2.4.0'

Maven

   <dependency>
  <groupId>com.squareup.picasso</groupId>
  <artifactId>picasso</artifactId>
  <version>2.4.0</version>
</dependency>

If you are using Proguard, Just add the line,

-dontwarn com.squareup.okhttp.**

Download the JAR.

Samples and Library Click here.

Shake Detection Library

If you want to detect the shake sensor,

Implement like this,  SensorManager
public class Demo extends Activity implements ShakeDetector.Listener

Class Implementation, 
SensorManager sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
ShakeDetector sd = new ShakeDetector(this);
sd.start(sensorManager);

Interface
public void hearShake() {
Toast.makeText(this, "Now You're Shaking", Toast.LENGTH_SHORT).show();

}


 Get the Library from this link

Make a Marquee Textview in android

Made change like that,

In main.xml

<TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/text_content"
        android:singleLine="true" 
        android:ellipsize="marquee"
        android:marqueeRepeatLimit ="marquee_forever"
        android:scrollHorizontally="true"
        android:focusable="true"
        android:focusableInTouchMode="true" />

string.xml

<string name="text_content">This is a android marquee textview, to view the text by left to right on the screeen.Did you see that?</string>

Record the mobile screens through MyMobiler

Dedicate to all android developers, MyMobiler is very useful for android app developers.

Features:

Records the mobile screens.
Screen Capture.
Control your mobile device from the desktop.
Transfer the file between desktop/device
USB/Wifi Connection
Supports from Android OS 2.2 version.

Download the desktop application.

Download the mobile application.

Watch the tutorials about connecting the device and desktop in YouTube: https://www.youtube.com/watch?v=t0nrGuKw1Ac




Android Studio: Import the project from Eclipse

If you want Import the project from the Eclipse Workspace, Just follow these steps.

Go to the Eclipse workspace

File --> Export --> Select "Generate Gradle Build Files"

Select the projects want to Export --> Finish

After that Eclipse displays "you can import the build.gradle file into Android Studio"


Open Android Studio:

Import Projects --> Go to Eclipse Workspace --> Select the file "build.gradle"

Progress show the importing the gradle files and libraries, wait for few moments, after that projects has been successfully imported in Android Studio.

Install or Update android device driver directly from the Android SDK.

Sometimes your windows OS can't accept your android mobile drivers. If you can't install the driver, you can't able to run the apk through wired. Some of android devices can't install driver in your PC. 

So you have another way to run the program through wired, Just install ADB(Android Debug Bridge) directly from follow the way. 

Open --> Device Manager --> 
Now you can see your device as unsupported devices. 
Right click -->
Select Update driver Software--> 
Browse for device software on your computer --> 
Select Let me pick from a list of device drivers on my computer --> 
Select Show all devices -->  
Press the "Have Disk" Button --> 
Enter the path of Google USB Driver, [Example: D:\android-sdk\extras\google\usb_driver]

List of devices shown then Select --> "Android ADB Interface" from the list of device types

Confirm the installation of the driver by pressing --> "Yes".

Confirm the installation again by pressing -->…

Change the color of scroll bar

List view or Scroll view, if you need to change the scroll bar, Just add below the lines.

Create the xml file in drawable folder,

scrollbar_thumbs.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle" >

    <gradient
        android:angle="45"
        android:centerColor="#1D862D"
        android:endColor="#4D8F57"
        android:startColor="#1D862D" />

    <corners android:radius="8dp" />

</shape>

Add this on your listview like that,

android:scrollbarThumbVertical="@drawable/scrollbar_thumbs"




Using Custom fonts through XML.

1st Create the custom TextView through java,

package com.example.customfont;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Typeface;
import android.util.AttributeSet;
import android.util.Log;
import android.widget.TextView;
public class CustomTextView extends TextView {
    private static final String TAG = "TextView";
    public CustomTextView(Context context) {
        super(context);
    }
    public CustomTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        setCustomFont(context, attrs);
    }
    public CustomTextView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        setCustomFont(context, attrs);
    }
    private void setCustomFont(Context ctx, AttributeSet attrs) {
        TypedArray a = ctx.obtainStyledAttributes(attrs, R.styleable.TextViewPlus);
        String customFont = a.getString(R.styleable.CustomTextView_customFont);
        setCustomFont(ctx, cust…

Rotate Animation to ImageView

Rotate the image at center axis, by using Rotate Animation.

RotateAnimation anim = new RotateAnimation(0.0f, 360.0f, Animation.RELATIVE_TO_SELF, 0.5f,Animation.RELATIVE_TO_SELF, 0.5f);
        anim.setInterpolator(new LinearInterpolator());
        anim.setRepeatCount(Animation.INFINITE);
        anim.setDuration(1500);

and set into image like this

imageView.startAnimation(anim);

Change the font of ActionBar title

Change the font of ActionBar title using SpannableString.

Just follow the code.

SpannableString s = new SpannableString("It's a new font");
s.setSpan(new TypefaceSpan(this, "arial.ttf"), 0, s.length(),
       Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
getActionBar().setTitle(s);

Back Navigation in action bar

Sometimes most of developers now using ActionBar. They need to navigate button on top, if they need just add few lines in the code.

getActionBar().setDisplayHomeAsUpEnabled(true);

and

public boolean onOptionsItemSelected(MenuItem item) {
// Take appropriate action for each action item click
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
default:
return super.onOptionsItemSelected(item);
}
}


Using Color HEX codes in android

This is transparent level codes of hex codes.

100% — FF
95% — F2
90% — E6
85% — D9
80% — CC
75% — BF
70% — B3
65% — A6
60% — 99
55% — 8C
50% — 80
45% — 73
40% — 66
35% — 59
30% — 4D
25% — 40
20% — 33
15% — 26
10% — 1A
5% — 0D
0% — 00

If you provide 6 hex digits, that means RGB (2 hex digits for each value of red, green and blue).

If you provide 8 hex digits, it's an ARGB (2 hex digits for each value of alpha, red, green and blue respectively).

So actually you're changing from R=B4, G=55, B=55 to A=B5, R=55, G=55, B=55 which is why it's a mostly-transparent grey colour.

http://en.wikipedia.org/wiki/ARGB
http://developer.android.com/guide/topics/resources/more-resources.html#Color

if you want to some transparent level of color using in layout or widgets, just use like that
android:background:"#80FFFFFF"

Current Weather Demo

I'm so happy today, because today is my first web based application released in google play. previously i'm developed the some web based applications, but that's not in google play or any public markets. all are third party usage applications. Now it's time to move some small steps.

Current Weather Demo

Get the Current Weather Status by City ID and City Name

Before that, just signup and get the APPID from

http://openweathermap.org/register

Get the City ID and City name information from

http://openweathermap.org/help/city_list.txt

This is just a demo application, soon release the full functionality app.

You can download the source from Github

Download the App from Google Play



Check the connectivity status in android

Many of web based applications, check the internet connections, before done the web services.

You can set the permission for network state, like this

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

Code:

public boolean networkAvailability() {
ConnectivityManager connectivity = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity != null) {
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null)
for (int i = 0; i < info.length; i++)
if (info[i].getState() == NetworkInfo.State.CONNECTED) {
return true;
}

}
return false;
}


Convert the Kelvin into celsius

celsius= kelvin-273.15;

subtract 273.15 from kelvin value, you got the celsius value.

public String kevinToCelsius(String kelvin) {
double kel, celsius;
kel = Double.parseDouble(kelvin);
celsius = kel - 273.15;
return String.valueOf(celsius).substring(0, 4);
}

Change the Unix timestamp into date format

It's very interesting. Sometimes you got the result as unix timestamp from any backend apis or some results. It's simple method to convert the unix timestamp into date format.

// Unix timestamp into time format
public String getDateFormat(String dateformat) {
long dt = Long.parseLong(dateformat);
Date date = new Date(dt * 1000L); // *1000 is to convert seconds to
// milliseconds
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm"); // the
sdf.setTimeZone(TimeZone.getTimeZone("GMT-4"));
String formattedDate = sdf.format(date);
return formattedDate;
}

Slide Navigation

Slide Navigation

Most of new android applications uses the slide navigation. you can do left to right and right to left slide navigations. Like an gmail or facebook app.


I develop the slide navigation app demo.
Click Here to download from Google Play
Also you can get the source from GitHub
App and Source include the Colored ListView, Numbers to Words, Coloring textview examples..

Change the TextView color Continuosly using UIThread

Have a nice day. Now i write the code for changing the textview continuosly using UIThread.

Just try out.

handler = new Handler();
new Thread(new Runnable() {

@Override
public void run() {
final int totalCount=1000;
// TODO Auto-generated method stub
for(int i=0;i<totalCount;i++){
try {
runOnUiThread(new Runnable() {
                       public void run() {                        
Random r = new Random();
colorText.setTextColor(Color.rgb(r.nextInt(256),
r.nextInt(256), r.nextInt(256)));                          
                       }                       
                   });

Thread.sleep(totalCount);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

}).start();


Textview is continuously changing the textcolor. I'm set the 1000 milliseconds (1 Second).

Set other font to textview

To set the other fonts into textview, using Typeface.

Copy the fonts into assets folder,

Typeface type = Typeface.createFromAsset(getAssets(),"fonts/consolas.ttf");

textInfo.setTypeface(type);


Copy the Database into SDCARD

To copy the Database into SDCARD, you can use following code to do that,

InputStream myInput = new FileInputStream("/data/data/pack_name/databases/databasename.db");

File directory = new File("/sdcard/some_folder");
if (!directory.exists()) {
    directory.mkdirs();
}

OutputStream myOutput = new FileOutputStream(directory.getPath() + "/AppName.backup");

byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer)) > 0) {
    myOutput.write(buffer, 0, length);
}

myOutput.flush();
myOutput.close();
myInput.close();

Creating the Database in SDCARD

public class MyDataBase extends SQLiteOpenHelper {

    MyDataBase (final Context context) {        super(context, Environment.getExternalStorageDirectory()
                + File.separator + "/DataBase/" + File.separator
                + DATABASE_NAME, null, DATABASE_VERSION);
    }

Set the permission for READ and WRITE ACCESS.
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

Creating or Formatting the JSON.

JSON - JavaScript Object Notation is lightweight interchange format. JSON is more comfortable than XML. Also fast than the parsing. Most of web services is achieved through this JSON.

Some peoples are struggling to create and formatting the JSON strings and arrays. Here i give the links, its very useful for formatting and creating JSON. Just try it and give your feedback.

http://jsonviewer.stack.hu/ --> My Best Option.

http://jsonformat.com/

http://www.jsoneditoronline.org/

http://jsonformatter.curiousconcept.com/




Export the SQLITEDB into .csv or .pdf

If you want to export the sqlite db into .csv  or .pdf. You are going use the following libraries
OPENCSV-2.3.jariTextPDF – 5.2.1.jar
Task of Creating CSV
public class ExportCSVTask extends AsyncTask<String, Void, Boolean> {            private final ProgressDialog dialog = new ProgressDialog(                      MainActivity.this);
           protected void onPreExecute() {                 this.dialog.setMessage("Exporting database...");                 this.dialog.show();            }
           @Override            protected Boolean doInBackground(String... params) {                 File dbFile = getDatabasePath("basic_db");                 File exportDB = new File(Environment.getExternalStorageDirectory(),                            "");                 if (!exportDB.exists()) {                      exportDB.mkdirs();                 }                 File file = new File(exportDB, getDateTime() + ".csv");                 try {                      file.…

Link the TextView without using webview

Java TextView link; link = (TextView) findViewById(R.id.link); link.setMovementMethod(LinkMovementMethod.getInstance());
Strings.xml
<string name="link_google"><u><a href="http://google.co.in">Go to Google</a></u></string>
mainActivity.xml
<TextView         android:layout_width="wrap_content"         android:layout_height="wrap_content"         android:textColor="#80BFFF"         android:text="@string/link_google"         android:id="@+id/link"         android:layout_gravity="center_vertical"         />