Tuesday, 30 August 2016

SQLite Database Example | insert data into database and show the data into Custom Listview

ScreenShots:-


Step 1:- main_activity.xml

<?xml version="1.0" encoding="utf-8"?>
<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:gravity="center_vertical">
    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Name"
        android:id="@+id/edtName"/>
    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Phone"
        android:id="@+id/edtPhone"/>
   <TextView
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:text="Gender"
       android:textSize="25sp"/>
    <RadioGroup
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/rdGroup"
        android:orientation="horizontal">
        <RadioButton
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="wrap_content"
        android:id="@+id/rdMale"
        android:text="Male"/>
        <RadioButton
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="wrap_content"
            android:id="@+id/rdFemale"
            android:text="FeMale"/>
    </RadioGroup>
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Insert"
        android:id="@+id/btnInsert"/>
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="View"
        android:id="@+id/btnView"/>
</LinearLayout>


Step 2:- MainActivity.java

package androidhubb.sqliteexample;

import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
    EditText edtname,edtNumber;
    Button btnInsert,btnView;
    RadioButton rdMale,rdFemale;
    RadioGroup rdGroup;
    SQLiteDatabase db;
    String gender="";
    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        edtname=(EditText)findViewById(R.id.edtName);
        edtNumber=(EditText)findViewById(R.id.edtPhone);
        btnInsert=(Button) findViewById(R.id.btnInsert);
        btnView=(Button) findViewById(R.id.btnView);
        rdGroup=(RadioGroup) findViewById(R.id.rdGroup);
        rdMale=(RadioButton) findViewById(R.id.rdMale);
        rdFemale=(RadioButton) findViewById(R.id.rdFemale);

        //database        db=openOrCreateDatabase("MyData3", Context.MODE_PRIVATE,null);
        db.execSQL("create table if not exists MyTable3(ID integer primary key autoincrement not null,NAME varchar,PHONE varchar,GENDER varchar)");

        btnInsert.setOnClickListener(new View.OnClickListener() {
            @Override            public void onClick(View view) {
                ContentValues cv=new ContentValues();
                cv.put("NAME",edtname.getText().toString().trim());
                cv.put("PHONE",edtNumber.getText().toString().trim());
                cv.put("GENDER",gender.toString().trim());
                Long i=db.insert("MyTable3",null,cv);
                if(i>0){
                    Toast.makeText(MainActivity.this,"Data inserted",Toast.LENGTH_LONG).show();
                    edtname.setText("");
                    edtNumber.setText("");
                    rdGroup.clearCheck();
                }
            }
        });

        btnView.setOnClickListener(new View.OnClickListener() {
            @Override            public void onClick(View view) {
                startActivity(new Intent(MainActivity.this,ListData.class));
            }
        });

        rdGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override            public void onCheckedChanged(RadioGroup radioGroup, int i) {
                if(i==R.id.rdMale){
                    gender="Male";
                }
                else if(i==R.id.rdFemale){
                    gender="Female";
                }
            }
        });





    }
}

Step 3:- listdata.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">
    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <android.support.design.widget.FloatingActionButton
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/fab"
            android:layout_gravity="right|bottom"
            android:src="@android:drawable/ic_input_add"

            android:layout_margin="16dp"/>
        <ListView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:id="@+id/list1"></ListView>
    </FrameLayout>


</LinearLayout>

Step 4: ListItem.java

package androidhubb.sqliteexample;

import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ListView;

import java.util.ArrayList;

/** * Created by Supriya on 8/31/2016. */public class ListData extends AppCompatActivity {
    ListView listView;
    SQLiteDatabase db;
    FloatingActionButton fab;
    @Override    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.listdata);
        listView=(ListView)findViewById(R.id.list1);
        fab=(FloatingActionButton)findViewById(R.id.fab);

        db=openOrCreateDatabase("MyData3", Context.MODE_PRIVATE,null);
        onViewData();

        fab.setOnClickListener(new View.OnClickListener() {
            @Override            public void onClick(View view) {
                startActivity(new Intent(ListData.this,MainActivity.class));
            }
        });
    }
    public void onViewData(){
        ArrayList<String> listname=new ArrayList<String>();
        ArrayList<String> listPhone=new ArrayList<String>();
        ArrayList<String> listgender=new ArrayList<String>();
        listname.clear();
        listPhone.clear();
        listgender.clear();
        Cursor c=db.rawQuery("select * from MyTable3",null);
        while(c.moveToNext()){
            listname.add(c.getString(1));
            listPhone.add(c.getString(2));
            listgender.add(c.getString(3));
        }
        listView.setAdapter(new Adapter(ListData.this,listname,listPhone,listgender));

    }
}
Step:-5 adapter.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="wrap_content"
        android:text="Name"
        android:id="@+id/tvName"
        android:textSize="20sp"/>
    <TextView
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="wrap_content"
        android:text="Name"
        android:id="@+id/tvphone"
        android:textSize="20sp"/>
    <TextView
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="wrap_content"
        android:text="Name"
        android:id="@+id/tvgender"
        android:textSize="20sp"/>
