Monday, 20 April 2015

Insert And Retrieve Data in Database SQLite

Hello All,

Today I am going to share the database connection in simple insert and delete actions in database.
In android for database functionality Sqlite database browser is used.

So let's move to our tasks that is to create ,insert and retrieve the data from DB..so to do this we have to follow following steps:

-> create a Database in Sqlite browser named employee.db

->create a table in employee db named user  table. this table will have following fields: id,name,city
and all are String type.

->Now in Employee.db ,the user table having three columns : id,name,city has been created
(if you want ,you can insert some records manually).

->after all these above steps save this db file into you projects Assets folder

Let's  move to the coding part:

->first design a layout having two buttons one is for Retrieve and another is for Insert and also will have a listview to retrieve the result. I have named it db_layout.xml  :

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:background="#C0C0C0" >

    <Button
        android:id="@+id/btn_retrieve"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Retrieve" />

    <Button
        android:id="@+id/btn_insert"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="36dp"
        android:layout_toRightOf="@+id/btn_retrieve"
        android:text="Insert" />

    <ListView
        android:id="@+id/list_dblayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/btn_retrieve"
        android:layout_marginTop="23dp"
      android:listSelector="@android:color/transparent" 
      android:divider="@android:color/transparent"
      android:cacheColorHint="@android:color/transparent">
    </ListView>

</RelativeLayout>


->Now copy and paste the dbhandler class from below.This class contains the codes to connect with the Db and also some methods to retrieve the data or insert the data.I have named it  DatabaseHandler.java


import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.List;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ContentValues;
import android.content.res.AssetManager;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class DatabaseHandler extends SQLiteOpenHelper {

public static final String TAG = "DatabaseHandler";

private SQLiteDatabase db;

private Activity activity;
String mydate;
     private String DB_PATH = "/data/data/com.example.demo" + "/databases/";

private static String DB_NAME = "employee.db";


public DatabaseHandler(Activity activity) throws IOException {
super(activity, DB_NAME, null, 1);
this.activity = activity;
boolean dbexist = checkdatabase();
if (dbexist) {
Log.d("Trong", "Database exists");
opendatabase();
} else {
System.out.println("Database doesn't exist");
createdatabase();
}
}

public void createdatabase() throws IOException {
boolean dbexist = checkdatabase();
if (dbexist) {
// System.out.println(" Database exists.");
} else {
this.getReadableDatabase();
try {
copydatabase();
} catch (IOException e) {
e.printStackTrace();
}
}
}

private boolean checkdatabase() {
// SQLiteDatabase checkdb = null;
boolean checkdb = false;
try {
String myPath = DB_PATH + DB_NAME;
Log.d("Trong", "DB_PATH + DB_NAME " + DB_PATH + DB_NAME);
File dbfile = new File(myPath);
// checkdb =
// SQLiteDatabase.openDatabase(myPath,null,SQLiteDatabase.OPEN_READWRITE);
checkdb = dbfile.exists();
} catch (SQLiteException e) {
Log.d("Trong", "Database doesn't exist");
}
return checkdb;
}


private void copydatabase() throws IOException {
        AssetManager am = activity.getAssets();
        OutputStream os = new FileOutputStream(DB_PATH + DB_NAME);
        byte[] b = new byte[1024];
        String[] files = am.list("");
        Arrays.sort(files);
        int r;
      
            InputStream is = am.open("employee.db");
            while ((r = is.read(b)) != -1) {
                os.write(b, 0, r);
            }
            Log.i("BABY_DATABASE_HELPER", "Copying the database (part " 
                    + " of 9)");
            is.close();
        
        os.close();
    }

public void opendatabase() throws SQLException {
// Open the database
String mypath = DB_PATH + DB_NAME;
db = SQLiteDatabase.openDatabase(mypath, null,
SQLiteDatabase.OPEN_READWRITE);

}

public synchronized void close() {
if (db != null) {
db.close();
}
super.close();
}




@Override
public void onCreate(SQLiteDatabase db) {

}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

}

