Powered By Blogger

Monday 11 March 2013

Global Array List


public static List<QuizQuestion> matchlist;

ArrayList<QuizQuestion> quest;


JSONObject Question = (new JSONObject(jstring))
.getJSONObject("");


Integer length = Question.length();
quest = new ArrayList<QuizQuestion>(length);
quizquestion = new QuizQuestion();

quizquestion = new QuizQuestion();
for (int i = 0; i < length; i++) {
quizquestion = new QuizQuestion();
//all the code.

                                                           quest.add(i, quizquestion);
                                                 }
    Global.setMatchlist(quest);

Checkmail


public boolean checkmail(String email2) {
Pattern pattern = Pattern
.compile("^([a-zA-Z0-9_.-])+@([a-zA-Z0-9_.-])+\\.([a-zA-Z])+([a-zA-Z])+");
return pattern.matcher(email2).matches();
}

DOM Parser

[sourcecode language="xml"]
<maintag>
<item>
<name>AndroidPeople</name>
<website category="android">www.androidpeople.com</website>
</item>
<item>
<name>iPhoneAppDeveloper</name>
<website category="iPhone">www.iphone-app-developer.com</website>
</item>
</maintag>
[/sourcecode]

Source Code


import java.net.URL;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import android.app.Activity;
import android.os.Bundle;
import android.widget.LinearLayout;
import android.widget.TextView;
public class XMLParsingDOMExample extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/** Create a new layout to display the view */
LinearLayout layout = new LinearLayout(this);
layout.setOrientation(1);
/** Create a new textview array to display the results */
TextView name[];
TextView website[];
TextView category[];
try {
URL url = new URL(
"http://www.androidpeople.com/wp-content/uploads/2010/06/example.xml");
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new InputSource(url.openStream()));
doc.getDocumentElement().normalize();
NodeList nodeList = doc.getElementsByTagName("item");
/** Assign textview array lenght by arraylist size */
name = new TextView[nodeList.getLength()];
website = new TextView[nodeList.getLength()];
category = new TextView[nodeList.getLength()];
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
name[i] = new TextView(this);
website[i] = new TextView(this);
category[i] = new TextView(this);
Element fstElmnt = (Element) node;
NodeList nameList = fstElmnt.getElementsByTagName("name");
Element nameElement = (Element) nameList.item(0);
nameList = nameElement.getChildNodes();
name[i].setText("Name = "
+ ((Node) nameList.item(0)).getNodeValue());
NodeList websiteList = fstElmnt.getElementsByTagName("website");
Element websiteElement = (Element) websiteList.item(0);
websiteList = websiteElement.getChildNodes();
website[i].setText("Website = "
+ ((Node) websiteList.item(0)).getNodeValue());
category[i].setText("Website Category = "
+ websiteElement.getAttribute("category"));
layout.addView(name[i]);
layout.addView(website[i]);
layout.addView(category[i]);
}
} catch (Exception e) {
System.out.println("XML Pasing Excpetion = " + e);
}
/** Set the layout view to display */
setContentView(layout);
}
}

Wednesday 6 March 2013

Creating a layout with Relative Layout


