Thursday, April 28, 2016

Registration & Login Simple One

" Jai Saraswati Maa" 
Hi ... Dear All ..Today I am uploading a superb example of Creating Registration Form with FirstName LastName and Password field. 
FirstName i am taken as userName for login Purpose.Please check.
I am using Android Studio 1.5.1
Minimun SDK API 19
Target SDK API 23
Please Like us & put your valuable suggestions in comment box.

A. Output Will be like 
a.        


b.       
            


B. XML files

a.  activity_main.xml   is as 

<?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="com.exam.ravi.customlistwithbutton.MainActivity">

    <EditText        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:id="@+id/logUser"

        android:layout_alignParentTop="true"

        android:layout_alignParentStart="true"

        android:layout_marginTop="54dp"        android:hint="UserName"

        android:layout_alignParentEnd="true" />

    <EditText        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:id="@+id/logPass"

        android:layout_below="@+id/logUser"

        android:layout_alignParentStart="true"

        android:layout_marginTop="40dp"

        android:hint="Password"        android:inputType="textPassword"

        android:layout_alignEnd="@+id/logUser" />

    <Button        android:layout_width="wrap_content"

        android:layout_height="wrap_content"        android:text="Login"

        android:id="@+id/logBut"

        android:onClick="loginUser"

        android:layout_centerVertical="true"

        android:layout_alignParentStart="true" />

    <Button        android:layout_width="wrap_content"

        android:layout_height="wrap_content"        android:text="New User"

        android:id="@+id/newuserBut"

        android:onClick="registerUser"

        android:layout_centerVertical="true"

        android:layout_alignParentEnd="true" />
</RelativeLayout>

b.  reguser.xml is as 

<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

    android:orientation="vertical" android:layout_width="match_parent"

    android:layout_height="match_parent">

    <EditText        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:id="@+id/fName"

        android:layout_alignParentTop="true"

        android:layout_alignParentStart="true"

        android:layout_marginTop="58dp"

        android:hint="First Name"

        android:layout_alignParentEnd="true" />

    <EditText        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:id="@+id/lName"        android:layout_below="@+id/fName"

        android:layout_alignParentStart="true"

        android:layout_marginTop="42dp"

        android:hint="Last Name"

        android:layout_alignParentEnd="true" />

    <EditText        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:inputType="textPassword"

        android:ems="10"

        android:id="@+id/userPass"

        android:layout_centerVertical="true"

        android:hint=" Password "

        android:layout_alignParentStart="true"

        android:layout_alignParentEnd="true" />

    <Button        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:text="Register"

        android:id="@+id/regist"

        android:layout_below="@+id/userPass"

        android:layout_centerHorizontal="true"

        android:layout_marginTop="50dp"

        android:onClick="regMe"/>
</RelativeLayout>

C. Java Files
a.   MainActivity.java ias as

package com.exam.ravi.customlistwithbutton;

import android.content.Intent;
import android.database.Cursor;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
    EditText EdLogUser,EdLogPass;
    String user,pass;
    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        EdLogUser = (EditText) findViewById(R.id.logUser);
        EdLogPass = (EditText) findViewById(R.id.logPass);
    }
    public void loginUser(View view)
    {
        user = EdLogUser.getText().toString();
        pass = EdLogPass.getText().toString();
        MyHelp myHelp = new MyHelp(this);
        Cursor crob = myHelp.getInfo(myHelp);
        crob.moveToFirst();
        boolean logstatus = false;
        String NAME = "";
        do {
         if((user.equals(crob.getString(0))) && (pass.equals(crob.getString(1)))) {
                logstatus = true;
                NAME = crob.getString(0);
            }
        } while (crob.moveToNext());
        if (logstatus) {
            Toast.makeText(getBaseContext(), "Login Success .. . \n Welcome " + NAME, 
                                Toast.LENGTH_LONG).show();
           EdLogUser.setText("");
           EdLogPass.setText("");
        } else {
            Toast.makeText(getBaseContext(), "Login Failed..Please Check your detail",
                                Toast.LENGTH_LONG).show();
            EdLogUser.setText("");
            EdLogPass.setText("");
        }
    }


    public void  registerUser(View view)
      {
        startActivity(new Intent(this,RegUser.class));
      }
}

b. RegUser.java is as 

package com.exam.ravi.customlistwithbutton;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

