jeudi 24 décembre 2015

How to save the generated textView into the database

In my android project i am having registration page..in that i am saving three edit text values to the database when a register button is pressed..and also i am generating random alphanumeric string when a register button is pressed in the textview place..that is after "textview2"..Now i have to save that generated string to the database along with those three edit text values. I dont know how to achieve this..Here i am saving only three values..i have to save that generated value with those three values in the database.

please help me to get this..

Below is my code..any help would be appreciated...thanks in advance..

DataBaseHelper.java

package com.example.miisky;

import android.app.Activity;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;

public class DataBaseHelper extends SQLiteOpenHelper{

    public DataBaseHelper(Context context, String name, CursorFactory factory, int version) {
        super(context, name, factory, version);
        // TODO Auto-generated constructor stub
    }

    @Override
    public void onCreate(SQLiteDatabase _db) {
        // TODO Auto-generated method stub

                _db.execSQL(LoginDataBaseAdapter.DATABASE_CREATE);

    }

    @Override
    public void onUpgrade(SQLiteDatabase _db, int _oldVersion, int _newVersion) {
        // TODO Auto-generated method stub

        Log.w("TaskDBAdapter", "Upgrading from version " +_oldVersion + " to " +_newVersion + ", which will destroy all old data");
        _db.execSQL("DROP TABLE IF EXISTS " + "TEMPLATE");
        // Create a new one.
        onCreate(_db);
    }
}

RegisterPage.java

package com.example.miisky;

import java.util.Random;


import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Typeface;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.text.SpannableString;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.text.style.ForegroundColorSpan;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.TextView.BufferType;
import android.widget.Toast;

public class RegisterPage extends Activity {

    final Context context = this;
    LoginDataBaseAdapter loginDataBaseAdapter;

     Random random = new Random();
     private static final String _CHAR = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890abcdefghijklmnopqrstuvwxyz!@#$%^&*_=+-/";
     private static final int RANDOM_STR_LENGTH = 15;

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

        ImageView img1 = (ImageView) findViewById(R.id.imageView1);
        TextView txt = (TextView)findViewById(R.id.textview1);

        final EditText ed1 = (EditText)findViewById(R.id.editText1);
        final EditText ed2 = (EditText)findViewById(R.id.editText2);
        final EditText ed5 = (EditText)findViewById(R.id.editText5);
        final EditText ed6 = (EditText)findViewById(R.id.editText6);
        TextView ch  = (TextView)findViewById(R.id.textview22);

        loginDataBaseAdapter=new LoginDataBaseAdapter(this);
        loginDataBaseAdapter=loginDataBaseAdapter.open();
        //setting Textview's text color
        SpannableString text = new SpannableString("By clicking Register you have agreed to our policy");
        text.setSpan(new ForegroundColorSpan(Color.GRAY), 0, 43, 0);//grey color for 0-43 characters.

        //displays Policy page if pressed.
        final Context context = this;  
        ClickableSpan clickableSpan = new ClickableSpan() {  
            @Override  
            public void onClick(View view) {  
                Intent intent = new Intent(context,Policy.class) ;
                startActivity(intent);
            }  
        };
        text.setSpan(clickableSpan, 44, 50, 0);
        text.setSpan(new ForegroundColorSpan(Color.BLUE), 44, 50, 0);//blue color for 44-50 characters

        ch.setMovementMethod(LinkMovementMethod.getInstance());// 
        ch.setText(text, BufferType.SPANNABLE);