<?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:background="@drawable/body_bg"
    tools:context=".LoginActivity" >

     <include
        android:id="@+id/header_lyt"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        layout="@layout/header_layout" >
    </include>
   
     <RelativeLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@id/header_lyt"
        android:layout_marginTop="20dip"
            android:padding="10dip" >
           
         <RelativeLayout
                android:id="@+id/Layout_Email_id"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_gravity="center" >
           
           
             <LinearLayout
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content"
                     >
               
                 <ImageView
                     android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:id="@+id/logo_img"
                    android:src="@drawable/login_logo"
                   android:paddingLeft="110dip"
                     />
               
               
               
             </LinearLayout>
           
           
         </RelativeLayout>
       
         <RelativeLayout
                android:id="@+id/Layout_Password"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_below="@id/Layout_Email_id"
                android:layout_gravity="center"
                android:layout_marginTop="1dip" >
           
              <LinearLayout
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content"
                   
                     >
               
                 
                  <TextView
                        android:id="@+id/logo"
                        android:layout_width="wrap_content"
                        android:paddingLeft="45dip"
                       
                        android:textColor="#000000"
                        android:textSize="34dip"
                        android:text="@string/app_name"
                        android:layout_height="wrap_content" />
              </LinearLayout>
           
           
           
         </RelativeLayout>
       
         <RelativeLayout
                android:id="@+id/Layout_desc"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_below="@id/Layout_Password"
                android:layout_gravity="center"
                android:layout_marginTop="1dip" >
           
              <LinearLayout
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content"
                   
                     >
               
                 
                  <TextView
                        android:id="@+id/logo"
                        android:layout_width="wrap_content"
                        android:paddingLeft="42dip"
                        android:textColor="#000000"
                        android:textSize="10dip"
                        android:text="Relationship Management Tools by DeltaPoint"
                        android:layout_height="wrap_content" />
              </LinearLayout>
           
           
           
         </RelativeLayout>
       
         <RelativeLayout
                android:id="@+id/Layout_seprator"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_below="@id/Layout_desc"
                android:layout_gravity="center"
                android:layout_marginTop="1dip" >
           
             
               
                 
                  <ImageView
                      android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:src="@drawable/seperator"
                    android:layout_centerInParent="true"
                      />
           
           
           
           
         </RelativeLayout>
       
         <RelativeLayout
                android:id="@+id/Layout_detail"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_below="@id/Layout_seprator"
                android:layout_gravity="center"
                android:layout_marginTop="6dip" >
           
           
               
                 
                  <TextView
                        android:id="@+id/tx_detail"
                        android:layout_width="wrap_content"
                     
                        android:textColor="#000000"
                        android:textSize="12dip"
                        android:paddingLeft="15dip"
                        android:textStyle="bold"
                         android:layout_centerVertical="true"
                        android:text="Enter your Login Details"
                        android:layout_height="wrap_content" />
                 
                  <TextView
                        android:id="@+id/tx_newuser"
                        android:layout_toRightOf="@id/tx_detail"
                        android:layout_width="wrap_content"
                       android:layout_height="wrap_content"
                       android:paddingLeft="27dip"
                       android:textSize="12dip"
                        android:layout_centerVertical="true"
                       android:text="New User?"
                        android:textColor="#000000"></TextView>
                  <Button
                      android:id="@+id/signuplbl"
                        android:layout_centerVertical="true"
                        android:layout_width="wrap_content"
                       android:layout_height="wrap_content"
                       android:layout_alignParentRight="true"
                      android:layout_marginRight="22dip"
                      android:text="Sign Up"
                      android:textColor="#ffffff"
                      android:textSize="10dip"
                       android:background="@drawable/sign_up"
                      />
                 
           
           
           
           
         </RelativeLayout>
       
         <RelativeLayout
                android:id="@+id/Layout_userid"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_below="@id/Layout_detail"
                android:layout_gravity="center"
                android:layout_marginTop="4dip" >
                 
           
              <TextView
                        android:id="@+id/tx_userid"
                        android:layout_width="wrap_content"
                     
                        android:textColor="#000000"
                        android:textSize="12dip"
                        android:paddingLeft="15dip"
                        android:textStyle="bold"
                         android:layout_centerVertical="true"
                        android:text="User ID:"
                        android:layout_height="wrap_content" />
             
             
             
           
         </RelativeLayout>
       
         <RelativeLayout
                android:id="@+id/Layout_userid_text"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_below="@id/Layout_userid"
                android:layout_gravity="center"
                android:layout_marginTop="4dip" >
             
             <com.realationshiplink.util.CustomEditTextLarge
                        android:id="@+id/useridtxt"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:background="@drawable/text_field"
                        android:paddingLeft="15dip"
                        android:layout_marginLeft="15dip"
                        android:imeOptions="actionDone"
                        android:ems="5"
                        android:inputType="textEmailAddress"
                     
                         />
           
           
           
           
         </RelativeLayout>
       
          <RelativeLayout
                android:id="@+id/Layout_pwd"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_below="@id/Layout_userid_text"
                android:layout_gravity="center"
                android:layout_marginTop="4dip" >
               
             
                <TextView
                        android:id="@+id/tx_pwd"
                        android:layout_width="wrap_content"
                     
                        android:textColor="#000000"
                        android:textSize="12dip"
                        android:paddingLeft="15dip"
                        android:textStyle="bold"
                         android:layout_centerVertical="true"
                        android:text="Enter Your Password:"
                        android:layout_height="wrap_content" />
               
               
               
                </RelativeLayout>
               
           <RelativeLayout
                android:id="@+id/Layout_pwd_text"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_below="@id/Layout_pwd"
                android:layout_gravity="center"
                android:layout_marginTop="4dip" >
               
             
               <com.realationshiplink.util.CustomEditTextLarge
                        android:id="@+id/passwordtxt"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:background="@drawable/text_field"
                        android:paddingLeft="15dip"
                        android:layout_marginLeft="15dip"
                        android:inputType="textPassword"
                        android:password="true"
                       
                         />
             
             
           
             
             
             
           </RelativeLayout>
         
           <RelativeLayout
                android:id="@+id/Layout_remember"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_below="@id/Layout_pwd_text"
                android:layout_gravity="center"
                android:layout_marginTop="8dip" >
             
               <CheckBox
         android:id="@+id/check"
         android:layout_width="24dip"
         android:layout_height="24dip"
       
         android:layout_centerVertical="true"
         android:layout_marginLeft="15dip"
         android:button="@drawable/remember_invisible" />
             
               <TextView
   android:id="@+id/remembermelbl"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:layout_centerVertical="true"
   android:textColor="#2a2929"
   android:textSize="12dip"
   android:textStyle="bold"
 
   android:layout_toRightOf="@+id/check"
   android:text="@string/remembermestr"></TextView>
             
               
               <TextView
   android:id="@+id/sepreator"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:paddingLeft="2dip"
   android:layout_centerVertical="true"
   android:textColor="#2a2929"
 
   android:layout_toRightOf="@+id/remembermelbl"
   android:text="|"></TextView>
             
               <TextView
   android:id="@+id/forgetpin"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:layout_centerVertical="true"
   android:textColor="@color/blue"
   android:paddingLeft="2dip"
   android:textSize="12dip"
   android:textStyle="bold"
   android:layout_toRightOf="@+id/sepreator"
   android:text="Forgot Password?"></TextView>
             
             
             
           </RelativeLayout>
         
         
           <RelativeLayout
                android:id="@+id/Layout_loginbutton"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_below="@id/Layout_remember"
                android:layout_gravity="center"
                android:layout_marginTop="8dip" >
             
             
               <Button
                      android:id="@+id/submitBtn"
                        android:layout_centerVertical="true"
                        android:layout_width="wrap_content"
                       android:layout_height="wrap_content"
                      android:layout_centerInParent="true"
                     
                      android:text="Log in"
                      android:textColor="#ffffff"
                      android:textSize="20dip"
                      android:textStyle="bold"
                   
                       android:background="@drawable/login_bg"
                      />
             
             
           </RelativeLayout>
         
         
       
       
     </RelativeLayout>
   
   
   
   
