Wednesday 28 January 2015

Building an Android Application Using Parse

PART 1

1. Create Account in Parse.com

2. Create New application from Dashboard console
3. Go to - >"Settings" - > "Keys" can see Application ID and Clint ID .




PART 2

1. Download External Libraries from  https://parse.com/downloads/android/Parse/latest


PART 3

1. Create new application in Eclipse with min SDK version 14

2. Put External all .jar files (will get from Parse-1.5.2.zip) inside libs folder. then build application.



3. Add permission on application manifest file.

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

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



4. Create one new java Class . Here Task.java

import com.parse.ParseClassName;

import com.parse.ParseObject;

@ParseClassName("Task")

public class Task extends ParseObject{
  public Task(){

  }

  public boolean isCompleted(){
      return getBoolean("completed");
  }
  public void setCompleted(boolean complete){
      put("completed", complete);
  }
  public String getDescription(){
      return getString("description");
  }
  public void setDescription(String description){
      put("description", description);
  } }



5. Create one new java class to fetch data from server . Here TaskAdapter

import java.util.List;

import android.content.Context;
import android.graphics.Paint;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

public class TaskAdapter extends ArrayAdapter<Task> {

  private Context mContext;
  private List<Task> mTasks;

  public TaskAdapter(Context context, List<Task> objects) {

      super(context, R.layout.task_row_item, objects);
      this.mContext = context;
      this.mTasks = objects;
  }
  public View getView(int position, View convertView, ViewGroup parent){
      if(convertView == null){
          LayoutInflater mLayoutInflater = LayoutInflater.from(mContext);
          convertView = mLayoutInflater.inflate(R.layout.task_row_item, null);
      }

      Task task = mTasks.get(position);


      TextView descriptionView = (TextView) convertView.findViewById(R.id.task_description);


      descriptionView.setText(task.getDescription());


      if(task.isCompleted()){

          descriptionView.setPaintFlags(descriptionView.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
      }else{
          descriptionView.setPaintFlags(descriptionView.getPaintFlags() & (~Paint.STRIKE_THRU_TEXT_FLAG));
      }
      return convertView;
  }
}



6. Create activity . Here "Todoactivity.java"  & Activity_todo.xml





7. Replace Activity_todo.xml file with given structure .

<LinearLayout 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"
    android:orientation="vertical"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:weightSum="2"
    tools:context=".TodoActivity" >

    <ListView

        android:id="@+id/task_list"
        android:layout_height="0dp"
        android:layout_width="match_parent"
        android:stackFromBottom="true"
        android:layout_weight="1" />

    <LinearLayout

        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:orientation="horizontal" >

        <EditText

            android:id="@+id/task_input"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:ems="10"
            android:hint="Enter a Task"
            android:inputType="text" >
            <requestFocus />
        </EditText>

        <Button

            android:id="@+id/submit_button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:onClick="createTask"
            android:text="Submit" />
    </LinearLayout>

</LinearLayout>




8. Create new xml file to show DB data in listview . Here "task_row_item.xml"

<?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:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:orientation="horizontal" >

    <TextView

        android:id="@+id/task_description"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical"
        android:layout_weight="1"
        android:textAppearance="?android:attr/textAppearanceMedium" />

</LinearLayout>







9. Add below functions in OnCreate method of TodoActivity.java

 Parse.initialize(this, //Application ID, //Client ID);

        ParseAnalytics.trackAppOpened(getIntent());
        ParseObject.registerSubclass(Task.class);
       
        TaskInput = (EditText) findViewById(R.id.task_input);
        ListView = (ListView) findViewById(R.id.task_list);
            
        mAdapter = new TaskAdapter(this, new ArrayList<Task>());
        ListView.setAdapter(mAdapter);
        Timer timer = new Timer();
        timer.scheduleAtFixedRate(new TimerTask() {
          @Override
         public void run() {
          // TODO Auto-generated method stub
           runOnUiThread(new  Runnable() {
           public void run() {
            if(questionInterval == 5) {
             questionInterval = 0;
            }       
            questionInterval++;
            updateData();
           
           }
          });
     
         }
        }, 1000, 1000);


10. Add below function after OnCreate method

 public void createTask(View v) {

        if (TaskInput.getText().length() > 0){
            Task t = new Task();
            t.setDescription(name +":" +TaskInput.getText().toString());
            t.setCompleted(false);
            t.saveEventually();
            TaskInput.setText("");
        }
    }
   
    public void updateData(){
       ParseQuery<Task> query = ParseQuery.getQuery(Task.class);
       query.findInBackground(new FindCallback<Task>() {
             
           @SuppressWarnings("static-access")
   @Override
           public void done(List<Task> tasks, ParseException error) {
               if(tasks != null){
                   mAdapter.clear();
                   mAdapter.addAll(tasks);
                   ListView.setTranscriptMode(ListView.TRANSCRIPT_MODE_ALWAYS_SCROLL);
               }
           }
       });
     }
   
===================================








Tuesday 6 January 2015

Find Location (Geolocation,Address)



Requirements  :


1. import library project. 
Eg: (E:\Android Setup\sdk\extras\google\google_play_services\libproject\google-play-services_lib).
2.Add reference with main project .
3.XML file to show the result.
4.Java class to access location.


public class MainActivity extends Activity implements
GooglePlayServicesClient.ConnectionCallbacks,
GooglePlayServicesClient.OnConnectionFailedListener

{

  LocationClient mLocationClient;
  private TextView addressLabel;
  private TextView locationLabel;
  private Button getLocationBtn;

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

      locationLabel = (TextView) findViewById(R.id.locationLabel);
     addressLabel = (TextView) findViewById(R.id.addressLabel);
     getLocationBtn = (Button) findViewById(R.id.getLocation);

     getLocationBtn.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {
           displayCurrentLocation();
        }
     });
 