        Button bt = (Button)findViewById(R.id.button1);
        bt.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {


            String  first = ed1.getText().toString();
            String last = ed2.getText().toString();
            //String email = ed3.getText().toString();
            //String password = ed4.getText().toString();
            String mobile = ed5.getText().toString();
            String otp = ed6.getText().toString();

            //ed1.setText("hello"+ed1.getText().toString());


            //Initializing flags
            boolean failFlag = false;
            //field validation
            if(first.length()==0)//empty validation for first name 
            {
                    //Toast.makeText(getApplicationContext(), "Field Vaccant", Toast.LENGTH_LONG).show();
                failFlag = true;
                ed1.setError("first name cannot be empty");
                    return ;
            }
            if(!first.matches("[a-zA-Z ]+"))//checks first name contains only alphabets.
            {
                failFlag=true;
                ed1.setError("enter only alphabetical character");
                return;
            }
             if(last.length()==0)//empty validation for last name.
            {
                //Toast.makeText(getApplicationContext(), "Field Vaccant", Toast.LENGTH_LONG).show();
                 failFlag = true;
                 ed2.setError("last name cannot be empty");
                return;
            }
             if(!last.matches("[a-zA-Z ]+"))//checks last name contains only alphabets.
             {
                    //Toast.makeText(getApplicationContext(), "Field Vaccant", Toast.LENGTH_LONG).show();
                 failFlag = true;
                 ed5.setError("enter valid mobile number");
                    return;
            }

             if (mobile != null && mobile.length() < 10) {//checks for empty field entry and valid mobile number.

                 failFlag = true;
                 ed5.setError("invalid mobile number");
                return ;
            }

             if(!mobile.matches("[0-9 ]+"))//mobile number should contain only numbers.
             {
                    //Toast.makeText(getApplicationContext(), "Field Vacant", Toast.LENGTH_LONG).show();
                 failFlag = true;
                 ed2.setError("enter only alphabetical character");
                    return;
            }
            if(otp.length()==0)//checks for empty otp field.
            {
                //Toast.makeText(getApplicationContext(), "Field Vacant", Toast.LENGTH_LONG).show(); 
                failFlag=true;
                ed6.setError("otp should not be empty");
                return;
            }
            if(failFlag == false)//if all the above fields are validated.store data into database.
            {
                // Save the Data in Database
                loginDataBaseAdapter.insertEntry(first,last,mobile,otp);
                /*Toast.makeText(getApplicationContext(), "Account Successfully Created ", Toast.LENGTH_SHORT).show();
                Intent intent = new Intent(getApplicationContext(),HomePage.class);
                startActivity(intent);*/

                //textview to display random string.
                TextView text_Random = (TextView) findViewById(R.id.textView01);
                text_Random.setText(getRandomString());
            }

              }
            });
    }

    //generates random string.
    public String getRandomString(){
        StringBuffer randStr = new StringBuffer();
        for (int i = 0; i < RANDOM_STR_LENGTH; i++) {
              int number = getRandomNumber();
              char ch = _CHAR.charAt(number);
              randStr.append(ch);
        }
        return randStr.toString();
  }

    //generates random number.
  private int getRandomNumber() {
        int randomInt = 0;
        randomInt = random.nextInt(_CHAR.length());
        if (randomInt - 1 == -1) {
              return randomInt;
        } else {
              return randomInt - 1;
        }
  }

    @Override
    protected void onDestroy() 
    {
        // TODO Auto-generated method stub
        super.onDestroy();
        loginDataBaseAdapter.close();
    }
}

LoginDataBaseAdapter.java

package com.example.miisky;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

public class LoginDataBaseAdapter {

    static final String DATABASE_NAME = "login.db";//creating database name login
    static final int DATABASE_VERSION = 1;
    public static final int NAME_COLUMN = 1;


    /*creating database table name LOGIN with columns first name,
    **last name,mobile number,otp..*/
    static final String DATABASE_CREATE = "create table "+"LOGIN"+
            "( " +"ID"+" integer primary key autoincrement,"+ "FIRST text,LAST text,MOBILE text,OTP text); ";

    public  SQLiteDatabase db;
    // Context of the application using the database.
    private final Context context;
    // Database open/upgrade helper
    private DataBaseHelper dbHelper;

    public  LoginDataBaseAdapter(Context _context) 
    {
        context = _context;
        dbHelper = new DataBaseHelper(context, DATABASE_NAME, null, DATABASE_VERSION);
    }
    public  LoginDataBaseAdapter open() throws SQLException 
    {
        db = dbHelper.getWritableDatabase();
        return this;
    }
    public void close() 
    {
        db.close();
    }
    public  SQLiteDatabase getDatabaseInstance()
    {
        return db;
    }
    public void insertEntry(String first, String last, String mobile, String otp)
    {
       ContentValues newValues = new ContentValues();
        // Assign values for each row.
        newValues.put("FIRST",first);
        newValues.put("LAST",last);
        newValues.put("MOBILE", mobile);
        newValues.put("OTP", otp);

        // Insert the row into your table
        db.insert("LOGIN", null, newValues);
        ///Toast.makeText(context, "Reminder Is Successfully Saved", Toast.LENGTH_LONG).show();
    }
    public int deleteEntry(String UserName)
    {
        //String id=String.valueOf(ID);
        String where="FIRST=?";
        int numberOFEntriesDeleted= db.delete("LOGIN", where, new String[]{UserName}) ;
       // Toast.makeText(context, "Number for Entry Deleted Successfully : "+numberOFEntriesDeleted, Toast.LENGTH_LONG).show();
        return numberOFEntriesDeleted;
    }
    public String getSinlgeEntry(String first)
    {
        Cursor cursor=db.query("LOGIN", null, " FIRST=?", new String[]{first}, null, null, null);
        if(cursor.getCount()<1) // First name Not Exist
        {
            cursor.close();
            return "NOT EXIST";
        }
        cursor.moveToFirst();
        String otp= cursor.getString(cursor.getColumnIndex("OTP"));
        cursor.close();
        return otp;             
    }
    public void  updateEntry(String first, String last, String mobile, String otp)
    {
        // Define the updated row content.
        ContentValues updatedValues = new ContentValues();
        // Assign values for each row.
        updatedValues.put("FIRST",first);
        updatedValues.put("LAST",last);
        /*updatedValues.put("EMAIL", email);
        updatedValues.put("PASSWORD",password);*/
        updatedValues.put("MOBILE", mobile);

        String where="FIRST = ?";
        db.update("LOGIN",updatedValues, where, new String[]{first});              
    }   
}

Aucun commentaire:

Enregistrer un commentaire