</RelativeLayout>


HeaderLayout



<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:background="@drawable/navigation_bar">
 
 
  <!-- <ImageView
  android:layout_marginLeft="10dip"
  android:layout_centerVertical="true"
   android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:src="@drawable/back"
  android:layout_alignParentLeft="true">
  </ImageView> -->
 
 
  <LinearLayout
  android:id="@+id/ll"
   android:layout_centerInParent="true"
    android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:orientation="vertical">
 
  <TextView
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:textStyle="bold"
  android:textSize="20dip"
  android:id="@+id/header_text"
  android:textColor="#000000"
  android:text="WELCOME">
  </TextView>
 
 
  </LinearLayout>
 
  <LinearLayout
 
  android:layout_centerVertical="true"
  android:layout_alignParentRight="true"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:orientation="vertical">
 
  </LinearLayout>
 
</RelativeLayout>


Select image from Gallery



private PopupWindow pv = null;
ImageButton add_img;
add_img.setOnClickListener(new OnClickListener() {

public void onClick(View v) {
// TODO Auto-generated method stub
LayoutInflater li = (LayoutInflater) CreateAccount.this
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View popupView = li.inflate(R.layout.popup_window_layout,
(ViewGroup) findViewById(R.id.popup_layout));
cancle = (Button) popupView.findViewById(R.id.popup_cancle);
cancle.setTypeface(tf1);
cancle.setOnClickListener(new OnClickListener() {

public void onClick(View v) {
// TODO Auto-generated method stub
pv.dismiss();

}
});

uploadPhoto = (Button) popupView
.findViewById(R.id.popup_upload_photo);
uploadPhoto.setTypeface(tf1);
uploadPhoto.setOnClickListener(new OnClickListener() {

public void onClick(View v) {
// TODO Auto-generated method stub
System.out.println("uploadPhoto clicked");
Intent intent = new Intent();
intent.setType("image/*");

intent.setAction(Intent.ACTION_GET_CONTENT);
// setResult(Activity.RESULT_OK);
startActivityForResult(
Intent.createChooser(intent, "Select Picture"),
1111);
pv.dismiss();

}
});


@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
if (resultCode == RESULT_OK) {

               if (requestCode == 1111) {
System.out
.println("After Result 1111..........................................");

System.out.println("With in Take Image");
Uri imageUri = data.getData();
System.out.println(imageUri);
Cursor c = getContentResolver().query(imageUri, null, null,
null, null);
c.moveToFirst();
String imagePath = c.getString(c
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA));
System.out
.println("Before Setting Image:::::::::::::::::::::::::::::::::::::::::"
+ imagePath);
set_Image(imagePath);

try {
io = new FileInputStream(new File(imagePath));
System.out
.println("IO got set:::::::::::::::::::::::::::::::::::::::");
} catch (Exception e) {
e.printStackTrace();
}
image = imagePath;

}
}
super.onActivityResult(requestCode, resultCode, data);



}




private void set_Image(String imagePath) {
BitmapFactory.Options opt = null;

try {
System.out
.println("Image Path::::::::::::::::::::in Set Image::::::::::::::::::::"
+ imagePath);
FileInputStream in = new FileInputStream(imagePath);
System.out.println("1..................");
opt = new BitmapFactory.Options();
opt.inTempStorage = new byte[16 * 1024];
opt.inSampleSize = 4;
opt.outWidth = 640;
opt.outHeight = 480;
Bitmap imageBitmap = BitmapFactory
.decodeStream(in, new Rect(), opt);
Bitmap map = this.scaleDown(imageBitmap, 10, true);
BitmapDrawable bmd = new BitmapDrawable(map);

ByteArrayOutputStream bao = new ByteArrayOutputStream();

map.compress(Bitmap.CompressFormat.PNG, 90, bao);

ba = bao.toByteArray();

imagedata = Base64.encodeBytes(ba);
System.out.println("the image data is............." + imagedata);

add_img.setImageDrawable(bmd);
if (in != null) {
in.close();
}

} catch (OutOfMemoryError e) {
opt.inTempStorage = new byte[50 * 1024];
System.out.println(e.getMessage());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}


XML



<?xml version="1.0" encoding="UTF-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:orientation="vertical"
android:id="@+id/popup_layout"
android:background="#404040">
<!-- <Button
android:id="@+id/popup_take_photo"
android:layout_gravity="center"
android:layout_marginTop="20dip"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/btn_large_light_grey_key" android:text="Take Photo" android:textColor="#000000" android:textSize="14dip" android:textStyle="bold"/> -->
<Button
android:id="@+id/popup_upload_photo"
android:layout_gravity="center"
android:layout_marginTop="5dip"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Upload Photo" android:textColor="#000000" android:textSize="14dip" android:textStyle="bold"
android:background="@drawable/btn_large_light_grey_key"/>
<Button
android:id="@+id/popup_cancle"
android:layout_gravity="center"
android:layout_marginTop="5dip"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Cancel" android:textColor="#000000"
android:textSize="14dip" android:textStyle="bold"
android:background="@drawable/btln_large_dark_gray"/>
</LinearLayout>




HTTP Connection





public String getProfile() {

Log.d(TAG, "getProfile");

String url


String jsonString = "";

try {

JSONObject json = new JSONObject();

json.put("uid", User.getUserid());

jsonString = getHttpConnection(url, json);

} catch (JSONException e) {

e.printStackTrace();
}

return jsonString;
}



private String getHttpConnection(String url, JSONObject json) {

Log.d(TAG, "getHttpConnection");
Log.d(TAG, "url............ " + url);
Log.d(TAG, "Json.toString() :" + json.toString());

StringBuffer sb2 = new StringBuffer("");

try {

BufferedReader bufferreader = null;

List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("json", "["+ json.toString() + "]"));

int timeoutConnection = 0;
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters,timeoutConnection);

int timeoutSocket = 0;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
DefaultHttpClient client = new DefaultHttpClient(httpParameters);
HttpPost httppost = new HttpPost(url);

UrlEncodedFormEntity p_entity = new UrlEncodedFormEntity(nameValuePairs, HTTP.UTF_8);
httppost.setEntity(p_entity);
Log.d(TAG, "httppost : " + httppost.toString());

HttpResponse response = client.execute(httppost);

Log.d(TAG, "request executed set ");

InputStream inputstream = response.getEntity().getContent();

Log.d(TAG, "inputstreame set ");

bufferreader = new BufferedReader(
new InputStreamReader(inputstream));

if (inputstream != null) {

bufferreader = new BufferedReader(new InputStreamReader(inputstream));

while ((line = bufferreader.readLine()) != null) {
sb2.append(line);

}
Log.d(TAG, "sb2.toString()" + sb2.toString());

} else {
sb2 = null;
}


System.out.println("Closed input stream:::::::::::::::::::::::::::::::::");
} catch (HttpHostConnectException h) {

Log.e(TAG, "HttpHostConnectException ... ");

} catch (ConnectException e) {

Log.e(TAG, "ConnectException ... ");
Intent i = new Intent(context, ConnectivityManager.class);
context.sendBroadcast(i);
} catch (ConnectionClosedException e) {

Log.e(TAG, "ConnectionClosedException ... ");
Intent i = new Intent(context, ConnectivityManager.class);
context.sendBroadcast(i);
} catch (ConnectTimeoutException e) {
Log.e(TAG, "ConnectTimeoutException ... ");
e.printStackTrace();
return null;
} catch (UnknownHostException e) {

Log.e(TAG, "UnknownHostException ... ");
e.printStackTrace();

} catch (Exception e) {
Log.e(TAG, "GeneralException ... " + e);
e.printStackTrace();

}

return sb2.toString();
}

