Wednesday, November 18, 2015

ANDROID SELECT QUERY AND BINDING WITH TABLE LAYOUT



REDIRECTING TO ANOTHER ACTIVITY:
    public void viewall(View v)
    {
       try
       {
       showdisplaysmall("Redirecting...");
       Intent in=new Intent(this,ViewActivity.class);
       startActivity(in);
       }
       catch(Exception ex)
       {
              showdisplaylong(ex.getMessage());
       }
    }
BINDING SQLITE DATA TO TABLE LAYOUT:

public class ViewActivity extends Activity {

 TableLayout table_layout;
 EditText rowno_et, colno_et;
 Button build_btn;
 List<String> ids=new ArrayList<String>();
 List<String> fnames=new ArrayList<String>();
 List<String> snames=new ArrayList<String>();

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

  table_layout = (TableLayout) findViewById(R.id.tableLayout1);
  table_layout.removeAllViews();
  FetchData();


 }
private void FetchData()
{
       try
       {
       String id,fname,sname;
       String query="select * from table1";
              Cursor c = MainActivity.db.rawQuery(query,null);
      
          if(c.moveToFirst()){
                 while(c.moveToNext()){
             
                 TableRow row = new TableRow(this);
                   row.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
                     LayoutParams.WRAP_CONTENT));
             
                   for (int j =0; j <= 2; j++) {

                    TextView tv = new TextView(this);
                    tv.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
                      LayoutParams.WRAP_CONTENT));
                    tv.setBackgroundResource(R.drawable.cell_shape);
                    tv.setPadding(5, 5, 5, 5);
                    if(j==0)
                    {
                    tv.setText(c.getString(0));
                    }
                    if(j==1)
                    {
                       tv.setText(c.getString(1));
                    }
                    if(j==2)
                    {
                       tv.setText(c.getString(2));
                    }
                  

                    row.addView(tv);
                    
                    
              }
                   table_layout.addView(row);
                  
                    
                    

           }
      
 
      

          }
          }
       catch(Exception ex)
       {
              showdisplaylong("ERROR.."+ex.getMessage());
       }

}
public void showdisplaylong(String val)
 {
       Toast.makeText(this, val, Toast.LENGTH_LONG).show();
      
      
 }
 public void showdisplaysmall(String val)
 {
       Toast.makeText(this, val, Toast.LENGTH_SHORT).show();
      
      
 }

DYNAMIC TABLE CREATION FUNCTION IN ANDROID:

private void BuildTable(int rows, int cols) {

  // outer for loop
  for (int i = 0; i < ids.size(); i++) {

   TableRow row = new TableRow(this);
   row.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
     LayoutParams.WRAP_CONTENT));

   // inner for loop
   for (int j = 0; j < 3; j++) {

    TextView tv = new TextView(this);
    tv.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
      LayoutParams.WRAP_CONTENT));
    tv.setBackgroundResource(R.drawable.cell_shape);
    tv.setPadding(5, 5, 5, 5);
    tv.setText("R " + i + ", C" + j);

    row.addView(tv);

   }
  

   table_layout.addView(row);

  }
 }

DRAWABLE RESOURCE FOR CELL SHAPE:
Cell_shape.xml

<?xml version="1.0" encoding="utf-8"?>
<shape
  xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape= "rectangle"  >
        <solid android:color="#fff"/>
        <stroke android:width="1dp"  android:color="#000"/>
</shape>

Activity_view.xml (FOR TABLE LAYOUT SETUP)

<?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="wrap_content"
        android:gravity="center_horizontal"
        android:orientation="horizontal"
        android:padding="5dp" >
    </LinearLayout>

    <TableLayout
        android:id="@+id/tableLayout1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:padding="10dp"
        android:shrinkColumns="*"
        android:stretchColumns="*" >
    </TableLayout>

</LinearLayout>

OUTPUT:





ANDROID SQLITE- (CRUD OPERATIONS)

ANDROID SQLITE DATABASE:
        try
        {
      
        db = openOrCreateDatabase("repository",MODE_PRIVATE,null);
        db.execSQL("CREATE TABLE IF NOT EXISTS table1(id int,fname VARCHAR(50),lname VARCHAR(50));");
        Toast.makeText(this,"DATABASE INITIALISED", Toast.LENGTH_LONG).show();
        }
        catch(Exception ex)
        {
        Toast.makeText(this,"ERROR.."+ex.getMessage(), Toast.LENGTH_LONG).show();
        }
