Sunday, March 12, 2017

SQLite Example - Register New User and View All Registered User

Dear All

" Happy Holi......"

What is SQLite :

SQLite is an in-process Library used to work with Database for Mobile OS(Mostly).
@ It's Server-Less
@ Already Configured
@ Follow ACID Property
@ Structured Database
@ No Dependency

How to work with Database in Android  :
Step 1 : Define Schema
             " Means Define Database name , table name , column name ..........."
Step 2: Create Database
             a.  Create a Class by extending SQLiteOpenHelper
             b.  Override  onCreate(SQLiteDatabase ob) method -
                   Like ob.execSQL(" String query")
             c. Override onUpgrade(SQLiteDatabase db, int oldVersion, int                                                 newVersion)
          if any alter in Table 
Step 3: Execute Query 
       a. Create object of SQLiteDatabase   either by                                  using getWritableDatabase() or 
          getReadableDatabase()  with the help of Helper class                         object 
       b. Use ContentValues  class object to put like key-value pair                   data
       c. Execute query like insert() , update().... by                               using SQLiteDatabase object

Just See the example :
A. Output will be like
     a. First Screen - Launched Activity

    XML Code for this
<?xml version="1.0" encoding="utf-8"?>

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

    xmlns:app="http://schemas.android.com/apk/res-auto"

    xmlns:tools="http://schemas.android.com/tools"

    android:layout_width="match_parent"

    android:layout_height="match_parent"

    tools:context="com.example.ravigodara.sql2017ex1.MainActivity"

    tools:layout_editor_absoluteY="81dp"

    tools:layout_editor_absoluteX="0dp">

    <Button        android:id="@+id/button"

        android:layout_width="368dp"

        android:layout_height="48dp"

        android:layout_alignEnd="@+id/button2"

        android:layout_alignParentTop="true"

        android:layout_marginTop="62dp"

        android:text="Register"

        tools:layout_editor_absoluteX="8dp"

        tools:layout_editor_absoluteY="45dp"

        android:onClick="reg"/>

    <Button        android:id="@+id/button2"

        android:layout_width="368dp"        android:layout_height="48dp"

        android:text="Registered User"

        tools:layout_editor_absoluteX="8dp"   tools:layout_editor_absoluteY="151dp"

        android:layout_alignParentBottom="true"

        android:layout_centerHorizontal="true"

        android:layout_marginBottom="109dp"

        android:onClick="showData"/>
</RelativeLayout> 
 b.  Second Screen - When you click on Register


XML Code for this layout
<?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">
    <TextView        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:textAppearance="?android:attr/textAppearanceLarge"

        android:text="UserName"        android:id="@+id/textView"

        android:layout_alignParentTop="true"

        android:layout_alignParentStart="true" />

    <TextView

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:textAppearance="?android:attr/textAppearanceLarge"

        android:text="Password"        android:id="@+id/textView2"

        android:layout_below="@+id/textView"

        android:layout_alignEnd="@+id/textView"

        android:layout_marginTop="44dp" />

    <EditText        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

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

        android:layout_alignParentEnd="true"

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

    <EditText

        android:layout_width="wrap_content"

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

        android:inputType="textPassword"

        android:layout_alignBottom="@+id/textView2"

        android:layout_alignParentEnd="true"

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

    <Button        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:text="Register"

        android:id="@+id/button"

        android:layout_centerVertical="true"

        android:layout_centerHorizontal="true" />
</RelativeLayout> 
  c. Third Screen - All registered User


XML Code for this layout
<?xml version="1.0" encoding="utf-8"?>

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

    xmlns:app="http://schemas.android.com/apk/res-auto"

    xmlns:tools="http://schemas.android.com/tools"

    android:layout_width="match_parent"

    android:layout_height="match_parent"

    tools:context="com.example.ravigodara.sql2017ex1.ViewData">

    <ListView

        android:layout_width="wrap_content"   android:layout_height="wrap_content"

        android:id="@+id/listView"

        android:layout_alignParentStart="true"

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

Single Row Layout File 

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

    android:weightSum="1">

    <TextView

        android:layout_width="wrap_content"    android:layout_height="39dp"

        android:text="New Text"        android:gravity="center"

        android:id="@+id/text_id"        android:layout_weight="0.06" />

    <TextView        android:layout_width="wrap_content"

        android:layout_height="41dp"

        android:text="New Text"        android:gravity="center"

        android:id="@+id/text_name"        android:layout_weight="0.90" />
    <TextView        android:layout_width="159dp"

        android:layout_height="37dp"

        android:text="New Text"        android:gravity="center"

        android:id="@+id/text_pass" />