Monday 4 March 2013

How to get data from database file in Assest folder


package com.adeptpros.trivia.db;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

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

import com.adeptpros.trivia.quiz.Level;
import com.adeptpros.trivia.quiz.Question;


public class DBHelper extends SQLiteOpenHelper{

//The Android's default system path of your application database.
private static String DB_PATH = "/data/data/com.adeptpros.trivia/databases/";
private static String DB_NAME = "questionsDb";
private SQLiteDatabase myDataBase;
private final Context myContext;

/**
* Constructor
* Takes and keeps a reference of the passed context in order to access to the application assets and resources.
* @param context
*/
public DBHelper(Context context) {
super(context, DB_NAME, null, 1);
this.myContext = context;
System.out.println("With in Constructor......................");
}

/**
* Creates a empty database on the system and rewrites it with your own database.
* */
public void createDataBase() throws IOException{

boolean dbExist = checkDataBase();
if(!dbExist)
{
//By calling this method and empty database will be created into the default system path
//of your application so we are gonna be able to overwrite that database with our database.
this.getWritableDatabase();

try {
copyDataBase();
} catch (IOException e) {
throw new Error("Error copying database");
}
}
}

/**
* Check if the database already exist to avoid re-copying the file each time you open the application.
* @return true if it exists, false if it doesn't
*/
private boolean checkDataBase(){
SQLiteDatabase checkDB = null;
try{
String myPath = DB_PATH + DB_NAME;
checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);
}catch(SQLiteException e){
//database does't exist yet.
}
if(checkDB != null){
checkDB.close();
}

return checkDB != null ? true : false;
}