</LinearLayout>
Step6:- AdapterList.java

package androidhubb.sqliteexample;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import java.util.ArrayList;

/** * Created by Supriya on 8/31/2016. */public class Adapter extends BaseAdapter {
    ArrayList<String> n,p,g;
    ListData l;
    LayoutInflater inflater;
    public Adapter(ListData data,ArrayList<String> name,ArrayList<String> phone,ArrayList<String> gender){
        this.l=data;
        this.n=name;
        this.p=phone;
        this.g=gender;
        this.inflater=LayoutInflater.from(data);
    }
    @Override    public int getCount() {
        return n.size();
    }

    @Override    public Object getItem(int i) {
        return null;
    }

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

    @Override    public View getView(int i, View view, ViewGroup viewGroup) {
        view=inflater.inflate(R.layout.adapter,null);
        TextView tvname=(TextView)view.findViewById(R.id.tvName);
        TextView tvnumber=(TextView)view.findViewById(R.id.tvphone);
        TextView tvgender=(TextView)view.findViewById(R.id.tvgender);
        tvname.setText(n.get(i));
        tvnumber.setText(p.get(i));
        tvgender.setText(g.get(i));
        return view;
    }
}
step 7;- For Floating Actionbar we have to add following in build.gradl

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:24.1.1'
    compile 'com.android.support:design:24.1.1'
}

Friday, 26 August 2016

Login and Signup in Android Studio By using SQLite Database

1. main_activity.xml:-
<?xml version="1.0" encoding="utf-8"?>
<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"
    tools:context="androidhubb.myproject.MainActivity"
    android:orientation="vertical"
    android:gravity="center">

    <ImageView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:src="@mipmap/logo1"
        android:id="@+id/imgLogo"/>
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Copywrite@androidhubb\nVersion 1.1.0"
        android:gravity="center"/>
</LinearLayout>

2. MainActivity.java
package androidhubb.myproject;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;

public class MainActivity extends AppCompatActivity {
    Animation animation;
    ImageView imgLogo;
    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //Imageview...        imgLogo=(ImageView)findViewById(R.id.imgLogo);
        //animation on image..        animation= AnimationUtils.loadAnimation(getApplicationContext(),R.anim.fade);
        imgLogo.startAnimation(animation);
        //spalsh screen....        Thread t=new Thread(){
            public void run(){
                try{
                   sleep(5000);
                    startActivity(new Intent(MainActivity.this,SignUp.class));
                    finish();
                }
                catch (Exception e){}
            }
        };
        t.start();
    }
    protected void onDestroy(){
        super.onDestroy();
    }
}

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


    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            android:layout_margin="16dp">
            <EditText
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="Email Id"
                android:layout_marginTop="16dp"
                android:inputType="textWebEmailAddress"
                android:id="@+id/txt_email"/>
            <EditText
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="Phone No"
                android:layout_marginTop="16dp"
                android:inputType="number"
                android:id="@+id/txt_phone"/>
            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="Gender"
                android:textSize="20sp"
                android:layout_marginTop="16dp"/>
            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal"
                android:layout_marginTop="10dp">
                <RadioGroup
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:id="@+id/rdgroup"
                    android:orientation="horizontal">
                    <RadioButton
                        android:layout_width="0dp"
                        android:layout_weight="1"
                        android:layout_height="wrap_content"
                        android:text="Male"
                        android:id="@+id/radio_male"/>
                    <RadioButton
                        android:layout_width="0dp"
                        android:layout_weight="1"
                        android:layout_height="wrap_content"
                        android:text="FeMale"
                        android:id="@+id/radio_female"/>
                </RadioGroup>
            </LinearLayout>
            <EditText
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="Birthday(dd/mm//yyyy)"
                android:layout_marginTop="16dp"
                android:id="@+id/edtdate"/>
            <EditText
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="password"
                android:layout_marginTop="16dp"
                android:id="@+id/edtpassword"/>
            <Button
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="Signup"
                android:layout_marginTop="20dp"
                android:id="@+id/btnSignup"
                android:background="@drawable/round_button"
                android:textColor="#ffffff"
                android:textSize="20sp" />
            <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Login"
            android:textSize="25sp"
            android:textAlignment="center"
            android:layout_marginTop="16dp"
            android:textColor="#f05f5f"
            android:id="@+id/txtLogin"/>
            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="View User Details"
                android:textSize="20sp"
                android:textAlignment="center"
                android:layout_marginTop="16dp"
                android:textColor="#000000"
                android:id="@+id/txtview"/>
        </LinearLayout>
    </ScrollView>
