RSS

Monthly Archives: July 2012

Android AlertDialog

Hey guys, today we gonna look at AlertDialogs. AlertDialogs are used when you want to inform the user of something urgent. There are different types of dialogs which we’ll see as we go on. That’s pretty much it for the theory. Lets look at the implemenation.

In this example, I’ll show how to alert the user when he presses an exit button prompting him if he really wants to exit. You’ve seen this type of dialog a gazilion times im sure of it.

First off we build the alert.

AlertDialog alert = new AlertDialog.Builder(Camera.this).create();

AlertDialog.builder(Context) takes in a context as an argument. In this case the class is Camera and its context will be Camera.this.

alert.setMessage("Are you sure you want to exit?");

setMessage() method will display the message in the alert.

alert.setButton("Yes", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					Camera.this.finish();
				}
			});

setButton() takes in a string and a listener as its arguments. The string is the text that will display on the button. The listener is what adds the functionality to the button. In this case if the user clicks on this button it should end the app.

Finally we have to display the alert.

alert.show();

There are other methods like the setTitle() which sets the title.
It should look like this:

Here is the full code snippet:

AlertDialog alert = new AlertDialog.Builder(Camera.this).create();
			alert.setMessage("Are you sure you want to exit?");
			alert.setButton("Yes", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					Camera.this.finish();
				}
			});
                       alert.setButton2("No", new DialogInterface.OnClickListener(){
				public void onClick(DialogInterface dialog, int which){
					dialog.cancel();
				}
				
			});
			alert.show();
 
Leave a comment

Posted by on July 25, 2012 in Uncategorized

 

Android Emulator’s Proxy settings

hey guys, this is gonna be a short one. If you are behind a proxy and you’ve wrote this cool app that accesses the internet and just cant get it to run on the emulator, then you are in the right place, well if you aren’t then a little won’t hurt you.
Changing the proxy settings on eclipse or the skd manager doesn’t change the proxy on the emulator, so what you got to do is to start the emulator.
Locate the settings – either press Menu -> settings at the home screen or from the launcher look for settings.

or

Go to Wireless and Networks -> Mobile Networks -> Access Point Names -> Telkila

Change the proxy and port and username and password if you have one. Another thing: DON’T forget to save. Hit menu then save:

 
Leave a comment

Posted by on July 25, 2012 in Android tutorials

 

area of Circle

#include <iostream>

using namespace std;

class Circle{
    private:
        double radius, area;
    public:
        Circle(double r){
            radius = r;
        }
        void setRadius(double r);
        double getRadius();
        double AreaOfCircle();

};

class Cylinder: public Circle{
    private:
        double height;
    public:
        Cylinder(double r,double h);
        double SArea();
        double Volume();
        void details();
};

void Circle::setRadius(double r){
    radius = r;
}
double Circle::getRadius(){
    return radius;
}
double Circle::AreaOfCircle(){
    area = 3.142 * radius * radius;
    return area;
}
Cylinder::Cylinder(double r,double h) : Circle(r){
    height = h;
}
double Cylinder::SArea(){
    double surface_area = 3.142 * 2 * getRadius()* height + AreaOfCircle();
    return surface_area;
}
double Cylinder::Volume(){
    double volume = AreaOfCircle() * height;
    return volume;
}
void Cylinder::details(){
    cout<<"Cylinder details: "<<endl;
    cout<<"Radius: "<<getRadius()<<endl;
    cout<<"Height: "<<height<<endl;
    cout<<"Area of circle: "<<AreaOfCircle()<<endl;
    cout<<"Surface Area: "<<SArea()<<endl;
    cout<<"Volume: "<<Volume()<<endl;

}
int main()
{
    Cylinder one(7, 10);
    one.details();
    return 0;
}


 
Leave a comment

Posted by on July 24, 2012 in C++

 

A look at operator overloading and alot of C++ stuff

Main.cpp

#include <iostream>
#include "Rational.h"
using namespace std;

int main()
{
    Rational half(1,2), two_thirds(2,3), four_fifths(4,5);
    Rational third(1,3), one(1,1), two(2,1);
    Rational answer;

    answer = third * half;
    answer.printRational();

    answer = half + four_fifths / two * (third + one); //does bodmas
    answer.printRational();

    (half + third).printRational();

    third.add(two).printRational();


    return 0;
}

The header:
Rational.h

#ifndef RATIONAL_H
#define RATIONAL_H