/**
* Copies your database from your local assets-folder to the just created empty database in the
* system folder, from where it can be accessed and handled.
* This is done by transfering bytestream.
* */
private void copyDataBase() throws IOException{

//Open your local db as the input stream
InputStream myInput = myContext.getAssets().open(DB_NAME);

// Path to the just created empty db
String outFileName = DB_PATH + DB_NAME;

//Open the empty db as the output stream
OutputStream myOutput = new FileOutputStream(outFileName);

//transfer bytes from the inputfile to the outputfile
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer))>0){
myOutput.write(buffer, 0, length);
}

//Close the streams
myOutput.flush();
myOutput.close();
myInput.close();

}

public void openDataBase() throws SQLException{
//Open the database
String myPath = DB_PATH + DB_NAME;
myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);
}


public synchronized void close() {
if(myDataBase != null)
myDataBase.close();
super.close();
}


public void onCreate(SQLiteDatabase db) {
}


public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}

// Add your public helper methods to access and get content from the database.
// You could return cursors by doing "return myDataBase.query(....)" so it'd be easy
// to you to create adapters for your views.




public List<Question> getQuestionSet(int difficulty, int numQ){
List<Question> questionSet = new ArrayList<Question>();
Cursor c = myDataBase.rawQuery("SELECT * FROM QUESTIONS WHERE DIFFICULTY=" + difficulty, null);
while (c.moveToNext()){
//Log.d("QUESTION", "Question Found in DB: " + c.getString(1));
Question q = new Question();
q.setQuestion(c.getString(1));
q.setAnswer(c.getString(2));
q.setOption1(c.getString(3));
q.setOption2(c.getString(4));
q.setOption3(c.getString(5));
q.setNote(c.getString(7));
q.setDiduknw(c.getString(8));
q.setRating(difficulty);
questionSet.add(q);
}
return questionSet;
}