public void deleteAll()
{
   SQLiteDatabase db = this.getWritableDatabase();
   db.delete("user",null,null);
   db.close();
}

public int insertvalue(String id, String str_name, String str_city) {
Log.e("InsertValues","sdk");
ContentValues cvalue=new ContentValues();
cvalue.put("id",id);
cvalue.put("name",str_name);
cvalue.put("city",str_city);

           db.insert("user", null, cvalue);
return 1;
}

public ArrayList<DbEntity> getInputMonths() {
 
 ArrayList<DbEntity> ittoentity = new ArrayList<DbEntity>();
 
 String selectQuery = "SELECT  * FROM "+"user";
 Log.d("rawquery", "inputs"+selectQuery);
 Cursor cursor = db.rawQuery(selectQuery, null);
        if (cursor.moveToFirst()) {
  do {
  DbEntity itto = new DbEntity();
  itto.set_name(cursor.getString(1));
   itto.set_city(cursor.getString(2));
   ittoentity.add(itto);
  } while (cursor.moveToNext());
 }

 return ittoentity;
}

->Now we have to write the code to start activity and click on buttons etc. means MainActivity class.
I have named this class DbActivity.java. And following is the code: 

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;

import com.demo.db.DatabaseHandler;
import com.demo.db.DbEntity;



import android.app.Activity;
import android.app.Dialog;
import android.database.SQLException;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

public class DbActivity extends  Activity{

Button btn_retreive,btn_insert;
DatabaseHandler db;
EditText edttxt_name, edttxt_city ;
Dialog dialog;
     Button btn_submit;
     ListView list ;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.db_layout);

btn_retreive = (Button)findViewById(R.id.btn_retrieve);
btn_insert= (Button)findViewById(R.id.btn_insert);
list = (ListView)findViewById(R.id.list_dblayout);

btn_retreive.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
RetriveDataFromDB();
}
});
btn_insert.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
dialog = new Dialog(DbActivity.this);
           dialog.getWindow();
         dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
           dialog.setContentView(R.layout.insert_dialog_layout);
          dialog.setCancelable(true);
           dialog.show();
           
     edttxt_name = (EditText)dialog.findViewById(R.id.edttxt_name_insertdialog);
    edttxt_city = (EditText)dialog.findViewById(R.id.edttxt_city_insertdialog);
           
           Button btn_submit = (Button)dialog.findViewById(R.id.btn_insert_insertdialog);
           
           btn_submit.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
String str_name = "",str_city="";

str_city = edttxt_city.getText().toString();
str_name = edttxt_name.getText().toString();

if (str_city.equals("")||(str_name.equals(""))) {
Toast.makeText(DbActivity.this,"Please fill all the fields!!",Toast.LENGTH_LONG).show();
}
else
{
insertIntoDb("11",str_name,str_city);
}
}

private void insertIntoDb(String id,
String str_name, String str_city) {
try {
db = new DatabaseHandler(DbActivity.this);
} catch (IOException e) {
e.printStackTrace();
}
db.opendatabase();

int i = db.insertvalue(id, str_name, str_city);

if (i==1) {
Toast.makeText(DbActivity.this,"Infomation saved succesfully.",Toast.LENGTH_LONG).show();
dialog.dismiss();

}
else
{
Toast.makeText(DbActivity.this,"Something went wrong.Please try again later.",Toast.LENGTH_LONG).show();
dialog.dismiss();
}

try {
db.close();
} catch (Exception e) {
e.printStackTrace();
}

}
});
           
}
});
}
protected void RetriveDataFromDB() {
try {
db = new DatabaseHandler(DbActivity.this);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
   db.createdatabase();

  } catch (IOException ioe) {
   throw new Error("Unable to create database");
  }
  try {
   db.opendatabase();
  } catch (SQLException sqle) {
   throw sqle;
  }
  
  ArrayList<DbEntity>  menuItems = new  ArrayList<DbEntity>();
  menuItems.clear();
 
ArrayList<DbEntity> contacts = db.getInputMonths();  
 
 
Log.e("Array",">>"+menuItems.size());
list.setAdapter(null);
list.setAdapter(new DbRetrieveAdapter(DbActivity.this,contacts));
}

}