</LinearLayout>

B. Java Code

a. MainActivity.java   code is

package com.example.ravigodara.sql2017ex1;

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 reg(View view)
    {
        startActivity(new Intent(this, Register.class));
    }
    public void showData(View view)
    {
        Intent iob = new Intent(this,ViewData.class);
        startActivity(iob);
    }
}

b. Register.java code is as

package com.example.ravigodara.sql2017ex1;

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

/** * Created by Ravi Godara on 3/10/2017. */
public class Register extends AppCompatActivity {

    EditText etus, etpass;
    String struser, strpass;
    Button reg;
    Context cob = this;

    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.regist);
        etus = (EditText) findViewById(R.id.userN);
        etpass = (EditText) findViewById(R.id.userP);

        reg = (Button) findViewById(R.id.button);
        reg.setOnClickListener(new View.OnClickListener() {
            @Override            public void onClick(View v) {
                struser = etus.getText().toString();
                strpass = etpass.getText().toString();


                DbHelper myob = new DbHelper(cob);
                    myob.putInfo(myob, struser, strpass);
                    Toast.makeText(getBaseContext(), 
                          "Registered Successfully", Toast.LENGTH_LONG).show();
                    finish();

            }
        });
    }
}

c. To See all Registered User is as

package com.example.ravigodara.sql2017ex1;

import android.content.Context;
import android.database.Cursor;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;

public class ViewData extends AppCompatActivity {
    Context context = this;

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

    private void showListView() {
        DbHelper myHelper = new DbHelper(context);
        Cursor cursorOb = myHelper.getAllRows(myHelper);
        String[] fromDB = new String[]{DbHelper.KEY_ID, DbHelper.USER_NAME, 
                           DbHelper.USER_PAS};
        int[] toShow = new int[]{R.id.text_id, R.id.text_name, R.id.text_pass};
        SimpleCursorAdapter simpleCursorAdapter = new SimpleCursorAdapter
                 (getBaseContext(), R.layout.onerow, cursorOb, fromDB, toShow, 0);
        ListView listView = (ListView) findViewById(R.id.listView);
        listView.setAdapter(simpleCursorAdapter);
    }
}

d. DataBase Helper class is as
package com.example.ravigodara.sql2017ex1;

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;

public class DbHelper extends SQLiteOpenHelper {
    public static final String KEY_ID="_id";
    public static final String USER_NAME="user_name";
    public static final String USER_PAS="user_pass";
    private static final String DB_NAME="mydb.db";
    private static final String TAB_NAME="myinfo";
    private static final int DB_VER=1;
    private static final  String CREATE_QUERY = "create table " + TAB_NAME + " ( "
                    + KEY_ID + " integer primary key autoincrement, " +
            USER_NAME + " text not null, " + USER_PAS + " text not null );";

    public DbHelper(Context context)
    {
        super(context,DB_NAME,null,1);
    }
    @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("hello", "onupgrade");
        onCreate(db);

    }
    public  void putInfo(DbHelper mob,String name,String pass)
    {
        SQLiteDatabase SQ= mob.getWritableDatabase();
        ContentValues CV=new ContentValues();
        CV.put(USER_NAME, name);
        CV.put(USER_PAS, pass);
        SQ.insert(TAB_NAME, null, CV);
    }

    public Cursor getAllRows(DbHelper mob)
    {
        SQLiteDatabase SQ = mob.getReadableDatabase();
        Cursor cob = SQ.query(TAB_NAME,null,null,null,null,null,null);
        if(cob!=null)
        {
            cob.moveToFirst();
        }
        return cob;
    }
}
 



Sunday, February 26, 2017

Event Handling in Android @ Button

Dear All

Event - Its an Action happened in App.

Event Handling means how we deal with Action Happened like Button Click is an Event.

Event can be Managed by following three important steps.
1. Adding Event Listener - It's an Interface
2. Event Listener Registration with widget - Its a procedure like setOnClickListener()
3. Event Handler - It's response method like onClick(View view)

Just See below example with all these three steps.

package com.example.ravigodara.buttonevent;
import android.support.v7.app.AppCompatActivity;

import android.os.Bundle;

import android.view.View;

import android.widget.Button;

import android.widget.TextView;