public Level getSelectedLevel(int levelPosition){
openDataBase();
Cursor c = myDataBase.rawQuery("SELECT * FROM Levels WHERE Level_Number=" + levelPosition,null);
c.moveToFirst();
Level level=new Level();
level.setLevel_No(c.getInt(0));
level.setBest_Score(c.getInt(1));
level.setStar_Rating(c.getDouble(2));
level.setIsUnlocked(c.getString(3));
return level;
}


public ArrayList<Level> getUnlockedLevelsfromdb()
{

Cursor c = myDataBase.rawQuery("SELECT * FROM Levels WHERE is_Unlocked='Yes'" ,null);
c.moveToFirst();
ArrayList<Level> levels=new ArrayList<Level>();
for (int i = 0; i < c.getCount(); i++) {
Level level=new Level();
level.setLevel_No(c.getInt(0));
level.setBest_Score(c.getInt(1));
level.setStar_Rating(c.getDouble(2));
level.setIsUnlocked(c.getString(3));
levels.add(level);
c.moveToNext();
}
c.close();
return levels;
}

public void updateBestScore(int selectedPosition,ContentValues contentValues)
{
int k=myDataBase.update("Levels", contentValues, "Level_Number="+selectedPosition, null);
if(k>0)
{
System.out.println("Score Updated in Database.....");
}

}
public void updateStarCount(int selectedLevel,ContentValues contentValues)
{
int k=myDataBase.update("Levels", contentValues, "Level_Number="+selectedLevel, null);
if(k>0)
{
System.out.println("StarCount Updated in Database....."+selectedLevel);
}
}

public void UnlockNextLevel(int selectedPosition)
{
if(!myDataBase.isOpen())
openDataBase();
ContentValues contentValues=new ContentValues();
contentValues.put("is_Unlocked", "Yes");
int k=myDataBase.update("Levels",contentValues,"Level_Number="+(selectedPosition+1), null);
if(k>0)
{
System.out.println("Unlocked Successfully....."+(selectedPosition+1));
}
}
public double getStar_Rating(int level)
{
Cursor c = myDataBase.rawQuery("SELECT * FROM Levels WHERE Level_Number=" + (level) ,null);
c.moveToFirst();
if(c.getCount()!=0)
return c.getDouble(2);
else
return 0;
}


}