Showing posts with label sample. Show all posts
Showing posts with label sample. Show all posts

Friday, 14 February 2014

Parsing Json array-Windows phone

Looking forward on improving the GPS phone tutorial from last time, will be adding our pushpins and markers from a JSON(JavaScript Object Notation) array, so the first step will be to learn how to parse our array, this blog post will be short because this is not our main goal.

I will be using a PHP and WAMP server to locally host my the json data.
Requirements:

  1. wamp server download HERE
  2. Visual studio
  3. Newtonsoft.json.dll download HERE or you can install directly to your project in visual studio follow these steps:
  • click the project tab in visual studio
  • click manage NuGet packages
  • wait for it to load and select Json.NET click install, this will allow us import the Newtonsoft.json.dll library.
Let us begin by setting up our JSON data from our database through PHP. I am not going to explain the PHP code but the comments within the code should be really helpful.

I won't be going into database configuration either, if need help on that visit this website Kiwixcompo

If you can recall GPS phone was about finding restaurants on the map and call for a reservation or place an order. Our json encoded data has to fit this need.

This is the PHP script to encode our data.

This our db_connect.php file with our connection variables
<?php
define('DB_USER', "root");
define('DB_PASSWORD', "");
define('DB_DATABASE', "jsontest");
define('DB_SERVER', "localhost");
?>

This is our db_kinnect.php file which checks out database connection status and connects us to the database
<?php
 
/**
 * A class file to connect to database
 */
class DB_CONNECT {
 
    // constructor
    function __construct() {
        // connecting to database
        $this->connect();
    }
 
    // destructor
    function __destruct() {
        // closing db connection
        $this->close();
    }
 
    /**
     * Function to connect with database
     */
    function connect() {
        // import database connection variables
        require_once __DIR__ . '/db_connect.php';
 
        // Connecting to mysql database
        $con = mysql_connect(DB_SERVER, DB_USER, DB_PASSWORD) or die(mysql_error());
 
        // Selecing database
        $db = mysql_select_db(DB_DATABASE) or die(mysql_error()) or die(mysql_error());
 
        // returning connection cursor
        return $con;
    }
 
    /**
     * Function to close db connection
     */
    function close() {
        // closing db connection
        mysql_close();
    }
 
}
 
?>


This is the file that wil spit out our JSON from the database for our mobile consumption
<?php
 
/*
 * Following code will list all the Restaurants
 */
 
// array for JSON response
$response = array();
 
// include db connect class
require_once __DIR__ . '/db_kinect.php';
 
// connecting to db
$db = new DB_CONNECT();
 restaurants") or die(mysql_error());
 
// check for empty result
if (mysql_num_rows($result) > 0) {
    // looping through all results
    // restaurants node
    $response["restaurants"] = array();
 
    while ($row = mysql_fetch_array($result)) {
        // temp user array
        $restaurants_array = array();
        $restaurants_array["pid"] = $row["pid"];
        $restaurants_array["longitude"] = $row["longitude"];
        $restaurants_array["latitude"] = $row["latitude"];
        $restaurants_array["created_at"] = $row["created_at"];
        $restaurants_array["updated_at"] = $row["updated_at"];
        
        // push single restaurant into final response array
        array_push($response["restaurants"], $restaurants_array);
    }
    // success
    $response["success"] = 1;
 
    // echoing JSON response
    echo json_encode($response);
} else {
    // no location found
    $response["success"] = 0;
    $response["message"] = "No location found";
 
    // echo no users JSON
    echo json_encode($response);
}
?>
The php code above should give us the required json we desire. see out put below

{"restaurants":[{"pid":"1","longitude":"46.8799000000","latitude":"35.8779000000","created_at":"2014-02-09 17:24:49","updated_at":"0000-00-00 00:00:00"},{"pid":"2","longitude":"25.5858660000","latitude":"62.8585850000","created_at":"2014-02-09 19:51:14","updated_at":"0000-00-00 00:00:00"},{"pid":"3","longitude":"9.3241082570","latitude":"9.1728899140","created_at":"2014-02-11 23:52:43","updated_at":"0000-00-00 00:00:00"},{"pid":"4","longitude":"8.8359202210","latitude":"7.4974748750","created_at":"2014-02-11 23:52:43","updated_at":"0000-00-00 00:00:00"}],"success":1}

That is all the PHP-ing we will be doing (thank God); copy the output json and goto Json2csharp.com paste the json output and click generate button you will get two csharp classes that looks like these ones below