</LinearLayout>


4. SignUp.java

package androidhubb.myproject;

import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.icu.util.Calendar;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.DialogFragment;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

/** * Created by Supriya on 8/19/2016. */public class SignUp extends AppCompatActivity {

    EditText edtEmail,edtPhone,edtDate,edtpass;
    RadioButton rMale,rFemale;
    RadioGroup rdGroup;
    TextView tLogin,tvview;
    SQLiteDatabase db;
    Button btnSignup;
    String gender="";

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

        //database        db=openOrCreateDatabase("MyDatabase1", Context.MODE_PRIVATE,null);
        db.execSQL("create table if not exists MyTable1(ID integer primary key autoincrement not null,EMAIL varchar,PHONE varchar,GENDER varchar,BIRTH varchar,PASSWORD varchar)");

        //find id..        btnSignup=(Button)findViewById(R.id.btnSignup);
        edtEmail=(EditText)findViewById(R.id.txt_email);
        edtPhone=(EditText)findViewById(R.id.txt_phone);
        edtDate=(EditText)findViewById(R.id.edtdate);
        edtpass=(EditText)findViewById(R.id.edtpassword);

        rdGroup=(RadioGroup)findViewById(R.id.rdgroup);
        rMale=(RadioButton)findViewById(R.id.radio_male);
        rFemale=(RadioButton)findViewById(R.id.radio_female);
        tLogin=(TextView)findViewById(R.id.txtLogin);
        tvview=(TextView)findViewById(R.id.txtview);

        //signup        btnSignup.setOnClickListener(new View.OnClickListener() {
            @Override            public void onClick(View view) {
                ContentValues cv=new ContentValues();
                cv.put("EMAIL",edtEmail.getText().toString().trim());
                cv.put("PHONE",edtPhone.getText().toString().trim());
                cv.put("GENDER",gender.toString().trim());
                cv.put("BIRTH",edtDate.getText().toString().trim());
                cv.put("PASSWORD",edtpass.getText().toString().trim());
                Long i=db.insert("MyTable1",null,cv);
                if(i>0){
                    Toast.makeText(SignUp.this,"Data Inserted",Toast.LENGTH_LONG).show();
                    edtDate.setText("");
                    edtEmail.setText("");
                    edtPhone.setText("");
                    edtpass.setText("");
                    rdGroup.clearCheck();
                }
            }
        });

   rdGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
       @Override       public void onCheckedChanged(RadioGroup radioGroup, int i) {
           if(i==R.id.radio_male){
               gender="Male";
           }
           else {
               gender="Female";
           }
       }
   });

        //login nevigation....        
tLogin.setOnClickListener(new View.OnClickListener() {
            @Override            
public void onClick(View view) {
                startActivity(new Intent(SignUp.this,Login.class));
            }
        });
        //view nevigation....        