->In the above class .I have write code to click on insert ,retrieve button ..call functions from DatabaseHandler class to insert data and to retrive data in listview .I have used a dialog on click on Insert button ,this dialog will have two edit boxes which are used to insert name,city value from the user, the design is for the dialog to insert the values is as follows: insert_dialog_layout.xml


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="300sp"
    android:layout_height="200sp"
    android:orientation="vertical" 
    android:background="#ff9900">

    <EditText
        android:id="@+id/edttxt_name_insertdialog"
        android:layout_width="match_parent"
        android:layout_height="50sp"
       android:layout_marginLeft="8sp"
       android:layout_marginRight="8sp"
       android:hint="Name"
       android:singleLine="true"
       android:layout_marginTop="15sp"
       android:textColor="#000000"
       >

    </EditText>
    
        <EditText
        android:id="@+id/edttxt_city_insertdialog"
        android:layout_width="match_parent"
        android:layout_height="50sp"
       android:layout_marginLeft="8sp"
       android:layout_marginRight="8sp"
       android:hint="City"
       android:singleLine="true"
       android:layout_marginTop="15sp"
       android:textColor="#000000"
       >

    </EditText>

        <Button
            android:id="@+id/btn_insert_insertdialog"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
               android:layout_marginTop="15sp"
            android:text="INSERT" />

</LinearLayout>


->Next I have used the adapter to retrieve the value from the DB in listview the design for the list view item is as follows:  layout_grid_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="match_parent"
    android:orientation="vertical" >
    

    <LinearLayout android:layout_width="match_parent"
        android:layout_height="60sp"
        android:background="#FFFFFF"
        android:layout_margin="5sp"
        android:orientation="vertical">

        <TextView
            android:id="@+id/txt_name_griditemlayout"
            android:layout_width="match_parent"
            android:layout_marginLeft="5sp"
            android:layout_marginRight="5sp"
            android:layout_marginTop="5sp"
            android:layout_height="wrap_content"
            android:text="Name"
              android:textColor="#000000"
              android:textSize="13sp" />

        <TextView
            android:id="@+id/txt_city_griditemlayout"
           
            android:layout_height="wrap_content"
            android:text="City"
            android:textColor="#000000"
            android:textSize="13sp"
             android:layout_width="match_parent"
            android:layout_marginLeft="5sp"
            android:layout_marginRight="5sp"
         
            android:layout_marginTop="10sp" />

    </LinearLayout>

</LinearLayout>


-> The DbRetrieveAdapter.java will also be needed : 

import java.util.ArrayList;
import java.util.HashMap;

import com.demo.db.DbEntity;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;


public class DbRetrieveAdapter extends BaseAdapter {

    private LayoutInflater mLayoutInflater = null;
private Activity activity;
private ViewHolder holder;
private String name,cat_id,str_flag="";

ArrayList<DbEntity>  Show;
 int i = 0 ;


private class ViewHolder {
public TextView tvName,tvCity;

}


public DbRetrieveAdapter(Activity activity2,
ArrayList<DbEntity> contacts) {
this.activity = activity2;
this.Show = contacts;
mLayoutInflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
 
}

@Override
public int getCount() {
return Show.size();
}

@Override
public Object getItem(int position) {
return Show.get(position);
}

@Override
public long getItemId(int position) {
return position;
}

@Override
public View getView(final int position, View convertView, ViewGroup parent) {

if (convertView == null) {
convertView = mLayoutInflater.inflate(R.layout.layout_grid_item, null);

holder = new ViewHolder();
holder.tvName = (TextView) convertView.findViewById(R.id.txt_name_griditemlayout);
holder.tvCity= (TextView) convertView.findViewById(R.id.txt_city_griditemlayout);


convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}

holder.tvName.setText("Name : "+Show.get(position).get_name()); 
holder.tvCity.setText("City : "+Show.get(position).get_city());

return convertView;
}

}