public class Restaurant
{
    public string pid { get; set; }
    public string longitude { get; set; }
    public string latitude { get; set; }
    public string created_at { get; set; }
    public string updated_at { get; set; }
}

public class RootObject
{
    public List restaurants { get; set; }
    public int success { get; set; }
}

With that done we are ready start coding our windows phone app
create a windows phone app and add a ListBox as shown below
<ListBox  HorizontalAlignment="Left"  Name="dList" Height="391" Margin="10,43,0,0" VerticalAlignment="Top" Width="436">

That is all we need to add next we have to switch over to our C# file and start the real work, first we have to add our Newtonsoft.Json
using Newtonsoft.Json;

We then setup our WebClient call to our JSON API as follows

//Web client call to JSON API
            WebClient wClient = new WebClient();
            wClient.DownloadStringCompleted +=new DownloadStringCompletedEventHandler(wClient_Downloaded);
            wClient.DownloadStringAsync(new Uri("http://localhost/Police/get_all_locs.php"));

Paste the Restaurant and RootObject classes we got from json2csharp into the MainPage class; the next thing we have to is implement our DownLoadStringCompleted event argument in this case wClient_Downloaded
public void wClient_Downloaded(object sender, DownloadStringCompletedEventArgs e)
        {
            try 
            {
                var rootObj = JsonConvert.DeserializeObject(e.Result);
                foreach(var stationz in rootObj.location)
                {
                  dList.Items.Add(stationz.station_name);
                    
                    dList.Items.Add(stationz.longitude);
                    dList.Items.Add(stationz.latitude);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error>>>> "+ex);
            }
        }

You will notice will notice we had put the commands within the try, catch blocks to handle any exception and that is all you need to consume JSON.

Full C# code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using Microsoft.Phone.Tasks;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.Device.Location;
using Microsoft.Phone.Controls.Maps;
using System.Windows.Media.Imaging;
using System.Windows.Controls.Primitives;
using System.ComponentModel;
using System.Collections;
using Newtonsoft.Json;

namespace PhoneApp4
{
    public partial class MainPage : PhoneApplicationPage
    {
        // Constructor
        public MainPage()
        {
            InitializeComponent();


            //Web client call to JSON API
            WebClient wClient = new WebClient();
            wClient.DownloadStringCompleted +=new DownloadStringCompletedEventHandler(wClient_Downloaded);
            wClient.DownloadStringAsync(new Uri("http://localhost/Police/get_all_locs.php"));

        }

        

        public void wClient_Downloaded(object sender, DownloadStringCompletedEventArgs e)
        {
            try 
            {
                var rootObj = JsonConvert.DeserializeObject(e.Result);
                foreach(var stationz in rootObj.location)
                {
                   dList.Items.Add(stationz.station_name);
                    
                    dList.Items.Add(stationz.longitude);
                    dList.Items.Add(stationz.latitude);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error>>>> "+ex);
            }
        }

 
        public class Location
        {
            public string pid { get; set; }
            public string longitude { get; set; }
            public string latitude { get; set; }
            public string created_at { get; set; }
            public string updated_at { get; set; }
            public string station_name { get; set; }
        }

        public class RootObject
        {
            public List location { get; set; }
            public int success { get; set; }
        }
    }
}

OUTPUT:

Thursday, 30 January 2014

Text to speech - Android

I remember back in school when i had little time to read and noticed that i had memorized lyrics of music i heard while sleeping lead me to download audio books but my lecture notes weren't audio books so i decided to write an app to read text for my then mytouch 3g slide, i just felt like visiting that memory once again with this tutorial.

Lets begin, create your android project and open the layout file (activity_main.xml), i left my default TextView but edited the output to something cooler and used it as my header, the main components you need to setup here are the EditText  and Button components which is shown in the code below:

<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:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <TextView
        android:id="@+id/header"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Have your text read" />
    
    <EditText 
        android:id="@+id/your_text"
        android:layout_below="@+id/header"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="textMultiLine"
        android:gravity="center"
        />

    <Button 
        android:id="@+id/speak_btn"
        android:layout_below="@+id/your_text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="please read my text"
        />
</RelativeLayout>


Now that we have painted the scene now it is time for action so switch to the MainActivity.java file for the main event (see what i did there :))
Okay we then declare our TextToSpeech, EditText and Button objects as follows:

        TextToSpeech textTS;
 Button speakBtn;
 EditText yourText;
you will a couple of errors, resolve by pressing ctrl+shift+o to import the necessary libraries and resolve the error.
Now you don't just name something and not bring it to life do you?
so we now initialize our objects in the onCreate() function so our objects are initialized when our application is started.
                //Initialize our objects
  textTS = new TextToSpeech(this, this);
  speakBtn = (Button)findViewById(R.id.speak_btn);
  yourText = (EditText)findViewById(R.id.your_text);
you will notice an error when initializing the textTS object you can resolve that by implementing this TextToSpeech.OnInitListener as follows:
public class MainActivity extends Activity implements TextToSpeech.OnInitListener
After doing the above you will have to implement a method to resolve the next error so just hover over the red line and select implement unimplemented method it will add a method (onInit)and resolve the problem.

Lets go back to our onCreate method and setup our onClickListener see the code below

//Hey when i click this button read my text
  speakBtn.setOnClickListener(new View.OnClickListener()
  {

   @Override
   public void onClick(View v) {
    // TODO Auto-generated method stub
    readText();
   }
   
  });
We just called a method readText() which we will implement later on. For now let us code our onInit(), this is where we will set our language, and check if our input is readable by our textTS object. The default speech rate was kinda fast for me so i reduced it from the default 1 to 0.7.
 @Override
 public void onInit(int status) {
  // TODO Auto-generated method stub
  if(status == TextToSpeech.SUCCESS)
  {
   int result = textTS.setLanguage(Locale.UK);
   textTS.setSpeechRate((float) 0.7);
   //textTS.setPitch(1);
   //Make sure that the data is valid
   //we check if our data if invalid or if the language received is invalid
   if(result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED)
   {
    Log.e("!!ER!!", "What crap are you feeding me");
   }
   //if our data is good we then proceed with our reading process
   else
   {
    speakBtn.setEnabled(true);
    readText();
   }
  }
 }
You will notice we call readText() again when our input is good and readable, the time is here to set up our readText() and convert our text to speech. This is the code:
private void readText()
 {
  String toBeRead = yourText.getText().toString();
  textTS.speak(toBeRead, TextToSpeech.QUEUE_FLUSH, null);
 }
And this is the full code below, notice i added the onDestroy(), this is to turn off TextToSpeech when the app goes off and keep the android life cycle clean.
package com.example.retts;

import java.util.Locale;

import android.app.Activity;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends Activity implements TextToSpeech.OnInitListener{

 //Declare our objects
 TextToSpeech textTS;
 Button speakBtn;
 EditText yourText;
 
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  
  //Initialize our objects
  textTS = new TextToSpeech(this, this);
  speakBtn = (Button)findViewById(R.id.speak_btn);
  yourText = (EditText)findViewById(R.id.your_text);
  
  //Hey when i click this button read my text
  speakBtn.setOnClickListener(new View.OnClickListener()
  {

   @Override
   public void onClick(View v) {
    // TODO Auto-generated method stub
    readText();
   }
   
  });
 }
 //keeping the life cycle clean
 @Override
 protected void onDestroy() {
  // TODO Auto-generated method stub
  super.onDestroy();
  if(textTS != null)
  {
   textTS.stop();
   textTS.shutdown();
  }
 }


 
 @Override
 public boolean onCreateOptionsMenu(Menu menu) {
  // Inflate the menu; this adds items to the action bar if it is present.
  getMenuInflater().inflate(R.menu.main, menu);
  return true;
 }

 @Override
 public void onInit(int status) {
  // TODO Auto-generated method stub
  if(status == TextToSpeech.SUCCESS)
  {
   int result = textTS.setLanguage(Locale.UK);
   textTS.setSpeechRate((float) 0.7);
   //textTS.setPitch(1);
   //Make sure that the data is valid
   //we check if our data if invalid or if the language received is invalid
   if(result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED)
   {
    Log.e("!!ER!!", "What crap are you feeding me");
   }
   //if our data is good we then proceed with our reading process
   else
   {
    speakBtn.setEnabled(true);
    readText();
   }
  }
 }
 
 private void readText()
 {
  String toBeRead = yourText.getText().toString();
  textTS.speak(toBeRead, TextToSpeech.QUEUE_FLUSH, null);
 }

}