import android.widget.Toast;
public class MainActivity extends AppCompatActivity 
                               implements View.OnClickListener 
                                          // Adding Event Listener
{
   Button btn1 , btn2;
    TextView txt;
    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        txt = (TextView) findViewById(R.id.text);
        btn1 = (Button) findViewById(R.id.butsum);
        btn2 = (Button) findViewById(R.id.butmul);
        btn1.setOnClickListener(this);    
                     // Listener Registration with Event Widget
        btn2.setOnClickListener(this);

    }
    @Override    public void onClick(View v) { 
                     // Event Handler Method which will be called  

        int id = v.getId();
        switch (id)
        {
            case R.id.butsum:
                Toast.makeText(this, "Button 1 Pressed", Toast.LENGTH_SHORT).show();
                txt.setText("Button 1 Pressed");
                break;
            case R.id.butmul:
                Toast.makeText(this, "Button 2 Pressed", Toast.LENGTH_SHORT).show();
                txt.setText("Button 2 Pressed");
                break;

        }

    }


}

B. Layout File

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:id="@+id/activity_main"

    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.example.ravigodara.buttonevent.MainActivity">

    <TextView

        android:id="@+id/text"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:text="Hello World!"

        android:layout_alignParentEnd="true"

        android:layout_alignParentStart="true" />

    <Button

        android:text="Sum"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:layout_below="@+id/textView"

        android:layout_toEndOf="@+id/textView"

        android:layout_marginStart="43dp"

        android:layout_marginTop="111dp"

        android:id="@+id/butsum" />

    <Button        android:text="Mul"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:layout_centerVertical="true"

        android:layout_alignEnd="@+id/button"

        android:id="@+id/butmul" />
</RelativeLayout>

C. Output will be like 

1. 


2.


3. 





Friday, December 9, 2016

Star Pattern-II - Placement Practice Questions @ C/C++

Special Thanks to - Rishubh Pratap Singh

A. Output 


B. Code in C 


#include <stdio.h>

int main()
{
int i,j,n;
printf("Enter the number of rows");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
for(j=n;j>=i;j--)
{
            printf(" * ");
        }
printf("\n");
}
return 10;

}

Star Pattern-I - Placement Practice Questions @ C/C++

Special Thanks to - Rishubh Pratap Singh

A. Output 



B. Code in C 

#include <stdio.h>

int  main()
{
int i,j,n;
printf("Enter the number of rows");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
for(j=1;j<=i;j++)
{
  printf(" * ");
}
printf("\n");
}
return 0;
}

Monday, December 5, 2016

Objective Questions in >= Swift2.2 @iPhone - Set J

Q.91: Which function is used to store URL preferences
A. func setFloat(Float Value ,  "KeyName")
B. func setDouble(Double Value ,  "KeyName")
C.  func setObject(value: AnyObject?,  "KeyName")
D.  func setURL(url: NSURL?, "KeyName")

Q.92: In func setBool(Bool Value , "KeyName") what will            be the keyname
  A. Integer Type
  B. Character type
  C. String Type
  D. Boolean type

Q.93: In func setObject(value:AnyObject?, "KeyName")               what will be the keyname
  A. Integer Type
  B. Character type
  C. Object type
  D. String Type

Q.94: What is the use of UIWebView class in iPhone
  A. To embed web content
  B. To render web content
  C. To load HTML pages
  D. All the above

Q.95: Which function is used load HTML content in    
        webview
  A. func loadHTMLString(_ string: String, baseURL:   
                                                         URL?)
  B. func loadHTMLString(baseURL: URL?)
  C. func loadHTMLString(_ string: String)
  D. None

Q.96: In the below function what can be   
         textEncodingName
func load(_ data: Data,  mimeType MIMEType: String, textEncodingName: String, baseURL: URL)

A.   utf-8
B.   utf-16
C.  A & B
D.  none

Q.97: In CGPointMake( value1 , value2) the type of value1 
          and value 2 is
  A. Float , Int
  B. Float , Float
  C. Int , Int
  D. Int , Float

Q.98: Which method is called when the view is actually 
         visible, and can be called multiple times during the 
         lifecycle of a View Controller.
  A. viewDidAppear()
  B. viewDidLoad()
  C. viewDidLayoutSubviews()
  D. None

Q.99: Which method is called once all of your subviews have 
           been laid out.
  A. viewDidAppear()
  B. viewDidLoad()
  C. viewDidLayoutSubviews()
  D. None

Q.100: Which class Is used to create session in swift
  A. NSURL
  B. NSURLSession
  C. NSURLRequest
  D. None


Answers:  D     C     D       D     A      C      B      A       C       B