tvview.setOnClickListener(new View.OnClickListener() {
            @Override            
public void onClick(View view) {
                startActivity(new Intent(SignUp.this,UserList.class));
            }
        });
        //listner...        edtDate.setOnClickListener(new View.OnClickListener() {
            @Override            public void onClick(View view) {

                DialogFragment dFragment=new DatePickerDialogClass();
                dFragment.show(getSupportFragmentManager(),"Select date");
            }
        });

    }

    public static class DatePickerDialogClass extends DialogFragment implements DatePickerDialog.OnDateSetListener{
        @NonNull        @Override        public Dialog onCreateDialog(Bundle savedInstanceState) {
            final Calendar c=Calendar.getInstance();
           final int year=c.get(Calendar.YEAR);
            int month=c.get(Calendar.MONTH);
            int date=c.get(Calendar.DAY_OF_MONTH);

            DatePickerDialog datePickerDialog=new DatePickerDialog(getActivity(), android.app.AlertDialog.THEME_DEVICE_DEFAULT_DARK,this,year,month,date);

            return datePickerDialog;
        }

        @Override        
public void onDateSet(DatePicker datePicker, int i, int i1, int i2) {
        EditText edate=(EditText)getActivity().findViewById(R.id.edtdate);
            edate.setText(i2+"/"+(i1+1)+"/"+i);

        }
    }

}
5.userlist.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">
    <ListView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/list1"></ListView>

</LinearLayout>

6. UserList.java
package androidhubb.myproject;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.widget.ListView;

import java.util.ArrayList;

/** * Created by Supriya on 8/31/2016. */public class UserList extends AppCompatActivity {
    ListView listView;
    SQLiteDatabase db;
    @Override    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.user_list);
        listView=(ListView)findViewById(R.id.list1);
        db=openOrCreateDatabase("MyDatabase1", Context.MODE_PRIVATE,null);
        onUserListView();
    }
    public void onUserListView(){
        ArrayList<String> email_list=new ArrayList<String>();
        ArrayList<String> phone_list=new ArrayList<String>();
        ArrayList<String> gender_list=new ArrayList<String>();
        ArrayList<String> birth_list=new ArrayList<String>();
        ArrayList<String> pass_list=new ArrayList<String>();
        email_list.clear();
        phone_list.clear();
        gender_list.clear();
        birth_list.clear();
        pass_list.clear();
        Cursor c=db.rawQuery("select * from MyTable1",null);
        while (c.moveToNext()){
            email_list.add(c.getString(1));
            phone_list.add(c.getString(2));
            gender_list.add(c.getString(3));
            birth_list.add(c.getString(4));
            pass_list.add(c.getString(5));
        }
        listView.setAdapter(new Adapter(UserList.this,email_list,phone_list,gender_list,birth_list,pass_list));

    }
}

7. adapter.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="email"
        android:textSize="25sp"
        android:id="@+id/tvEmail"/>
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="email"
        android:textSize="25sp"
        android:id="@+id/tvPhone"/>
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="email"
        android:textSize="25sp"
        android:id="@+id/tvGender"/>
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Birth"
        android:textSize="25sp"
        android:id="@+id/Birth"/>
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Password"
        android:textSize="25sp"
        android:id="@+id/tvPass"/>

</LinearLayout>
8.login.xml

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

            <EditText
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="Email Id"
                android:layout_marginTop="16dp"
                android:inputType="textWebEmailAddress"
                android:id="@+id/txt_email"/>
            <EditText
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="Password"
                android:layout_marginTop="16dp"
                android:inputType="textPassword"
                android:id="@+id/txt_pass"/>

            <Button
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="Login"
                android:layout_marginTop="20dp"
                android:id="@+id/btnlogin"
                android:background="@drawable/round_button"
                android:textColor="#ffffff"
                android:textSize="20sp"/>
            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="SignUp"
                android:textSize="25sp"
                android:textAlignment="center"
                android:layout_marginTop="16dp"
                android:textColor="#f05f5f"
                android:id="@+id/txtsignup"/>

</LinearLayout>
Step 8:Login.java
package androidhubb.myproject;

import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