Thursday, 23 January 2014

Android Accelerometer vs Windows Accelerometer part 1

Hello guys i will like to show you how to get accelerometer readings from android and windows phone devices, as for this part we will focus on Android devices.
So we will be using a TextView to display the data.
Setup your project and open the activity_main.xml and edit the default Hello world text to:
<TextView
android:id="@+id/display_reading"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>

That is all we need to do to our activity_main.xml
Next we have to create a SensorManager and Sensor variable as follows

Sensor sensor;
//help us manage sensor components
SensorManager sm
TextView displayReading;
We then configure our service and select the type of service we wish to utilize in this case the sensor service, after that we then select a sensor (Accelerometer)
//setup a sensor service
sm = (SensorManager)getSystemService(SENSOR_SERVICE);
//select the sensor we wish to use
sensor = sm.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
	
sm.registerListener(this, sensor, SensorManager.SENSOR_DELAY_NORMAL);
		
displayReading = (TextView)findViewById(R.id.display_reading);
you will notice we implemented a sensor manager listener to sm.registerListener after doing this you will get an error which can be resolved by implementing SensorEventListener. After doing this you will get another error which is resolved by implementing to methods; onSensorChanged() and onAccuracyChanged()

We are all done with setting things up now we have to get our readings, which we implement in the onSensorChanged() method:
@Override
	public void onSensorChanged(SensorEvent event) {
		// TODO Auto-generated method stub
		displayReading.setText("X"+event.values[0]+"\nY"+event.values[1]+"\nZ"+event.values[2]);
		
	}