     // Create the LocationRequest object
     mLocationClient = new LocationClient(this, this, this);
  }
  @Override
  protected void onStart() {
     super.onStart();
     // Connect the client.
     mLocationClient.connect();
     locationLabel.setText("Got connected....");
  }
  @Override
  protected void onStop() {
     // Disconnect the client.
     mLocationClient.disconnect();
     super.onStop();
     locationLabel.setText("Got disconnected....");
  }
  @Override
  public void onConnected(Bundle dataBundle) {
     // Display the connection status
     Toast.makeText(this, "Connected", Toast.LENGTH_SHORT).show();
  }
  @Override
  public void onDisconnected() {
     // Display the connection status
     Toast.makeText(this, "Disconnected. Please re-connect.",
     Toast.LENGTH_SHORT).show();
  }
  @Override
  public void onConnectionFailed(ConnectionResult connectionResult) {
     // Display the error code on failure
     Toast.makeText(this, "Connection Failure : " +
     connectionResult.getErrorCode(),
     Toast.LENGTH_SHORT).show();
  }
  public void displayCurrentLocation() {
     // Get the current location's latitude & longitude
     Location currentLocation = mLocationClient.getLastLocation();
     String msg = "Current Location: " +
     Double.toString(currentLocation.getLatitude()) + "," +
     Double.toString(currentLocation.getLongitude());
   
     // Display the current location in the UI
     locationLabel.setText(msg);
   
     // To display the current address in the UI
     (new GetAddressTask(this)).execute(currentLocation);
  }
  /*
   * Following is a subclass of AsyncTask which has been used to get
   * address corresponding to the given latitude & longitude.
   */
  private class GetAddressTask extends AsyncTask<Location, Void, String>{
     Context mContext;
     public GetAddressTask(Context context) {
        super();
        mContext = context;
     }

     /*
      * When the task finishes, onPostExecute() displays the address.
      */
     @Override
     protected void onPostExecute(String address) {
        // Display the current address in the UI
        addressLabel.setText(address);
     }
     @Override
     protected String doInBackground(Location... params) {
        Geocoder geocoder =
        new Geocoder(mContext, Locale.getDefault());
        // Get the current location from the input parameter list
        Location loc = params[0];
        // Create a list to contain the result address
        List<Address> addresses = null;
        try {
           addresses = geocoder.getFromLocation(loc.getLatitude(),
           loc.getLongitude(), 1);
        } catch (IOException e1) {
           Log.e("LocationSampleActivity",
           "IO Exception in getFromLocation()");
           e1.printStackTrace();
           return ("IO Exception trying to get address");
        } catch (IllegalArgumentException e2) {
           // Error message to post in the log
           String errorString = "Illegal arguments " +
           Double.toString(loc.getLatitude()) +
           " , " +
           Double.toString(loc.getLongitude()) +
           " passed to address service";
           Log.e("LocationSampleActivity", errorString);
           e2.printStackTrace();
           return errorString;
        }
        // If the reverse geocode returned an address
        if (addresses != null && addresses.size() > 0) {
           // Get the first address
           Address address = addresses.get(0);
           /*
           * Format the first line of address (if available),
           * city, and country name.
           */
           String addressText = String.format(
           "%s, %s, %s",
           // If there's a street address, add it
           address.getMaxAddressLineIndex() > 0 ?
           address.getAddressLine(0) : "",
           // Locality is usually a city
           address.getLocality(),
           // The country of the address
           address.getCountryName());
           // Return the text
           return addressText;
        } else {
           return "No address found";
        }
     }
  }// AsyncT

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

}


XML LAYOUT

<LinearLayout 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"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <Button
        android:id="@+id/getLocation"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/get_location" />

    <TextView
        android:id="@+id/locationLabel"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <TextView
        android:id="@+id/addressLabel"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</LinearLayout>






Notification In Android Development


Creating notification from UI .
Requirements :

1. XML Layout with three Edittext and one Button2. Java file for coding.

public class NotificationActivity extends Activity
{
NotificationManager NM;
  EditText one,two,three;
 
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
one = (EditText)findViewById(R.id.editText1);
two = (EditText)findViewById(R.id.editText2);
three = (EditText)findViewById(R.id.editText3);
             }
                @SuppressWarnings("deprecation")
         public void notify(View vobj){
String title = one.getText().toString();
String subject = two.getText().toString();
String body = three.getText().toString();
NM=(NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
Notification notify=new Notification(android.R.drawable.
stat_notify_more,title,System.currentTimeMillis());
PendingIntent pending=PendingIntent.getActivity(
getApplicationContext(),0, new Intent(),0);
notify.setLatestEventInfo(getApplicationContext(),subject,body,pending);
NM.notify(0, notify);
}
}

XML Layout


<LinearLayout 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"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

       <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:onClick="notify"
        android:text="@string/notification" />

    <EditText
        android:id="@+id/editText1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:ems="10" />

    <EditText
        android:id="@+id/editText2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:ems="10" />

    <EditText
        android:id="@+id/editText3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:ems="10" />

</LinearLayout>


How to do text writing animation?  In Android Development we do not have the option to use any other custom font in our default Tex...