/** * Created by Supriya on 8/19/2016. */public class Login extends AppCompatActivity {
    TextView tvSign;
    EditText edtEmail,edtpass;
    Button btnLogin;
    SQLiteDatabase db;

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

        edtEmail=(EditText)findViewById(R.id.txt_email);
        edtpass=(EditText)findViewById(R.id.txt_pass);
        btnLogin=(Button)findViewById(R.id.btnlogin);
        tvSign=(TextView)findViewById(R.id.txtsignup);

        db=openOrCreateDatabase("MyDatabase1", Context.MODE_PRIVATE,null);

        btnLogin.setOnClickListener(new View.OnClickListener() {
            @Override            public void onClick(View view) {

                String email=edtEmail.getText().toString().trim();
                String pass=edtpass.getText().toString().trim();
                Cursor c=db.rawQuery("select * from MyTable1 where EMAIL=? AND PASSWORD=?",new String[]{email,pass});
                if(c.moveToFirst()){
                    Toast.makeText(Login.this,"Success",Toast.LENGTH_LONG).show();
                    startActivity(new Intent(Login.this,WelcomeClass.class));
                    edtpass.setText("");
                    edtEmail.setText("");
                }
                else{
                    Toast.makeText(Login.this,"invalid details",Toast.LENGTH_LONG).show();
                }

            }
        });

        //login nevigation....        tvSign.setOnClickListener(new View.OnClickListener() {
            @Override            public void onClick(View view) {
                startActivity(new Intent(Login.this,SignUp.class));
            }
        });
    }
}

Wednesday, 24 August 2016

Started Service Example in Android Studio 2.1.2

Code Verified on-
Android Studio 2.1.2

Step1:
Take a new Project and open activity_main.xml file. Coding will be like following.

<?xml version="1.0" encoding="utf-8"?>
<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"
    tools:context="androidhubb.setvices.MainActivity"
    android:layout_margin="16dp"
    android:gravity="center_vertical">

   <Button
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:text="Start Services"
       android:onClick="onStart"/>

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Stop Services"
        android:onClick="onStop"/>
</LinearLayout>

Step 2:- To start a Bound Service we have to take another java MyService.java

package androidhubb.startedservice;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.widget.Toast;

/** * Created by Supriya on 8/24/2016. */public class MyService extends Service{

    @Override    
public void onCreate() {
        super.onCreate();
    }

    @Override   
 public int onStartCommand(Intent intent, int flags, int startId) {

        Toast.makeText(getApplicationContext(),"Service started",Toast.LENGTH_LONG).show();
        return START_STICKY;
    }

    @Override    
public void onDestroy() {
        super.onDestroy();
        Toast.makeText(getApplicationContext(),"Service stoped",Toast.LENGTH_LONG).show();
    }

    @Nullable    @Override   
 public IBinder onBind(Intent intent) {
        return null;
    }
}

3. MainActivity.java

package androidhubb.startedservice;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;

public class MainActivity extends AppCompatActivity {

    @Override    
protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
    public void onStart(View v){
        startService(new Intent(getApplicationContext(),MyService.class));
    }

    public void onStop(View v){
        stopService(new Intent(getApplicationContext(),MyService.class));
    }
}

Bound Service Example in Android Studio 2.1.2

Code Verified on-
Android Studio 2.1.2

Step1: main_activity.xml
Take a new Project and open activity_main.xml file. Coding will be like following.

<?xml version="1.0" encoding="utf-8"?>
<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"
    tools:context="androidhubb.setvices.MainActivity"
    android:layout_margin="16dp"
    android:gravity="center_vertical">

   <Button
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:text="Start Services"
       android:onClick="onStart"/>

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Stop Services"
        android:onClick="onStop"/>
</LinearLayout>

Step 2:- To start a Bound Service we have to take another java file MyService.java | code will be like..
package androidhubb.boundservice;

import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.support.annotation.Nullable;

/** * Created by Supriya on 8/24/2016. */
public class MyService extends Service {
    MediaPlayer mp;
    @Nullable    @Override   
 public IBinder onBind(Intent intent) {
        return null;
    }

    @Override    
public void onCreate() {
        super.onCreate();
        mp=MediaPlayer.create(this,R.raw.sanam);
        mp.setLooping(true);
    }

    @Override    
public void onStart(Intent intent, int startId) {
        super.onStart(intent, startId);
        mp.start();
    }

    @Override   
 public void onDestroy() {
        super.onDestroy();
        mp.stop();
    }
}

3. MainAvtivity.java

package androidhubb.boundservice;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;

public class MainActivity extends AppCompatActivity {

    @Override    
protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
    public void onStart(View v){
        startService(new Intent(getApplicationContext(),MyService.class));
    }
    public void onStop(View v){
        stopService(new Intent(getApplicationContext(),MyService.class));
    }
}


Thursday, 4 August 2016

SOAP | XMl Parsing Example