The Full code
package com.example.accelerometer;

import android.app.Activity;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.Menu;
import android.widget.TextView;

public class MainActivity extends Activity implements SensorEventListener{

	//this class help select a particular sensor
	Sensor sensor;
	//help us manage sensor components
	SensorManager sm;
	
	TextView displayReading;
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		//setup a sensor service
		sm = (SensorManager)getSystemService(SENSOR_SERVICE);
		//select the sensor we wish to use
		sensor = sm.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
		
		sm.registerListener(this, sensor, SensorManager.SENSOR_DELAY_NORMAL);
		
		displayReading = (TextView)findViewById(R.id.display_reading);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@Override
	public void onAccuracyChanged(Sensor arg0, int arg1) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onSensorChanged(SensorEvent event) {
		// TODO Auto-generated method stub
		displayReading.setText("X"+event.values[0]+"\nY"+event.values[1]+"\nZ"+event.values[2]);
		
	}

}


With all that done you can now test "on a real device" since the emulator can not simulate accelerometer behavior, i will get a snapshot of it, thanks.

Saturday, 28 December 2013

GpsPhone

Navigation in Africa is a real drag, most places are not reflected on the map using street view, and lets imagine taking a girl out on a date and you have to make reservations for dinner but need to find a restaurant that serves a particular type of food,  my first tutorial handles this issue on the Windows Phone platform. No longer shall we have the "is this what I ordered" look ever again.
You will learn how to:
Access GPS functionality on your device.
How to attach pushpins to the maps
Implement events on pushpins
And also implement a phone task to call and make reservations.
Tools
Windows Phone SDK
Bing maps API
GPS device
Visual studio 2012 or 2010 (I am using the 2012 version)
Creating the project
Open up visual studio and create a windows phone application
Give it whatever name you want, for mine I will call it GpsPhone
we are given a main page by default and two “TextBlocks” on it
<TextBlock x:Name="ApplicationTitle" Text="Gps Phone" Style="{StaticResource PhoneTextNormalStyle}"/>
 
<TextBlock x:Name="PageTitle" Text="Bing Maps" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>
Setting up Bing Maps
Since we are developing for windows phone devices I believe the best map technology to use would be Bing Maps as both technologies are owned by Microsoft any change made on one end would most likely be implemented on the other.
To use Bing Maps you first need an API key, which is pretty easy to get
Check this link Here to obtain the API key
Bing Maps can be setup in two ways that I know of;
  1. Drag Bing maps from the Toolbox to the MainPage layout.
  2. Add the following code to the top of your MainPage.xaml code within phone tag
xmlns:mp="clr-namespace:Microsoft.Phone.Controls.Maps;assembly=Microsoft.Phone.Controls.Maps"
This calls the maps control libraries which handles navigation features like views and zoom level etc.
Then and this to the body of MainPage.xaml and you should be able to view the map now
&ltmp:Map x:Name=”map” CredentialsProvider=”Your Bing maps Api key goes here” ZoomBarVisibility=”Visible” Margin=”0,0,0,69″ /&gt
You fill the CredentialsProvider with your API key and your map should be up and running.
The map look nice and beautiful, but we need to know where we are.
Getting users location
To achieve this we first have to add the System.Device.Location class to MainPage.xaml.cs, it handles GPS services and allows us developer to achieve many other location services. Add this line at the top of your code.
using System.Device.Location;
also add this line using Microsoft.Phone.Controls.Maps; this class gives us tools that enable us to manipulate the map features like add pushpins and change the view type.
Create the following variable
GeoCoordinateWatcher loc_watcher;
GeoCoordinateWatcher supplies location based on latitude and longitude values.
Next we add the following code the MainPage.xaml.cs constructor
if (loc_watcher == null)
 