/** * Created by Ravi on 4/28/2016. */public class RegUser extends AppCompatActivity
{
   EditText EdFname,EdLname,EdPass;
    String sFname,sLname,sPass;
    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.reguser);
        EdFname = (EditText) findViewById(R.id.fName);
        EdLname = (EditText) findViewById(R.id.lName);
        EdPass = (EditText) findViewById(R.id.userPass);
    }
    public void regMe(View view)
    {
        sFname = EdFname.getText().toString();
        sLname = EdLname.getText().toString();
        sPass = EdPass.getText().toString();
        MyHelp myob = new MyHelp(this);
        myob.putInfo(myob, sFname, sLname,sPass);
        Toast.makeText(RegUser.this, "Registered Successfully...."
                                              Toast.LENGTH_SHORT).show();
        finish();

    }
}

c. MyHelp.java is as 
package com.exam.ravi.customlistwithbutton;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

/** * Created by Ravi on 4/28/2016. */public class MyHelp  extends SQLiteOpenHelper {
    public static final String KEY_ID="_id";
    private static final String DB_NAME="cont.db";
    private static final String TAB_NAME="info";
    private static final int DB_VER=1;
    private static final  String CREATE_QUERY = "create table " + TAB_NAME 
            " ( " + KEY_ID + " integer primary key autoincrement, " +
            UserInfo.F_NAME + " text not null, " + UserInfo.L_NAME + " text not null, 
            " + UserInfo.PASS + " text not null);";

    public MyHelp(Context context)
    {
        super(context,DB_NAME,null,DB_VER);
    }
    @Override    public void onCreate(SQLiteDatabase sdb) {

        sdb.execSQL(CREATE_QUERY);
        Log.d("rrrr", "oncreate");
    }

    @Override

    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS " + TAB_NAME);
        Log.d("rrrr", "onupgrade");
        onCreate(db);

    }
    public  void putInfo(MyHelp mob,String fname,String lname,String pass)
    {
        SQLiteDatabase SQ= mob.getWritableDatabase();
        ContentValues CV=new ContentValues();
        CV.put(UserInfo.F_NAME, fname);
        CV.put(UserInfo.L_NAME, lname);
        CV.put(UserInfo.PASS, pass);
        SQ.insert(TAB_NAME, null, CV);
    }
    public Cursor getInfo(MyHelp mob)
    {
        SQLiteDatabase SQ= mob.getWritableDatabase();
        String cols[]={UserInfo.F_NAME,UserInfo.PASS};
        Cursor CR= SQ.query(TAB_NAME,cols,null,null,null,null,null); 
        return  CR;
    }
}

d. UserInfo.java is as

package com.exam.ravi.customlistwithbutton;


public class UserInfo {
    public static final String F_NAME="f_name";
    public static final String L_NAME="l_name";
    public static final String PASS="pass";

}

Friday, April 22, 2016

Mini-App (Upload Text & Image and View Data in a List with SQLite Database (Registration Form Part-III) )

"Jai Saraswati Maa"

Please Read Part-I & Part -II of Registration Form 


Hi ... Dear All ..Today I am uploading a superb example of Uploading data (Text and Image from Gallery) into DataBase using SQLite. And View registered user in a ListView.
*****  This is just like a App which can be added in your project*****
***** Its Mostly required in App Development *****
**** if you are working with latest one API means Marshmallow ****
Don't worry we resolved permission issue.
***** Its little complex .... please have a patience ***** Thanks
Please check.
I am using Android Studio 1.5.1
Minimun SDK API 19
Target SDK API 23
Please Like us & put your valuable suggestions in comment box.
Special Thanks Yatendra Balodia (Student Partner)
Please add permissions in manifest file 
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

A. Outputs will be 
a.     This will happen if your OS is Marshmallow  *** Please ALLOW




b.
    


c. 
    


d.




B. Layout xml files are 
a.  activity_main.xml


<?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"

    tools:context="com.exam.ravi.regform.MainActivity">


    <Button        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:text="Registration "        android:id="@+id/btReg"

        android:onClick="register"

        android:layout_alignParentTop="true"

        android:layout_centerHorizontal="true"

        android:layout_marginTop="71dp" />

    <Button        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:text="View All"        android:id="@+id/btnView"

        android:onClick="viewAll"        android:layout_centerVertical="true"

        android:layout_centerHorizontal="true" />

</RelativeLayout>

b. activity_reg.xml