->Now in last DbEntity.java:  

public class DbEntity {

private String _name,_city;
public DbEntity() {
super();
}
        public DbEntity(String _name,String _city) {
super();
this._name = _name;
this._city = _city;

}
       public String get_name() {
return _name;
}
       public void set_name(String _name) {
this._name = _name;
}
        public String get_city() {
return _city;
}
public void set_city(String _city) {
this._city = _city;
}
}


->This is the code to insert and retrieve the data from the DB using SQLite .Below is the screen shot:




Sunday, 23 November 2014

removing and add one value in array saved in Parse table with Parse.com

Hello all,

In the Previous Post ,I have explained how to add the array and Parse File in Parse table

Now let's move to another step in Parse.com series which is to remove one value from the array and also adding one value in an array which is saved in Parse table 

The difference : in the Previous Post I have explained to add the whole array in Parse table , But In this post I am going to explain how to modify (add/remove) the array which is saved in Parse DB

Let's make a Parse table named "channel" having  usersArray (datatype : array) column 

Now first we will add a value in the usersArray in "channel" . For this we have to follow following steps: 
1: Assume an List<String> list1= new ArrayList<String>
2: Check usersArray  is null or not
3: Assign the value of usersArray to list1
4: Check that list1 contains that value (which is need to be added)
5: If not Add the value in list1 .
6: save the list1 in usersArray in channel table.

For this please check the below code to add one value in array :

                 List<String> list11 =  new ArrayList<String>();
String object_id = "123456"; //change this according to your need.
ParseQuery<ParseObject> pQuery = ParseQuery.getQuery("Channel");
pQuery.whereEqualTo("objectId",object_id);
pQuery.findInBackground(new FindCallback<ParseObject>() {

@Override
public void done(List<ParseObject> list, ParseException e) {
if (e==null) {
if (list.size()>0) {
ParseObject p = list.get(0);
if (p.getList("usersArray")!=null) {
list11 =  p.getList("usersArray");
}
else
{
list11= null;
}

if (list11!=null) {
if (!list11.contains(user_id)) {
list11.add(user_id);
}
                                                }
if (list11!=null) 
p.put("usersArray", list11);
else
p.put("usersArray",null );
   p.saveInBackground(new SaveCallback() {

@Override
public void done(ParseException arg0) {
                     Toast.makeText(mActivity,"done",Toast.LENGTH_LONG).show();
}
});
}
}
}
}

});


Now let's move to remove one value from the usersArray in "channel" . For this we have to follow following steps: 
1: Assume an List<String> list1= new ArrayList<String>
2: Check usersArray  is null or not
3: Assign the value of usersArray to list1
4: Check that list1 contains that value (which is need to be added)
5: If yes remove the value from list1 .
6: save the list1 in usersArray in channel table again.

For this please check the below code to remove one value from saved array :

  final List<String> list11 =  new ArrayList<String>();
String object_id = "123456"; //change this according to your need.
ParseQuery<ParseObject> pQuery = ParseQuery.getQuery("Channel");
pQuery.whereEqualTo("objectId",object_id);
pQuery.findInBackground(new FindCallback<ParseObject>() {

@Override
public void done(List<ParseObject> list, ParseException e) {
if (e==null) {
if (list.size()>0) {
ParseObject p = list.get(0);
if (p.getList("usersArray")!=null) {
list11 =  p.getList("usersArray");
}
else
{
list11= null;
}

if (list11!=null) {
if (list11.contains(user_id)) {
list11.remove(user_id);
}
                                       }
if (list11!=null) 
p.put("usersArray", list11);
else
p.put("usersArray",null );
p.saveInBackground(new SaveCallback() {

@Override
public void done(ParseException arg0) {
              Toast.makeText(mActivity,"done",Toast.LENGTH_LONG).show();
}
});
}
} }}
});

That's all..for remove and add one value from/to the array which is saved in Parse table with Parse.com.
In above code I have applied condition on the basis of objectId  you have to change according to your need.
Please leave any comment if you have any query.Thanks...