GETING MAX VALUE (AGGREGATE FUNCTION IN ANDROID:
    public void Maxval()
    {
       String maxval="";
       try
       {
       String query="select max(id) as maxid from table1";
       Cursor c = db.rawQuery(query,null);
        if (c.moveToFirst()) {
           // temp_address = c.getString(c.getColumnIndex("lastchapter"));
               maxval=c.getString(0);
               maxid=Integer.parseInt(maxval)+1;
               
        }
        showdisplaysmall(maxval);
        c.close();
       }
       catch(Exception ex)
       {
              showdisplaylong(ex.getMessage());
       }
      
    }
INSERT SQLITE QUERY IN ANDROID
  public void insert(View v)
    {
       Maxval();
       EditText fname=(EditText)findViewById(R.id.fname);
       EditText lname=(EditText)findViewById(R.id.lname);
      
       db.execSQL("insert into table1 values("+maxid+",'"+fname.getText().toString()+"','"+lname.getText().toString()+"')");
       Toast.makeText(this, "INSERTED...", Toast.LENGTH_LONG).show();
      
    }
UPDATE AND DELETE QUERY IN SQLITE:
    public void update(View v)
    {
    
       String query="update table1 set fname= '"+fname+"',lname='"+lname+"' where id=";
       AlertDisplay(query,"ENTER ID TO UPDATE","..Updated");
    }
  public void delete(View v)
    {
       String query="delete from table1 where id=";
       AlertDisplay(query,"ENTER ID TO DELETE","..DELETED");
      
    }
ALERT DISPLAY METHOD:
public void AlertDisplay(final String query,String title,final String passMessage)
    {
       AlertDialog.Builder builder = new AlertDialog.Builder(this);
       builder.setTitle(title);

       // Set up the input
       final EditText input = new EditText(this);
       // Specify the type of input expected; this, for example, sets the input as a password, and will mask the text
       input.setInputType(InputType.TYPE_CLASS_NUMBER);
       builder.setView(input);

       // Set up the buttons
       builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
           @Override
           public void onClick(DialogInterface dialog, int which) {
             
               m_Text = input.getText().toString();
               int id=Integer.parseInt(m_Text);
               
               String fullquery=query+id;
               try
               {
               db.execSQL(fullquery);
               }
               catch(Exception ex)
               {
                     showdisplaylong(ex.getMessage());
               }
               showdisplaylong("Record.."+m_Text+passMessage);
           }
           
       });
       builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
           @Override
           public void onClick(DialogInterface dialog, int which) {
               dialog.cancel();
               showdisplaysmall("Operation Canceled By User");
           }
       });

       builder.show();
      
    }


DISPLAY TOAST METHOD:
   public void showdisplaylong(String val)
    {
       Toast.makeText(this, val, Toast.LENGTH_LONG).show();
      
      
    }


Friday, November 6, 2015

HIBERNATE (CRUD) OPERATIONS

INSERT

String sname=request.getParameter("sname");
            SessionFactory sdf=new Configuration().configure().buildSessionFactory();
            Session s=sdf.openSession();
            Transaction tr=s.beginTransaction();
            Hyper obj=new Hyper(1,fname,sname);
            s.save(obj);
            tr.commit();
            s.close();
            out.println("DATA INSERTED....");

SELECT
SessionFactory sdf=new Configuration().configure().buildSessionFactory();           
            Session session=sdf.openSession();
            Transaction tx=session.beginTransaction();
            List employees = session.createQuery("FROM Hyper").list();
            for(int i=0;i<employees.size();i++)
            {
                Hyper hyper=(Hyper) employees.get(i);
                out.println(hyper.getId());
            out.println(hyper.getFname());
            out.println(hyper.getSname());
            out.println("</br>");
           
               
               // out.println(employees.get(i));
            }
UPDATE:
String fname=request.getParameter("fname");
                String sname=request.getParameter("sname");
                String upd=request.getParameter("upd");
            SessionFactory factory1 = new Configuration().configure().buildSessionFactory();
           
            Session session=factory1.openSession();
            Transaction tx=session.beginTransaction();
            String hql = "UPDATE Hyper set fname = :temp ,sname = :temp1 "  +
             "WHERE id = :id";        
out.println(fname);
out.println(sname);
out.println(upd);
Query query = session.createQuery(hql);
query.setParameter("temp",fname);
query.setParameter("temp1",sname);
query.setParameter("id",Integer.parseInt(upd));
int result = query.executeUpdate();
out.println("Rows affected: " + result);
tx.commit();
session.close();
DELETE
String delid=request.getParameter("del");
           
            SessionFactory factory1 = new Configuration().configure().buildSessionFactory();
           
            Session session=factory1.openSession();
            Transaction tx=session.beginTransaction();
            String hql = "DELETE FROM Hyper "  +
             "WHERE id = :id";
Query query = session.createQuery(hql);
query.setParameter("id", Integer.parseInt(delid));
int result = query.executeUpdate();
//Regis r=new (Regis) result;
out.println("Rows DELETED: " + result);
//session.save(query);
tx.commit();

session.close();

 TO GET MAX ID

     Criteria criteria = s.createCriteria(Datahandler.class)
    .setProjection(Projections.max("id"));
      Integer maxid = (Integer)criteria.uniqueResult()+1;

      Transaction tr=s.beginTransaction();