<?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"

        tools:context="com.exam.ravi.regform.RegAct">

    <EditText        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:id="@+id/et_fname"        android:layout_alignParentTop="true"

        android:layout_marginTop="58dp"        android:layout_alignParentStart="true"

        android:layout_alignParentEnd="true" />

    <EditText        android:layout_width="wrap_content"

        android:layout_height="wrap_content"        android:id="@+id/et_lname"

        android:layout_below="@+id/et_fname"

        android:layout_alignParentStart="true"

        android:layout_marginTop="62dp"

        android:layout_alignEnd="@+id/et_fname" />

    <Button        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:text="OK"        android:id="@+id/btOk"

        android:onClick="submit"

        android:layout_alignParentBottom="true"

        android:layout_centerHorizontal="true"

        android:layout_marginBottom="48dp" />

    <Button        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:text="SelectImage"        android:onClick="selectImage"

        android:id="@+id/btnImg"        android:layout_marginTop="56dp"

        android:layout_below="@+id/et_lname"

        android:layout_alignParentStart="true" />

    <ImageView        android:layout_width="150dp"

        android:layout_height="120dp"

        android:id="@+id/imageView"

        android:src="@mipmap/ic_launcher"

        android:layout_alignTop="@+id/btnImg"

        android:layout_alignEnd="@+id/et_lname"

        android:layout_alignStart="@+id/btOk" />
</RelativeLayout>

c. activity_view.xml
<?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"

       tools:context="com.exam.ravi.regform.ViewAct">

    <ListView        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:id="@+id/listView"

        android:layout_alignParentTop="true"

        android:layout_alignParentStart="true" />
  </RelativeLayout>

d. single_row.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">

    <ImageView

        android:layout_width="150dp"        android:layout_height="120dp"

        android:id="@+id/imageView2"

        android:src="@mipmap/ic_launcher"        android:layout_alignParentTop="true"

        android:layout_alignParentStart="true" />

    <TextView        android:layout_width="match_parent"

        android:layout_height="60dp"        android:text="New Text"

        android:id="@+id/textView1"        android:gravity="center"

        android:textSize="20dp"        android:textStyle="bold"

        android:layout_alignParentTop="true"

        android:layout_toEndOf="@+id/imageView2" />

    <TextView        android:layout_width="wrap_content"

        android:layout_height="60dp"        android:text="New Text"

        android:id="@+id/textView2"

        android:gravity="center"

        android:textSize="15dp"        android:textStyle="italic"

        android:layout_below="@+id/textView1"

        android:layout_alignEnd="@+id/textView1"

        android:layout_toEndOf="@+id/imageView2" />
</RelativeLayout>


C. Java Files are 
a.    MainActivity.java
package com.exam.ravi.regform;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;

public class MainActivity extends AppCompatActivity {
    final int REQUEST_CODE=123;
    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        int hasPermission=
                ContextCompat.checkSelfPermission(MainActivity.this,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE);
        if(hasPermission!= PackageManager.PERMISSION_GRANTED)
        {
         if( !ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE))
            {
                ActivityCompat.requestPermissions(MainActivity.this,
                        new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                        REQUEST_CODE);
                return;
            }
        }
        ActivityCompat.requestPermissions(MainActivity.this,
                new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                REQUEST_CODE);
    }
    public void register(View view)
    {
        startActivity(new Intent(this, RegAct.class));
    }
    public void viewAll(View view)
    {
        startActivity(new Intent(this,ViewAct.class));
    }

}

b .  RegAct.java

package com.exam.ravi.regform;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

public class RegAct extends AppCompatActivity {
    EditText f_name,l_name;
    String fname,lname;
    byte myimg[];
    ImageView imageView;
    Bitmap bitmap = null;
    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_reg);
        f_name = (EditText) findViewById(R.id.et_fname);
        l_name = (EditText) findViewById(R.id.et_lname);
        imageView = (ImageView) findViewById(R.id.imageView);
    }

    public void selectImage(View view) {
        Intent intent = new Intent(Intent.ACTION_PICK,
                    MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(intent, 0);
    }
    @Override

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        if(resultCode== Activity.RESULT_OK && data !=null) {

            Uri selectedImage = data.getData();
            try {
                bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(),
                                                     selectedImage);
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.PNG, 100, bos);
                myimg = bos.toByteArray();
                imageView.setImageBitmap(bitmap);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    public void submit(View view)
    {
        fname = f_name.getText().toString();
        lname = l_name.getText().toString();
        Helper hob = new Helper(this);
        hob.putInfo(hob,fname,lname,myimg);
        finish();
    }
}

c.   TabInfo.java 
package com.exam.ravi.regform;


public class TabInfo {
    public static final String KEY_ID = "_id";
    public static final String FNAME = "fname";
    public static final String LNAME = "lname";
    public static final String DB_NAME = "user_info";
    public static final String TAB_NAME = "info";
    public static final String DP = "img";
}

d. DisplayData .java
package com.exam.ravi.regform;
public class DisplayData {
    String dis_fname;
    String dis_lname;
    byte[] dis_img;
    public DisplayData( ) {}

    public void setDis_fname(String dis_fname) {
        this.dis_fname = dis_fname;
    }

    public void setDis_lname(String dis_lname) {
        this.dis_lname = dis_lname;
    }

    public void setDis_img(byte[] dis_img) {
        this.dis_img = dis_img;
    }
}