Sunday, 16 November 2014

adding array and Parse file in Parse table with Parse.com

Hello all,

In the Previous Blog I have explained to add and remove different data types in Parse table.

Now again adding the next step in the Parse.com series I am sharing the code to add array in Parse table also in the post I will share the code to add the Parse File in Parse table .

Let's make a table named "channel" having following columns with the data types :

1.  pic (datatype: File(parse file))
2.  usersArray (datatype : array)

Lets us assume the List<String>  mAryUsers =  new ArrayList<String>(); ,it is used to save the array of users.
Lets  us assume the  byte [] imagearray = null; it is used to upload the pic in Parse table

Note:  -> image ,pdf etc. will upload as a Parse File in Parse table  in the form of  byte [] ,Here I am uploading an image picked from gallery ,then change it to byte[] then will upload to the parse table(code below)

-> mAryUsers  will have the array of name of users which will save in array column in Parse table .

Lets take a look on the code to add the byte []  and  List<String>  in the columns pic (datatype: File(parse file)) and usersArray (datatype : array)

    final ParseObject testObject = ParseObject.create("channel");

if (mAryUsers!=null) {

 testObject.put("usersArray",mAryUsers);//ADDING ARRAY IN "usersArray" column
}

if (imagearray!=null) {
final ParseFile  file = new ParseFile("123.png",imagearray);
                file.saveInBackground(new SaveCallback() {

@Override
public void done(ParseException arg0) {
testObject.put("pic", file);//ADDING IMAGE IN "pic" column
testObject.saveInBackground();
}
});
       
}
              testObject.saveInBackground(new SaveCallback() {

@Override
public void done(ParseException e) {
  Log.e("Exception", "get: " +e);
         if (e == null) {
 Toast.makeText(getApplicationContext(),"Channel Added                Succesfully",Toast.LENGTH_LONG).show();
  }
                                  else {
   
        Toast.makeText(getApplicationContext(),"Something went wrong.Please try again later",Toast.LENGTH_LONG).show();
  }
}
});

For more info you can  see this: Add array in parse Table in right way

That's all for adding the Parse file and array in Parse table with the help of Parse.com.






Add different types of data in Parse Table and fetch them from the Parse table in Parse.com

Hello all,

In the previous post I have explained how to signup and login as a Parse User in Parse Table with the help of Parse.com sdk

Now I am going to add one another tutorial in Parse.com series.

Today I am going to share the code to add different types of data(string,int,boolean) in the Parse Table and then explains the code to fetch them.

First you have to create a table in Parse database manually,then add the columns with different data types according to your need

I have made a Parse Table named "channel" and add the following columns  in it :

1. name(String)
2. isPrivate(boolean)
3. maxSize(int)

Now below is the code to add the values to the Parse table(here  "channel") in runtime:

boolean b_privacy = false;
String s_name = "XYZ";
int max_size = 50;

 final ParseObject testObject = ParseObject.create("channel");

                 testObject.put("isPrivate",b_privacy);
testObject.put("maxSize",max_size);
 testObject.put("name",s_name);
 testObject.saveInBackground(new SaveCallback() {

@Override
public void done(ParseException e) {

 if (e == null) {
Toast.makeText(getApplicationContext(),"Channel Added            Succesfully",Toast.LENGTH_LONG).show();
 } 
                                        else {
Toast.makeText(getApplicationContext(),"Something went wrong.Please try again later",Toast.LENGTH_LONG).show();

   }
}
});

After that lets move to the second part of the post that is to fetch the data from the Parse table in runtime:

Let's us assume to fetch the data from the "channel" table.Now we have to fetch the name(String) , isPrivate (boolean) and  maxsize(int).

Here is the code to fetch the data from "channel" table:

Note: Here I am fetching the data on the basis of objectId.

            ParseQuery<ParseObject> query = ParseQuery.getQuery("channel");
   query.whereEqualTo("objectId",objid);
   query.findInBackground(new FindCallback<ParseObject>() {
       public void done(List<ParseObject> userList, ParseException e) {
       
                if (e == null) {
          
            Log.d(">>",">>"+userList.size());
            if (userList.size()>0) {

        ParseObject p = userList.get(0);

String s_name = p.getString("name");
boolean is_private = p.getBoolean("isPrivate");
int max_size =p.getInt("maxSize");

        }} 
              else {
               // error
            Log.d(">>",">>"+e);
           }
       }
   });


Note : if you want to fetch or add the data in Parse User table you have to replace this line :
ParseQuery<ParseObject> query = ParseQuery.getQuery("channel");
by
ParseQuery<ParseObject> query = ParseQuery.getQuery("_User");

->"_User" is used to represent the ParseUser table .

That's all .Hope it will be useful for you . thanks


Friday, 7 November 2014

SignUp and login as a Parse User with Parse.com(Parse sdk)


SignUp And Login Screen

   Hello friends,

Today I am going to started new series of code of Parse.com(Parse sdk) .It is a new open source sdk ,used by many android ,iphone apps.

Today I am going to share the code to signup and login with the help of Parse.com.

Parse.com is mainly a package collection of many Parse classes,which are used for many different functionalities ,one of these parse classes is Parse User class .It is used to register any user with parse table .

For getting started with Parse sdk read the tutorial: Android Quick Start Guide
For more info please read android tutorial of Parse.com 

Now let's move to the actual topic of this blog:

For create account ,I am only sharing the java class as the xml is very easy

SignUpActivity.java

import com.constants.Alert;
import com.constants.ConnectionDetector;
import com.constants.FunctionsValue;
import com.parse.ParseException;
import com.parse.ParseFile;
import com.parse.ParseUser;
import com.parse.SaveCallback;
import com.parse.SignUpCallback;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class SignUpActivity extends Activity{

EditText edttxt_uname,edttxt_email,edttxt_password,edttxt_phone;
String str_uname,str_email,str_password,str_phone;
Button btn_submit;
ConnectionDetector cd;
ProgressDialog dlg;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.signup_layout);
inItUi();
inItAction();
}

private void inItAction() {
btn_submit.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
str_email = edttxt_email.getText().toString();
str_uname = edttxt_uname.getText().toString();
str_password = edttxt_password.getText().toString();
str_phone = edttxt_phone.getText().toString();
if (str_uname.equals("")) {
Alert.alertOneBtn(SignUpActivity.this,"Empty","Please enter your name!");
}
else if (str_email.equals("")) {
Alert.alertOneBtn(SignUpActivity.this,"Empty","Please enter your email!");
}
else if (str_password.equals("")) {
Alert.alertOneBtn(SignUpActivity.this,"Empty","Please enter your password!");
}
else if (str_phone.equals("")) {
Alert.alertOneBtn(SignUpActivity.this,"Empty","Please enter your phone number!");
}
else if (!FunctionsValue.checkEmail(str_email)) {
Alert.alertOneBtn(SignUpActivity.this,"Empty","Email is not valid!");
}
else if(!cd.isConnectingToInternet())
{
Alert.alertOneBtn(SignUpActivity.this, "No Internet Connection",
"You don't have internet connection.");

}
else
{
if (Build.VERSION.SDK_INT >= 11 ) {
  dlg = new ProgressDialog(SignUpActivity.this,AlertDialog.THEME_HOLO_LIGHT );
     } else {
        dlg = new ProgressDialog(SignUpActivity.this);
       }
       dlg.setMessage("Registering...");
       dlg.show();
signUp(str_uname, str_email, str_password,str_phone);

}

}
});
}

protected void signUp(String name, String email,
String password, String str_phone2) {
final ParseUser user = new ParseUser();

user.setUsername(name);
user.setPassword(password);
user.setEmail(email);
user.put("phone", str_phone2);


user.signUpInBackground(new SignUpCallback() {

 public void done(ParseException e) {
 dlg.dismiss();
   if (e == null) {
     signUpMsg("Account Created Successfully");

     startActivity(new Intent(getApplicationContext(),LoginActivity.class));
   } else {
    
    Log.d("error",">>"+e);
    signUpMsg("Something went wrong.Please try again later!!");
   }
 }
});

}
protected void signUpMsg(String msg) {
Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT).show();
}