class Rational{
    public:
        Rational();
        Rational(int, int);
        //Operator overloading. This four are the main methods
        Rational operator+(Rational);
        Rational operator-(Rational);
        Rational operator*(Rational);
        Rational operator/(Rational);
        Rational operator()(Rational);

        //This others just call the four above
        Rational add(Rational);
        Rational Subtract(Rational);
        Rational multiply(Rational);
        Rational divide(Rational);
        Rational add(int, int);
        Rational Subtract(int, int);
        Rational multiply(int, int);
        Rational divide(int, int);
        //This are used within the methods
        void simplify();
        void printRational();
        void improper();
        int GCD(int, int);
    private:
    //a is the numerator and d the denominator. whole keeps the whole number part
        int a, b, whole;

};

#endif // RATIONAL_H

and the meat of the code:
Rational.cpp

#include "Rational.h"
#include <iostream>

using namespace std;

Rational::Rational()
{
    a = 0;
    b = 1;
    whole =0;
}
int Rational::GCD(int a, int b){
    if(a%b == 0)
        return b;
    else
        return GCD(b, a%b);
}
Rational::Rational(int x, int y){
    a = x;
    if(y != 0){
        b = y;
    }else{
        //Validation
        cout<<"Denominator cannot be zero";
        b =1;
    }
    whole=0;
    simplify();
}

void Rational::simplify(){
        //get the whole part of the fraction
        whole = a/b;
        //first get the greatest common divisor of the two
        int gcd = GCD(a , b);
        a = a%b;
        a = a / gcd; //numerator
        b = b / gcd; //denominator

}
void Rational::improper(){
    if(whole != 0)
        a = whole * b + a;
}

void Rational::printRational(){
    simplify();
    // if no whole number no need to print 0, if b is zero just print the whole part
    if(whole ==0 && a != 0)
        cout<<a<<"/"<<b<<endl;
    else if(a== 0)
        cout<<whole<<endl;
    else
        cout<<whole<<" "<<a<<"/"<<b<<endl;
}
//overloading the addition operator. An addition sign between two objects
//of Rational class will cause this method to be executed
Rational Rational::operator+(Rational frac){
    Rational obj; //Initialise an object from Rational class;
    improper(); //Change to improper fractions to get rid of the whole number part
    frac.improper();
    obj.b = b * frac.b;        // a/b + c/d = (ad + cb)/bd
    obj.a = a * frac.b + frac.a * b;

    return obj;  //return the object with its a and b values altered
}
Rational Rational::operator-(Rational frac){
    Rational obj; //Similar as above
    improper();
    frac.improper();
    obj.b = b * frac.b;  // a/b - c/d = (ad - bc)/bd
    obj.a = a * frac.b - frac.a * b;

    return obj;
}
Rational Rational::operator*(Rational frac){
    Rational obj;
    improper();
    frac.improper();
    obj.b = b * frac.b;  // a/b * c/d = ac/bd
    obj.a = a * frac.a;

    return obj;
}
Rational Rational::operator/(Rational frac){
    Rational obj;
    improper();
    frac.improper();
    obj.a = a * frac.b; //a/b / c/d = ad / bc
    obj.b = b * frac.a;

    return obj;
}
//Overloading the brackets will allow:
// third * (half + third)
Rational Rational::operator()(Rational frac){
    //the object pointed to by 'this'(thats this object) multiplied by another
    //object
    Rational obj = *this * frac; //the * has been overloaded

    return obj;
}
Rational Rational::multiply(Rational frac){
    Rational obj = *this /frac; //Using operator overloading use this object divided by frac and return the new object
    return obj;
}
Rational Rational::add(Rational frac){
    Rational obj = *this + frac;
    return obj;
}
Rational Rational::Subtract(Rational frac){
    Rational obj = *this - frac;
    return obj;
}
Rational Rational::divide(Rational frac){
    Rational obj = *this / frac;
    return obj;
}
Rational Rational::add(int x, int y){
    Rational obj,frac(x,y);
    obj = *this + frac;

    return obj;
}
Rational Rational::Subtract(int x, int y){
    Rational obj,frac(x,y);
    obj = *this - frac;

    return obj;
}
Rational Rational::multiply(int x, int y){
    Rational obj,frac(x,y);
    obj = *this * frac;

    return obj;
}
Rational Rational::divide(int x, int y){
    Rational obj,frac(x,y);
    obj = *this / frac;

    return obj;
}

 
Leave a comment