Step1:- Open your Android Studio.
Step2:-Click on File >New >New Project> SOAPExample
Step3:-Click on res>activity_main.xml and take 1TextView and 1 Spinner
Step 4:- activity_main.xml code will be like following.

<?xml version="1.0" encoding="utf-8"?>
<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"
    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="supriya.soap2.MainActivity">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Select Country"
        android:id="@+id/textView" />

    <Spinner
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/spinner"
        android:layout_below="@+id/textView"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_marginTop="58dp" />
</RelativeLayout>

Step 5:- Click to Download ksoap2 dependencies library  After downloading extract the file and copy that library file and paste that in libs folder. app >libs >after paste right click on that ksoap2 file and select > set as library > ok
Step 6:- MainActivity.java code will be like following.

package supriya.soap2;

import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;

import java.util.ArrayList;

public class    MainActivity extends AppCompatActivity {
    Spinner spnCountry;
    ProgressDialog pd;

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

        //process dialoge coding...        
pd=new ProgressDialog(MainActivity.this);
        pd.setMessage("Loading..");

        //id of Spinner..        
spnCountry=(Spinner)findViewById(R.id.spinner);

        //array list...        
ArrayList<String> list=new ArrayList<String>();
        list.clear();
        list.add("--Select--");
        list.add("India");
        list.add("US");


        //array adapter...        
ArrayAdapter<String> adp=new ArrayAdapter<String>(getApplicationContext(),R.layout.spinback,list);
        spnCountry.setAdapter(adp);

        //spinner listner,.....        
spnCountry.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override            
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                MyTask t=new MyTask(spnCountry.getSelectedItem().toString());
                t.execute();

            }

            @Override            
public void onNothingSelected(AdapterView<?> parent) {

            }
        });
    }//closing of onCreate method......
    class MyTask extends AsyncTask<String,String,String>{
        //variables....        
String setCountryName="";
        String getCitiesName="";

        //constructor.....        
public  MyTask(String cName){
            this.setCountryName=cName;

        }
        @Override        
protected void onPreExecute() {
            super.onPreExecute();
            pd.show();
        }

        @Override        
protected String doInBackground(String... params) {
            AddEvent ae=new AddEvent();
            getCitiesName=ae.getResultOfCitiesName(setCountryName);
            return null;
        }

        @Override        
protected void onPostExecute(String s) {
            super.onPostExecute(s);
            tostOutput(getCitiesName);
            pd.dismiss();
        }

        @Override        
protected void onProgressUpdate(String... values) {
            super.onProgressUpdate(values);
        }
    }
//close MyTask class
    public void tostOutput(String result){
        Toast.makeText(getApplicationContext(),result,Toast.LENGTH_LONG).show();
    }
}
Step 6:- AddEvent.java code will be like following.

public class AddEvent {
    String NAMESPACE = "http://www.webserviceX.NET";
    String URL="http://www.webservicex.net/globalweather.asmx?wsdl";


    public String getResultOfCitiesName(String getAllCitiesName)
    {
        String SOAP_ACTION1 = "http://www.webserviceX.NET/GetCitiesByCountry";
        String METHOD_NAME1 = "GetCitiesByCountry";
        String result_="";
        SoapObject request = new SoapObject(NAMESPACE,METHOD_NAME1);

        request.addProperty("CountryName",getAllCitiesName);

        SoapSerializationEnvelope envelope =new SoapSerializationEnvelope(SoapEnvelope.VER11);
        envelope.setOutputSoapObject(request);
        envelope.dotNet = true;
        try        {
            HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
            //this is the actual part that will call the webservice         
androidHttpTransport.call(SOAP_ACTION1, envelope);

            // Get the SoapResult from the envelope body.            
SoapObject result = (SoapObject)envelope.bodyIn;
            if(result != null)
            {
                result_=result.getProperty(0).toString().trim();
            }
            else            {
                result_="no data found";
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result_;
    }
}

Step 6:-To give customlook to spineer add a xml file in layout folder  app > res > layout > right click on layout > new > layout resource file > spinback.xml
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@android:id/text1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:textAppearance="?android:attr/textAppearanceListItemSmall"
    android:gravity="center_vertical"
    android:textColor="#000000"
    android:minHeight="?android:attr/listPreferredItemHeightSmall" />