private void inItUi() {
cd = new ConnectionDetector(getApplicationContext());
edttxt_email = (EditText)findViewById(R.id.edttxt_email_signuplayout);
edttxt_password = (EditText)findViewById(R.id.edttxt_password_signuplayout);
edttxt_phone = (EditText)findViewById(R.id.edttxt_phone_signuplayout);
edttxt_uname = (EditText)findViewById(R.id.edttxt_username_signuplayout);
btn_submit = (Button)findViewById(R.id.btn_submit_signuplayout);
}


}


In above code I have used some classes for showing alert,detect connection and save value in shared preference,you can changed it according to the requirement.

LoginActivity.java:

import com.constants.Alert;
import com.constants.ConnectionDetector;
import com.constants.PreferenceSetting;
import com.parse.LogInCallback;
import com.parse.ParseException;
import com.parse.ParseUser;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class LoginActivity extends Activity{
EditText edttxt_username,edttxt_password;
String str_uname,str_password;
Button btn_submit;
ConnectionDetector cd;
ProgressDialog dlg;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.login_layout);
inItUi();
inItAction();
}
private void inItAction() {
btn_submit.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
str_uname = edttxt_username.getText().toString();
str_password = edttxt_password.getText().toString();
if (str_uname.equals("")) {
Alert.alertOneBtn(LoginActivity.this,"Empty","Please enter your username!");

}
else if (str_password.equals("")) {
Alert.alertOneBtn(LoginActivity.this,"Empty","Please enter your password!");

}
else
{
boolean isInternetPresent = cd.isConnectingToInternet();
// check for Internet status
if (isInternetPresent) {
if (Build.VERSION.SDK_INT >= 11 ) {
  dlg = new ProgressDialog(LoginActivity.this,AlertDialog.THEME_HOLO_LIGHT );
     } else {
        dlg = new ProgressDialog(LoginActivity.this);
       }
       dlg.setMessage("Please wait...");
       dlg.show();
attemptLogin(str_uname,str_password);
     
} else {
// Internet connection is not present
// Ask user to connect to Internet
Alert.alertOneBtn(LoginActivity.this, "No Internet Connection",
"You don't have internet connection.");
}

}

}
});
}
protected void attemptLogin(String str_email2, String str_password2) {
ParseUser.logInInBackground(str_email2, str_password2, new LogInCallback() {
@Override
public void done(ParseUser user, ParseException e) {
dlg.dismiss();
if(e == null)
{
Log.d(">>>",">>"+user.getObjectId()+">>>"+user.getUsername());
PreferenceSetting.SaveLoginInfo(LoginActivity.this,user.getObjectId(),usergetUsername());
startActivity(new Intent(getApplicationContext(),HomeTabActivity.class));
}
else
loginUnSuccessful();
}
});
}

protected void loginUnSuccessful() {
    Alert.alertOneBtn(LoginActivity.this,"Login", "Username or Password is invalid.");
edttxt_username.setText("");
edttxt_password.setText("");

}
private void inItUi() {
cd = new ConnectionDetector(getApplicationContext());
edttxt_password = (EditText)findViewById(R.id.edttxt_password_loginlayout);
edttxt_username = (EditText)findViewById(R.id.edttxt_username_loginlayout);
btn_submit = (Button)findViewById(R.id.btn_submit_loginlayout);

}
}


The above two classes are used for signup and login with parse sdk.I will share more code related to parse sdk in next blogs.If you faced any difficulty to understand this code ,please mention in comment.


Advanced Kotlin Coroutines : Introduction

 Hi,  Today I am unwraping the topic in Kotin world i.e. Coroutine . If you want to get started with Kotlin coroutine and ease your daily de...