Posted by on July 23, 2012 in C++

 

Android getting tweets from Twitter to your app

The following source code describes an app that gets ur very last tweet and displays it on a TextView, nothing to complicated on the xml part. It uses JSONParsing.

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;

public class JSONStuff extends Activity{
	
		TextView tweet;
		final static String URL = "http://api.twitter.com/1/statuses/user_timeline.json?screen_name=";
		HttpClient client;
		JSONObject json;
		
	protected void onCreate(Bundle b){
		super.onCreate(b);
		setContentView(R.layout.tweet);
		tweet = (TextView) findViewById(R.id.tvtweet);
		
		client = new DefaultHttpClient();
		
		new Read().execute("text");
	}
	
	public JSONObject lastTweet(String username) throws ClientProtocolException, IOException, JSONException{
		StringBuilder url= new StringBuilder(URL);
		url.append(username);
		
		HttpGet get = new HttpGet(url.toString());
		HttpResponse r = client.execute(get);
		int status = r.getStatusLine().getStatusCode();
		
		if(status == 200 ){
			HttpEntity e = r.getEntity();
			String data = EntityUtils.toString(e);
			JSONArray timeline = new JSONArray(data);
			JSONObject last = timeline.getJSONObject(0);
			
			return last;
		}else{
			Toast.makeText(JSONStuff.this, "Error", Toast.LENGTH_SHORT);
			return null;
			
		}
		
		
		
	}
	public class Read extends AsyncTask<String, Integer, String>{

		@Override
		protected String doInBackground(String... params) {
			
			try {
				json = lastTweet("gilokimu");
				return json.getString(params[0]);
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (ClientProtocolException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return null;
			
		}

		@Override
		protected void onPostExecute(String result) {
			// TODO Auto-generated method stub
			tweet.setText(result);
		}
		
		
	}
	

}

 
Leave a comment

Posted by on July 17, 2012 in Uncategorized

 

Android SeekBar to set the volume.


Below is how you can use a SeekBar to adjust the volume:

package com.learning.gilo;

import android.app.Activity;
import android.content.Context;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.Toast;

public class SetVolume extends Activity implements OnSeekBarChangeListener{

	SeekBar sb;
	MediaPlayer mp;
	AudioManager am;
	int Volume=0;
	
	protected void onCreate(Bundle b){
		super.onCreate(b);
		setContentView(R.layout.seek);
		
		sb  =(SeekBar) findViewById(R.id.sbVolume);
		mp = MediaPlayer.create(this, R.raw.say);
		am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
		
		mp.start();
		int maxVolume = am.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
		int curVolume = am.getStreamVolume(AudioManager.STREAM_MUSIC);
		
		sb.setMax(maxVolume);
		sb.setProgress(curVolume);
		
		sb.setOnSeekBarChangeListener(this);
	}
	
	protected void onPause(){
		super.onPause();
		
		mp.pause();
		//mp.release();
	}
	protected void onResume(){
		super.onResume();
		
		mp.start();
		
	}
	
	public void onProgressChanged(SeekBar seekb, int progress, boolean arg2) {
			am.setStreamVolume(AudioManager.STREAM_MUSIC, progress, 0);
			Volume = progress;		
	}

	public void onStartTrackingTouch(SeekBar arg0) {
		// TODO Auto-generated method stub
		
	}

	public void onStopTrackingTouch(SeekBar arg0) {
		// TODO Auto-generated method stub
		Toast.makeText(getApplicationContext(), "Volume: " + Integer.toString(Volume), Toast.LENGTH_SHORT).show();
	}
}


 
10 Comments

Posted by on July 13, 2012 in Uncategorized

 

Creating a Dialog from code

In my earlier blogpost I mentioned something about a dialog. Here is how to build one:

                        Dialog d =new Dialog(this);
			d.setTitle("Oh Yeah!!");
			TextView tv =new TextView(this);
			tv.setText("This is a dialog");

			d.setContentView(tv);
			d.show();

In the above code snippet what is happening is; an instance of the Dialog class is created which takes in a context(this):

Dialog d =new Dialog(this);

The title is set:

d.setTitle("Oh Yea!!");

Make an instance of the TextView which takes a context of this and set its text. This will form the body of the dialog.


TextView tv =new TextView(this);
tv.setText("This is a dialog");

Add the TextView to the dialog and show it to the user


d.setContentView(tv);
d.show();

 
Leave a comment

Posted by on July 13, 2012 in Uncategorized