e. Helper.java

package com.exam.ravi.regform;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.widget.Toast;
import java.util.ArrayList;

public class Helper extends SQLiteOpenHelper {

    private static final  String CREATE_QUERY = "create table " + TabInfo.TAB_NAME 
                   " ( " + TabInfo.KEY_ID + " integer primary key autoincrement, " +
            TabInfo.FNAME + " text not null, " + TabInfo.LNAME + " text not null , " 
            + TabInfo.DP + " blob );";

   Context ctx;
    public  Helper(Context context)
    {
        super(context,TabInfo.DB_NAME,null,2);
        ctx=context;
    }

    @Override    public void onCreate(SQLiteDatabase db) {
        db.execSQL(CREATE_QUERY);
    }

    @Override

    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS " + TabInfo.TAB_NAME);
        onCreate(db);
    }
    public  void putInfo(Helper mob,String name,String pass,byte [] img)
    {
        SQLiteDatabase SQ= mob.getWritableDatabase();
        ContentValues CV=new ContentValues();
        CV.put(TabInfo.FNAME, name);
        CV.put(TabInfo.LNAME, pass);
        CV.put(TabInfo.DP, img);
        SQ.insert(TabInfo.TAB_NAME, null, CV);
        Toast.makeText(ctx,"1 Row Inserted",Toast.LENGTH_LONG).show();
    }
    public ArrayList<DisplayData> getAllRows(Helper mob)
    {
        ArrayList<DisplayData> data = new ArrayList<DisplayData>();
        SQLiteDatabase SQ = mob.getReadableDatabase();
        String col[] = {TabInfo.FNAME,TabInfo.LNAME,TabInfo.DP};
        Cursor cob = SQ.query(TabInfo.TAB_NAME,col,null,null,null,null,null);
        if(cob!=null)
        {
            cob.moveToFirst();
            do {
                DisplayData displayData = new DisplayData();
                displayData.setDis_fname(cob.getString(0));
                displayData.setDis_lname(cob.getString(1));
                displayData.setDis_img(cob.getBlob(2));
                data.add(displayData);
                }while(cob.moveToNext());
            }
        Toast.makeText(ctx,"Retrieved",Toast.LENGTH_LONG).show();

        return data;
    }
}

f.   ImageAdapter.java 
package com.exam.ravi.regform;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import java.io.ByteArrayInputStream;
import java.util.ArrayList;

public class ImageAdapter extends ArrayAdapter<DisplayData> {
    Context context;
    int layoutResourceId;
    ArrayList<DisplayData> data=new ArrayList<DisplayData>();
    public ImageAdapter(Context context, int layoutResourceId, 
                                          ArrayList<DisplayData> data) 
         {
        super(context, layoutResourceId, data);
        this.layoutResourceId = layoutResourceId;
        this.context = context;
        this.data = data;
    }

    @Override

    public View getView(int position, View convertView, ViewGroup parent) {
        View row = convertView;
        ImageHolder holder = null;
        if(row == null)
        {
            LayoutInflater inflater = ((Activity)context).getLayoutInflater();
            row = inflater.inflate(layoutResourceId, parent, false);
            holder = new ImageHolder();
            holder.txtTitle = (TextView)row.findViewById(R.id.textView1);
            holder.txtDesc = (TextView)row.findViewById(R.id.textView2);
            holder.imgIcon = (ImageView)row.findViewById(R.id.imageView2);
            row.setTag(holder);
        }
        else        {
            holder = (ImageHolder)row.getTag();
        }
        DisplayData picture = data.get(position);
        holder.txtTitle.setText(picture.dis_fname);
        holder.txtDesc.setText(picture.dis_lname);

        byte[] outImage=picture.dis_img;
        ByteArrayInputStream imageStream = new ByteArrayInputStream(outImage);
        Bitmap theImage = BitmapFactory.decodeStream(imageStream);
        holder.imgIcon.setImageBitmap(theImage);
        return row;
    }
    static class ImageHolder
    {
        ImageView imgIcon;
        TextView txtTitle;
        TextView txtDesc;

    }
}

g.  ViewAct.java

 package com.exam.ravi.regform;
import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ListView;

import java.util.ArrayList;
import java.util.List;

public class ViewAct extends AppCompatActivity {
    Context context = this;
    ArrayList<DisplayData> showData;
    ImageAdapter adapter;
    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_view);
        showListView();
    }

    private void showListView() {
        Helper myHelper = new Helper(context);
        showData= myHelper.getAllRows(myHelper);
        adapter= new ImageAdapter(context,R.layout.single_row,showData);
        ListView listView = (ListView) findViewById(R.id.listView);
        listView.setAdapter(adapter);
       }
}