{
 
loc_watcher = new GeoCoordinateWatcher(GeoPositionAccuracy.Default);
 
loc_watcher.MovementThreshold = 20;
 
loc_watcher.StatusChanged += new EventHandler&ltGeoPositionStatusChangedEventArgs&gt(watcher_StatusChanged);
 
loc_watcher.PositionChanged += new EventHandler&ltGeoPositionChangedEventArgs&ltGeoCoordinate&gt&gt(watcher_PositionChanged);
 
}
 
loc_watcher.Start();
What the above code does is simple, if we get value from GeoCoordinateWatcher we set the accuracy (in this case DEFAULT) and set the MovementThreshold to 20, this calls the PositionChanged event, we also check for StatusChanged which indicates that GeoCoordinateWatcher object has changed which we will handle with the watcher_StatusChanged method, after that we check if the position has changed with the watcher_PositionChanged method.
void watcher_StatusChanged(object sender, GeoPositionStatusChangedEventArgs e)
 
{
 
switch (e.Status)
 
{
 
case GeoPositionStatus.Disabled:
 
MessageBox.Show(“Location Service is not enabled on the device”);
 
break;
 
case GeoPositionStatus.NoData:
 
MessageBox.Show(” The Location Service is working, but it cannot get location data.”);
 
break;
 
}
 
}
The method checks if location data is being received which could be distorted by turning off locations services in device settings or due to poor network coverage.
Attaching pushpins to locations
The code below attaches pushpins to the users current location with purple colour and I also attached a pushpin to another location which will serve as our restaurant.
void watcher_PositionChanged(object sender, GeoPositionChangedEventArgs e)
 
{
 
if (e.Position.Location.IsUnknown)
 
{
 
MessageBox.Show("Please wait while your position is determined....");
 
return;
 
}
 
this.map.Center = new GeoCoordinate(e.Position.Location.Latitude, e.Position.Location.Longitude);
 
if (this.map.Children.Count != 0)
 
{
 
var pushpin = map.Children.FirstOrDefault(p => (p.GetType() == typeof(Pushpin) && ((Pushpin)p).Tag == "locationPushpin"));
 
if (pushpin != null)
 
{
 
this.map.Children.Remove(pushpin);
 
}
 
}
 
Pushpin locationPushpin = new Pushpin();
 
locationPushpin.Background = new SolidColorBrush(Colors.Purple);
 
locationPushpin.Content = "You are here";
 
locationPushpin.Tag = "locationPushpin";
 
locationPushpin.Location = loc_watcher.Position.Location;
 
this.map.Children.Add(locationPushpin);
 
this.map.SetView(loc_watcher.Position.Location, 10.0);
 
//creating an instance of the pushpin
 
Pushpin hospitalPushpin = new Pushpin();
 
String phoneNo = " phone number goes here ";
 
hospitalPushpin.Content = " Mr. Biii’s Restaurant " + "\n" + phoneNo;
 
//the pushpin is assigned the latitude and longitude ***(latitude, longitude)***
 
hospitalPushpin.MouseLeftButtonUp += new MouseButtonEventHandler(hospitalPushpin_MouseLeftButtonUp);
 
hospitalPushpin.Location = new GeoCoordinate(8.957914, 7.699131);
 
this.map.Children.Add(hospitalPushpin);
 
}
The third line from the bottom calls a method that makes phone call to the restaurant when the pushpin is touched, the method is shown below.
void hospitalPushpin_MouseLeftButtonUp(object sender, MouseButtonEventArgs eve)
 
{
 
try
 
{
 
phoneTask.DisplayName = "Mr. Biii’s Restaurant";
 
phoneTask.PhoneNumber = "phone number goes here";
 
phoneTask.Show();
 
}
 
catch(Exception ev)
 
{
 
MessageBox.Show("Try later "+ev);
 
}
 
}
This method makes a phone call when the pushpin is touched.
Add this code to the constructor
phoneTask = new PhoneCallTask();
add this code to the class body that is outside the constructor.
A there you have it, you call develop it further, like getting pushpin locations from a REST API so as restaurants increase you get update dynamically.
I tested on real device that is why it is getting my real location on the emulator it won't
Download the code off git https://github.com/BarkaBoss/GpsPhoneWP
Screenshots
ImageImage