BarabasiAlbertGenerator implementation - junit

I wanted to implement BarabasiAlbertGenerator to generate graph. After creating all Factory objects in main method and changing the Objects (V, E) to (Integer, String) in the generator class, two errors worried me after making all possible modification.
1. index_vertex.put(v, i); type mismatch
2. index_vertex.put(newVertex, new Integer(vertex_index.size() - 1));// an Object of Integer cannot be instantiated. I made several casting the errors still appear. Please any help on how to correct the errors.
public class BarabasiAlbertGenerator<Integer, String> implements EvolvingGraphGenerator<Integer, String> {
mGraph = graphFactory.create();
vertex_index = new ArrayList<Integer>(2*init_vertices);
index_vertex = new HashMap<Integer, Integer>(2*init_vertices);
for (int i = 0; i < init_vertices; i++) {
Integer v = vertexFactory.create();
mGraph.addVertex(v);
vertex_index.add(v);
index_vertex.put(v, i);
seedVertices.add(v);
}
mElapsedTimeSteps = 0;
}
for (Pair<Integer> pair : added_pairs)
{
Integer v1 = pair.getFirst();
Integer v2 = pair.getSecond();
if (mGraph.getDefaultEdgeType() != EdgeType.UNDIRECTED ||
!mGraph.isNeighbor(v1, v2))
mGraph.addEdge(edgeFactory.create(), pair);
}
// now that we're done attaching edges to this new vertex,
// add it to the index
vertex_index.add(newVertex);
index_vertex.put(newVertex, new Integer(vertex_index.size() - 1));
}
public static void main(String[] args) {
SparseGraph<Integer, String> sir = new SparseGraph<Integer, String>();
ConstantFactory<Graph<Integer, String>> graphFactory = new ConstantFactory<Graph<Integer, String>>(sir);
InstantiateFactory<Integer> vertexFactory = new InstantiateFactory<Integer>(Integer.class);
InstantiateFactory<String> edgeFactory = new InstantiateFactory<String>(String.class);
HashSet<Integer> seedVertices = new HashSet<Integer>();
int evolve = 1;
int node = 10;
int agents = 100;
BarabasiAlbertGenerator<Integer, String> bbr = new BarabasiAlbertGenerator<Integer, String>(graphFactory, vertexFactory, edgeFactory, agents, node, seedVertices);
bbr.evolveGraph(evolve);
Layout<Integer, String> layout = new CircleLayout(sir);
layout.setSize(new Dimension(300,300));
BasicVisualizationServer<Integer,String> vv =
new BasicVisualizationServer<Integer,String>(layout);
vv.setPreferredSize(new Dimension(350,350));
// Setup up a new vertex to paint transformer...
Transformer<Integer,Paint> vertexPaint = new Transformer<Integer,Paint>() {
public Paint transform(Integer i) {
return Color.GREEN;
}
};
// Set up a new stroke Transformer for the edges
float dash[] = {10.0f};
final Stroke edgeStroke = new BasicStroke(1.0f, BasicStroke.CAP_BUTT,
BasicStroke.JOIN_MITER, 10.0f, dash, 0.0f);
Transformer<String, Stroke> edgeStrokeTransformer =
new Transformer<String, Stroke>() {
public Stroke transform(String s) {
return edgeStroke;
}
};
vv.getRenderContext().setVertexFillPaintTransformer(vertexPaint);
vv.getRenderContext().setEdgeStrokeTransformer(edgeStrokeTransformer);
vv.getRenderContext().setVertexLabelTransformer(new ToStringLabeller());
//vv.getRenderContext().setEdgeLabelTransformer(new ToStringLabeller());
vv.getRenderer().getVertexLabelRenderer().setPosition(Position.CNTR);
JFrame frame = new JFrame("Undirected Graph ");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(vv);
frame.pack();
frame.setVisible(true);
}

I don't think you want to use InstantiateFactory.
I was able to run your program after changing it to look like this (mostly the vertex and edge factories):
public static void main(String[] args) {
SparseGraph<Integer, String> sir = new SparseGraph<Integer, String>();
ConstantFactory<Graph<Integer, String>> graphFactory = new ConstantFactory<Graph<Integer, String>>(sir);
Factory<Integer> vertexFactory = new Factory<Integer>() {
int i = 0;
public Integer create() {
return i++;
}
};
Factory<String> edgeFactory = new Factory<String>() {
int i = 0;
public String create() {
return "" + i++;
}
};
HashSet<Integer> seedVertices = new HashSet<Integer>();
int evolve = 1;
int node = 10;
int agents = 100;
BarabasiAlbertGenerator<Integer, String> bbr = new BarabasiAlbertGenerator<Integer, String>(graphFactory, vertexFactory, edgeFactory, agents, node, seedVertices);
bbr.evolveGraph(evolve);
Layout<Integer, String> layout = new CircleLayout(sir);
layout.setSize(new Dimension(300, 300));
BasicVisualizationServer<Integer, String> vv =
new BasicVisualizationServer<Integer, String>(layout);
vv.setPreferredSize(new Dimension(350, 350));
// Setup up a new vertex to paint transformer...
Transformer<Integer, Paint> vertexPaint = new Transformer<Integer, Paint>() {
public Paint transform(Integer i) {
return Color.GREEN;
}
};
// Set up a new stroke Transformer for the edges
float dash[] = {10.0f};
final Stroke edgeStroke = new BasicStroke(1.0f, BasicStroke.CAP_BUTT,
BasicStroke.JOIN_MITER, 10.0f, dash, 0.0f);
Transformer<String, Stroke> edgeStrokeTransformer =
new Transformer<String, Stroke>() {
public Stroke transform(String s) {
return edgeStroke;
}
};
vv.getRenderContext().setVertexFillPaintTransformer(vertexPaint);
vv.getRenderContext().setEdgeStrokeTransformer(edgeStrokeTransformer);
vv.getRenderContext().setVertexLabelTransformer(new ToStringLabeller());
//vv.getRenderContext().setEdgeLabelTransformer(new ToStringLabeller());
vv.getRenderer().getVertexLabelRenderer().setPosition(Renderer.VertexLabel.Position.CNTR);
JFrame frame = new JFrame("Undirected Graph ");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(vv);
frame.pack();
frame.setVisible(true);
}
Make sure your imports are correct. I used these:
import edu.uci.ics.jung.algorithms.generators.random.BarabasiAlbertGenerator;
import edu.uci.ics.jung.algorithms.layout.CircleLayout;
import edu.uci.ics.jung.algorithms.layout.Layout;
import edu.uci.ics.jung.graph.Graph;
import edu.uci.ics.jung.graph.SparseGraph;
import edu.uci.ics.jung.visualization.BasicVisualizationServer;
import edu.uci.ics.jung.visualization.decorators.ToStringLabeller;
import edu.uci.ics.jung.visualization.renderers.Renderer;
import org.apache.commons.collections15.Factory;
import org.apache.commons.collections15.Transformer;
import org.apache.commons.collections15.functors.ConstantFactory;
import javax.swing.*;
import java.awt.*;
import java.util.HashSet;

Related

Convert liste of vector3 to Json [duplicate]

This question already has answers here:
Serialize and Deserialize Json and Json Array in Unity
(9 answers)
Closed 3 years ago.
I'm trying to get all my lines render positions and add it to a list of vector3 then covert it to Json, so I can save it in the firebase. I'm using JsonUtility, but the problem is my jsondata is always empty even the list of vecor3 is not.
This is my code then I'm using :
public class Path : MonoBehaviour
{
[SerializeField] private List<Transform> checkpoints = new List<Transform>();
private LineRenderer linerenderer;
public Material TheLineMateriel;
public static bool _ispressed = false;
private string DATA_URL = "https://kataraproject-a233a.firebaseio.com/";
private DatabaseReference reference;
public string hello = "khraaa" ;
// Start is called before the first frame update
void Start()
{
FirebaseApp.DefaultInstance.SetEditorDatabaseUrl(DATA_URL);
reference = FirebaseDatabase.DefaultInstance.RootReference;
GameObject lineObject = new GameObject();
this.linerenderer = lineObject.AddComponent<LineRenderer>();
this.linerenderer.startWidth = 0.05f;
this.linerenderer.endWidth = 0.05f;
this.linerenderer.positionCount = checkpoints.Count;
this.linerenderer.material = TheLineMateriel;
}
// Update is called once per frame
void Update()
{
this.DrawLine();
}
private void DrawLine()
{
Vector3[] checkpointsArray = new Vector3[this.checkpoints.Count];
for (int i = 0; i < this.checkpoints.Count; i++) {
Vector3 checkpointPos = this.checkpoints[i].position;
checkpointsArray[i] = new Vector3(checkpointPos.x, checkpointPos.y, 0f);
}
Vector3[] newPos = new Vector3[linerenderer.positionCount];
this.linerenderer.SetPositions(checkpointsArray);
linerenderer.GetPositions(newPos);
//for (int i = 0; i < linerenderer.positionCount ; i++)
//{
// newPos[i] = i;
//}
if ( _ispressed == true)
{
string jsonData = JsonUtility.ToJson(checkpointsArray);
//reference.Child("Position" + Random.Range(0,1000000)).SetRawJsonValueAsync(jsonData);
Debug.Log(jsonData);
_ispressed = false;
}
}
public void Save ()
{
_ispressed = true;
}
}
can someone help me please?
You could create a simple class to handle serialization of Unity types like such :
[Serializable]
public class SerializedVector3
{
public float x;
public float y;
public float z;
public SerializedVector3(float x, float y, float z)
{
this.x = x;
this.y = y;
this.z = z;
}
public SerializedVector3(Vector3 vector3)
{
x = vector3.x;
y = vector3.y;
z = vector3.z;
}
}
public static class Vector3Extensions
{
public static Vector3 ToVector3(this SerializedVector3 serializedVector3)
{
return new Vector3(serializedVector3.x, serializedVector3.y, serializedVector3.z);
}
public static SerializedVector3 FromVector3(this Vector3 vector3)
{
return new SerializedVector3(vector3);
}
}

Easy way to write and read some Transform to a text file in Unity3d?

This is strictly in Unity3D, I have an array of 100 Transform,
I want to write those to a file on the PC desktop, and later read them.
Consider ...
// write to desktop...
string s = "";
for ( int i=0; i< sendMe.Length; ++i )
{
Transform tt = sendMe[i].transform;
s = s +tt.position.x +"," +tt.position.x +"," ...etc... "\n";
}
string d = System.Environment.GetFolderPath(
System.Environment.SpecialFolder.DesktopDirectory);
string path = System.IO.Path.Combine(d, "happyData.txt" );
System.IO.File.Delete(path);
System.IO.File.WriteAllText(path,s);
return;
.. and then read it similarly, just manually parsing the text format. Something like...
public ReadTrackFromDesktopFile()
{
GetSplineGetReady("development");
string tt = File.ReadAllText( .. path as above);
List<string> ts = new List<string>(
tt.Split(new string[] { "\r","\n" },
StringSplitOptions.RemoveEmptyEntries) );
foreach (string t in ts)
{
string[] parts = t.Split(',');
Vector3 pos = new Vector3(parts[0],parts[1],parts[2]);
Quaternion rot = new Quaternion(parts[3],parts[4],parts[5],parts[6]);
GetSplineOneNode(pos, rot);
}
GetSplineFinalise();
}
But this seems naive. What's the "simple Unity way" to do this?
You can use Json and the Playerprefs to save the Transform. This is a TransformSaver extension class that can do that:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public static class TransformSaver
{
[System.Serializable]
public class TransformInfo
{
public Vector3 pos;
public Quaternion rot;
public Vector3 scale;
}
//Save Transform
public static void SaveTransform(this Transform trans, Transform[] tranformToSave)
{
TransformInfo[] trnfrm = new TransformInfo[tranformToSave.Length];
for (int i = 0; i < trnfrm.Length; i++)
{
trnfrm[i] = new TransformInfo();
trnfrm[i].pos = tranformToSave[i].position;
trnfrm[i].rot = tranformToSave[i].rotation;
trnfrm[i].scale = tranformToSave[i].localScale;
}
string jsonTransform = JsonHelper.ToJson(trnfrm, true);
PlayerPrefs.SetString("transform", jsonTransform);
}
//Load Transform
public static Transform[] LoadTransform(this Transform trans)
{
string jsonTransform = PlayerPrefs.GetString("transform");
if (jsonTransform == null)
{
return null;
}
//Debug.Log("Loaded: " + jsonTransform);
TransformInfo[] savedTransforms = JsonHelper.FromJson<TransformInfo>(jsonTransform);
GameObject[] gameObjects = new GameObject[savedTransforms.Length];
Transform[] loadedTransforms = new Transform[savedTransforms.Length];
for (int i = 0; i < gameObjects.Length; i++)
{
gameObjects[i] = new GameObject("_");
gameObjects[i].hideFlags = HideFlags.HideAndDontSave;
loadedTransforms[i] = gameObjects[i].transform;
loadedTransforms[i].position = savedTransforms[i].pos;
loadedTransforms[i].rotation = savedTransforms[i].rot;
loadedTransforms[i].localScale = savedTransforms[i].scale;
}
return loadedTransforms;
}
public static void CopyTransform(this Transform trans, Transform source, Transform target, bool createNewInstance = false)
{
if (source == null)
{
return;
}
if (target == null || createNewInstance)
{
GameObject obj = new GameObject("_");
obj.hideFlags = HideFlags.HideAndDontSave;
target = obj.transform;
}
target.position = source.position;
target.rotation = source.rotation;
target.localScale = source.localScale;
}
public static void CopyTransform(this Transform trans, Transform[] source, Transform[] target, bool createNewInstance = false)
{
if (source == null || source.Length <= 0)
{
return;
}
for (int i = 0; i < target.Length; i++)
{
CopyTransform(null, source[i], target[i], createNewInstance);
if (i >= target.Length - 1)
{
break;
}
}
}
}
JsonHelper script for converting arrays to json and vice versa:
using UnityEngine;
using System.Collections;
using System;
public class JsonHelper
{
public static T[] FromJson<T>(string json)
{
Wrapper<T> wrapper = UnityEngine.JsonUtility.FromJson<Wrapper<T>>(json);
return wrapper.Items;
}
public static string ToJson<T>(T[] array, bool prettyPrint)
{
Wrapper<T> wrapper = new Wrapper<T>();
wrapper.Items = array;
return UnityEngine.JsonUtility.ToJson(wrapper, prettyPrint);
}
[Serializable]
private class Wrapper<T>
{
public T[] Items;
}
}
Usage:
using UnityEngine;
using System.Collections;
public class TransformTest : MonoBehaviour
{
public Transform[] objectToSave;
// Use this for initialization
void Start()
{
//Save Transform
transform.SaveTransform(objectToSave);
//Load Transform
Transform[] loadedTransform = transform.LoadTransform();
transform.CopyTransform(loadedTransform, objectToSave);
}
}
It's not perfect and can be improved. Improvement includes making the LoadTransform function take transform array as parameter instead of returning an array.
You can use Binary Serialization.
Create following structs:
[Serializable]
public struct SerializebleVector
{
public float x, y, z, w;
public SerializebleVector(float x, float y, float z, float w = 0f)
{
this.x = x;
this.y = y;
this.z = z;
this.w = w;
}
public static explicit operator SerializebleVector(Quaternion a)
{
return new SerializebleVector(a.x, a.y, a.z, a.w);
}
public static implicit operator SerializebleVector(Vector3 a)
{
return new SerializebleVector(a.x, a.y, a.z);
}
}
[Serializable]
public struct SerializebleTransform
{
SerializebleVector position;
SerializebleVector rotation;
SerializebleVector scale;
public SerializebleTransform(Transform tr)
{
position = tr.position;
rotation = (SerializebleVector) tr.rotation;
scale = tr.lossyScale;
}
public static implicit operator SerializebleTransform(Transform tr)
{
return new SerializebleTransform(tr);
}
}
Save method:
public static void Save(Transform[] ts )
{
var data = new List<SerializebleTransform>();
foreach (var t in ts)
{
data.Add(t);
}
BinaryFormatter bf = new BinaryFormatter();
using (FileStream file = File.Create (Application.persistentDataPath + "/savedTransforms.dat"))
{
bf.Serialize(file, data);
}
}
Load Method:
public static void Load(out List<SerializebleTransform> ts)
{
if(File.Exists(Application.persistentDataPath + "/savedTransforms.dat"))
{
BinaryFormatter bf = new BinaryFormatter();
using (FileStream file = File.Open(Application.persistentDataPath + "/savedTransforms.dat", FileMode.Open))
{
var data = (List<SerializebleTransform>)bf.Deserialize(file);
return data;
}
}
else
ts = null;
}
PS: As far as I know you can't create Transform without GameObject, so read data from SerializebleTransform into Transform kind of manually.

GoogleMaps displaying "locals" on wrong position

i want to display the CurrentPosition of the mobile phone and display all bar|cafe nearby the position.
The CurrentPosition works.
But the displaying of the bars/cafes is wrong. It seems like they are showing up from the center of vienna and not from the position of my phone.
Would be really thankful if someone could find the problem
MapsActivity.java
package androfenix.currentpositionandplacesnearby;
import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.AsyncTask;
import android.os.Build;
import android.support.v4.app.ActivityCompat;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class MapsActivity extends AppCompatActivity implements OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener {
private GoogleMap mMap;
GoogleApiClient mGoogleApiClient;
Location mLastLocation;
Marker mCurrLocationMarker;
LocationRequest mLocationRequest;
LatLng latLng;
double mLatitude=0;
double mLongitude=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
checkLocationPermission();
}
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
//Mit setMapType setzen wir das Aussehen der Karte auf "Hybrid"
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
//Initialize Google Play Services
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
}
else {
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
}
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mGoogleApiClient.connect();
}
#Override
public void onPause()
{
super.onPause();
//Unregister for location callbacks:
if (mGoogleApiClient != null)
{
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
}
#Override
public void onConnected(Bundle bundle) {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(1000);
mLocationRequest.setFastestInterval(1000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onLocationChanged(Location location) {
mLastLocation = location;
if (mCurrLocationMarker != null) {
mCurrLocationMarker.remove();
}
// Create a LatLng object for the current location
latLng = new LatLng(location.getLatitude(), location.getLongitude());
mLatitude = location.getLatitude();
mLongitude = location.getLongitude();
//Place current location marker
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title("Current Position");
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
mCurrLocationMarker = mMap.addMarker(markerOptions);
//move map camera
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(11));
//stop location updates
if (mGoogleApiClient != null) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
StringBuilder sbValue = new StringBuilder(sbMethod());
PlacesTask placesTask = new PlacesTask();
placesTask.execute(sbValue.toString());
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
public boolean checkLocationPermission(){
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
// Asking user if explanation is needed
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.ACCESS_FINE_LOCATION)) {
// Show an explanation to the user *asynchronously* -- don't block
// this thread waiting for the user's response! After the user
// sees the explanation, try again to request the permission.
//Prompt the user once explanation has been shown
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
}
return false;
} else {
return true;
}
}
#Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_LOCATION: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted. Do the
// contacts-related task you need to do.
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
if (mGoogleApiClient == null) {
buildGoogleApiClient();
}
mMap.setMyLocationEnabled(true);
}
} else {
// Permission denied, Disable the functionality that depends on this permission.
Toast.makeText(this, "permission denied", Toast.LENGTH_LONG).show();
}
return;
}
// other 'case' lines to check for other permissions this app might request.
// You can add here other case statements according to your requirement.
}
}
public StringBuilder sbMethod() throws SecurityException
{
StringBuilder sb = new StringBuilder("https://maps.googleapis.com/maps/api/place/nearbysearch/json?");
sb.append("location=" + mLatitude + "," + mLongitude);
sb.append("&radius=50000");
sb.append("&sensor=true");
sb.append("&keyword=" + "bar|cafe");
sb.append("&key= SERVER API KEY ");
Log.d("Map", "url: " + sb.toString());
return sb;
}
private class PlacesTask extends AsyncTask<String, Integer, String>
{
String data = null;
// Invoked by execute() method of this object
#Override
protected String doInBackground(String... url) {
try {
data = downloadUrl(url[0]);
} catch (Exception e) {
Log.d("Background Task", e.toString());
}
return data;
}
// Executed after the complete execution of doInBackground() method
#Override
protected void onPostExecute(String result) {
ParserTask parserTask = new ParserTask();
// Start parsing the Google places in JSON format
// Invokes the "doInBackground()" method of the class ParserTask
parserTask.execute(result);
}
}
private String downloadUrl(String strUrl) throws IOException
{
String data = "";
InputStream iStream = null;
HttpURLConnection urlConnection = null;
try {
URL url = new URL(strUrl);
// Creating an http connection to communicate with url
urlConnection = (HttpURLConnection) url.openConnection();
// Connecting to url
urlConnection.connect();
// Reading data from url
iStream = urlConnection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(iStream));
StringBuffer sb = new StringBuffer();
String line = "";
while ((line = br.readLine()) != null) {
sb.append(line);
}
data = sb.toString();
br.close();
} catch (Exception e) {
Log.d("Exception", e.toString());
} finally {
iStream.close();
urlConnection.disconnect();
}
return data;
}
private class ParserTask extends AsyncTask<String, Integer, List<HashMap<String, String>>> {
JSONObject jObject;
// Invoked by execute() method of this object
#Override
protected List<HashMap<String, String>> doInBackground(String... jsonData) {
List<HashMap<String, String>> places = null;
Place_JSON placeJson = new Place_JSON();
try {
jObject = new JSONObject(jsonData[0]);
places = placeJson.parse(jObject);
} catch (Exception e) {
Log.d("Exception", e.toString());
}
return places;
}
// Executed after the complete execution of doInBackground() method
#Override
protected void onPostExecute(List<HashMap<String, String>> list) {
Log.d("Map", "list size: " + list.size());
// Clears all the existing markers;
//mGoogleMap.clear();
for (int i = 0; i < list.size(); i++) {
// Creating a marker
MarkerOptions markerOptions = new MarkerOptions();
// Getting a place from the places list
HashMap<String, String> hmPlace = list.get(i);
// Getting latitude of the place
double lat = Double.parseDouble(hmPlace.get("lat"));
// Getting longitude of the place
double lng = Double.parseDouble(hmPlace.get("lng"));
// Getting name
String name = hmPlace.get("place_name");
Log.d("Map", "place: " + name);
// Getting vicinity
String vicinity = hmPlace.get("vicinity");
latLng = new LatLng(lat, lng);
// Setting the position for the marker
markerOptions.position(latLng);
markerOptions.title(name + " : " + vicinity);
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
// Placing a marker on the touched position
Marker m = mMap.addMarker(markerOptions);
// ZZZZZZZZZZZZZZZZZZZ
}
}
}
public class Place_JSON {
/**
* Receives a JSONObject and returns a list
*/
public List<HashMap<String, String>> parse(JSONObject jObject) {
JSONArray jPlaces = null;
try {
/** Retrieves all the elements in the 'places' array */
jPlaces = jObject.getJSONArray("results");
} catch (JSONException e) {
e.printStackTrace();
}
/** Invoking getPlaces with the array of json object
* where each json object represent a place
*/
return getPlaces(jPlaces);
}
private List<HashMap<String, String>> getPlaces(JSONArray jPlaces) {
int placesCount = jPlaces.length();
List<HashMap<String, String>> placesList = new ArrayList<HashMap<String, String>>();
HashMap<String, String> place = null;
/** Taking each place, parses and adds to list object */
for (int i = 0; i < placesCount; i++) {
try {
/** Call getPlace with place JSON object to parse the place */
place = getPlace((JSONObject) jPlaces.get(i));
placesList.add(place);
} catch (JSONException e) {
e.printStackTrace();
}
}
return placesList;
}
/**
* Parsing the Place JSON object
*/
private HashMap<String, String> getPlace(JSONObject jPlace)
{
HashMap<String, String> place = new HashMap<String, String>();
String placeName = "-NA-";
String vicinity = "-NA-";
String latitude = "";
String longitude = "";
String reference = "";
try {
// Extracting Place name, if available
if (!jPlace.isNull("name")) {
placeName = jPlace.getString("name");
}
// Extracting Place Vicinity, if available
if (!jPlace.isNull("vicinity")) {
vicinity = jPlace.getString("vicinity");
}
latitude = jPlace.getJSONObject("geometry").getJSONObject("location").getString("lat");
longitude = jPlace.getJSONObject("geometry").getJSONObject("location").getString("lng");
reference = jPlace.getString("reference");
place.put("place_name", placeName);
place.put("vicinity", vicinity);
place.put("lat", latitude);
place.put("lng", longitude);
place.put("reference", reference);
} catch (JSONException e) {
e.printStackTrace();
}
return place;
}
}
}
Using the Google Places API for Android, you can discover the place where the device is currently located. That is, the place at the device's currently-reported location. Examples of places include local businesses, points of interest, and geographic locations.
If your app uses PlaceDetectionApi.getCurrentPlace() must request the ACCESS_FINE_LOCATION permission.
The following code sample retrieves the list of places where the device is most likely to be located, and logs the name and likelihood for each place.
PendingResult<PlaceLikelihoodBuffer> result = Places.PlaceDetectionApi
.getCurrentPlace(mGoogleApiClient, null);
result.setResultCallback(new ResultCallback<PlaceLikelihoodBuffer>() {
#Override
public void onResult(PlaceLikelihoodBuffer likelyPlaces) {
for (PlaceLikelihood placeLikelihood : likelyPlaces) {
Log.i(TAG, String.format("Place '%s' has likelihood: %g",
placeLikelihood.getPlace().getName(),
placeLikelihood.getLikelihood()));
}
likelyPlaces.release();
}
});
The PlacePicker provides a UI dialog that displays an interactive map and a list of nearby places, including places corresponding to geographical addresses and local businesses. Users can choose a place, and your app can then retrieve the details of the selected place.
The following code snippet retrieves the place that the user has selected:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == PLACE_PICKER_REQUEST) {
if (resultCode == RESULT_OK) {
Place place = PlacePicker.getPlace(data, this);
String toastMsg = String.format("Place: %s", place.getName());
Toast.makeText(this, toastMsg, Toast.LENGTH_LONG).show();
}
}
}

WebClient event firing order

I'm new to WP7 app development and I'm having trouble passing parameters to an API on a website.
It's my understanding that the onNavigatedTo() is fired first when a page is open on the WP7, however when I try to grab the parameters the webClient_DownloadStringCompleted() is fired first.
public partial class Ranks : PhoneApplicationPage
{
private WebClient webClient;
private string pageType;
private string pagePosition;
public Ranks()
{
InitializeComponent();
this.webClient = new WebClient();
string header_auth = "application/json";
this.webClient.DownloadStringCompleted += new DownloadStringCompletedEventHandler(webClient_DownloadStringCompleted);
this.webClient.Headers[HttpRequestHeader.Authorization] = header_auth;
Uri serviceUri = new Uri(#"http://www.example.com/api/API.php?type=" + pageType + "&position=" + pagePosition);
this.webClient.DownloadStringAsync(serviceUri);
}
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
string type, position;
if (NavigationContext.QueryString.TryGetValue("type", out type))
{
pageType = type;
}
if (NavigationContext.QueryString.TryGetValue("pos", out position))
{
pagePosition = position;
}
}
void webClient_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
string myJsonString = e.Result;
List<PlayerDetails> dataSource = new List<PlayerDetails>();
//load into memory stream
using (var ms = new MemoryStream(Encoding.Unicode.GetBytes(myJsonString)))
{
//parse into jsonser
var ser = new DataContractJsonSerializer(typeof(PlayerDetails[]));
PlayerDetails[] obj = (PlayerDetails[])ser.ReadObject(ms);
foreach (PlayerDetails plyr in obj)
{
dataSource.Add(plyr);
}
playerList.ItemsSource = dataSource;
}
}
Whenever the URI string is built it's missing the parameters 'pageType' and 'pagePosition'
Any help would be greatly appreciated!
The class constructor will always get called before OnNavigatedTo. you should move that code from the constructor, and into OnNavigatedTo (or Loaded).
I'm guessing that you have that code in the constructor because you only want it to happen once per page load (i.e. not when the user navigates Back onto the page). If that's the case, you can check the NavigationMode.
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
if (e.NavigationMode == NavigationMode.New)
{
string type, position;
if (NavigationContext.QueryString.TryGetValue("type", out type))
{
pageType = type;
}
if (NavigationContext.QueryString.TryGetValue("pos", out position))
{
pagePosition = position;
}
this.webClient = new WebClient();
string header_auth = "application/json";
this.webClient.DownloadStringCompleted += new DownloadStringCompletedEventHandler(webClient_DownloadStringCompleted);
this.webClient.Headers[HttpRequestHeader.Authorization] = header_auth;
Uri serviceUri = new Uri(#"http://www.example.com/api/API.php?type=" + pageType + "&position=" + pagePosition);
this.webClient.DownloadStringAsync(serviceUri);
}
}

Java Reflection Problem

Hi I am currently doing my final year project; I need to develop an algorithm visualization tool. I need to cater for user-defined algo; that is animate the algorithm the user types in a text-editor provided in my tool.
I am using the Java Compiler API to compile the code that the user has typed and saved. My tool offers a set of classes that the user can use in his/her algo.
For example:
myArray(this class is provided by my tool)
import java.awt.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.accessibility.AccessibleContext;
import javax.swing.*;
public class myArray extends JComponent {
int size = 0;
int count = 0;
int[]hold;
Thread th;
public myArray(int[]arr)//pass user array as parameter
{
//th = new Thread();
size=arr.length;
hold = arr;//make a copy of the array so as to use later in swap operation
}
public int length()
{
return hold.length;
}
public void setAccessibleContext(AccessibleContext accessibleContext) {
this.accessibleContext = accessibleContext;
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
this.setPreferredSize(new Dimension(360,100));
for(int i=1; i<=size; i++)
{
g2d.drawRect((i*30), 30, 30, 50);
}
for(int i=1; i<=size; i++)
{
g2d.drawString(Integer.toString(hold[i-1]), (i*30)+15, 30+25);
}
}
public void set(int i, int j)//position of the two elements to swap in the array
{
try {
th.sleep(2000);//sleep before swapping because else user won't see original array since it would swap and then sleep
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
int temp = hold[i];
hold[i] = hold[j];
hold[j] = temp;
hold[i]=j;
this.repaint();//can use eapint with a class that extends JPanel
}
public void swap(int i, int j)//position of the two elements to swap in the array
{
try {
th.sleep(2000);//sleep before swapping because else user won't see original array since it would swap and then sleep
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
int temp = hold[i];
hold[i] = hold[j];
hold[j] = temp;
this.repaint();//can use eapint with a class that extends JPanel
}
public int get(int pos)
{
return hold[pos];
}
}
This is a portion of my GUI that will cause the compilation:
JavaCompiler jc = null;
StandardJavaFileManager sjfm = null;
File javaFile = null;
String[] options = null;
File outputDir = null;
URL[] urls = null;
URLClassLoader ucl = null;
Class clazz = null;
Method method = null;
Object object = null;
try
{
jc = ToolProvider.getSystemJavaCompiler();
sjfm = jc.getStandardFileManager(null, null, null);
File[] files = new File[1];
//files[0] = new File("C:/Users/user/Documents/NetBeansProjects/My_Final_Year_Project/myArray.java");
//files[1] = new File("C:/Users/user/Documents/NetBeansProjects/My_Final_Year_Project/Tool.java");
files[0] = new File("C:/Users/user/Documents/NetBeansProjects/My_Final_Year_Project/userDefined.java");
// getJavaFileObjects’ param is a vararg
Iterable fileObjects = sjfm.getJavaFileObjects(files);
jc.getTask(null, sjfm, null, null, null, fileObjects).call();
// Add more compilation tasks
sjfm.close();
options = new String[]{"-d", "C:/Users/user/Documents/NetBeansProjects/My_Final_Year_Project"};
jc.getTask(null, sjfm, null, Arrays.asList(options), null, fileObjects).call();
outputDir = new File("C:/Users/user/Documents/NetBeansProjects/My_Final_Year_Project");
urls = new URL[]{outputDir.toURL()};
ucl = new URLClassLoader(urls);
clazz = ucl.loadClass("userDefined");
method = clazz.getMethod("user", null);
object = clazz.newInstance();
Object ob = method.invoke(object, null);
}
This is an example of a user-defined algo(userDefined.java):
import java.awt.*;
import javax.swing.*;
public class userDefined
{
public void user()
{
int [] numArr = {1,3,1,-1,5,-5,0,7,12,-36};
myArray myArray = new myArray(numArr);
JFrame frame = new JFrame("Rectangles");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setSize(360, 300);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
frame.add(myArray);
for (int i=myArray.length(); i>1; i--)
{
for (int j=0; j<i-1; j++)
{
if (myArray.get(j) > myArray.get(j+1))
{
myArray.swap(j, j+1);
}
}
}
}
}
The problem I am getting is that if I try to use reflection like above; I only get a white window which does not show the animation) but just displays the result at the very end.
However if I use this instead of reflection(and change the method void user() to static void main(string args) in userDefined.java):
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
if(compiler.run(null, null, null, "userDefined.java") != 0) {
System.err.println("Could not compile.");
System.exit(0);
}
try {
Runtime rt = Runtime.getRuntime();
Process pr = rt.exec("java "+"userDefined");
BufferedReader input = new BufferedReader(new InputStreamReader(pr.getInputStream()));
String line=null;
while((line=input.readLine()) != null) {
System.out.println(line);
}
} catch(Exception e) {
System.out.println(e.toString());
e.printStackTrace();
it woks provided that after first compilation I place the myArray class in the same folder as the userDefined.java. In this case I can see the animation take place correctly.
How do I use reflection to invoke the main method instead of using an instance of the class.
Please I really need some help with this. Thanks!
You a violating / missusing the first rule of swing: acces swing components only in the EDT (Event Dispatch Thread).
When you start your program using the main method, you are violating that rule. This happens to work, but might have all kinds of weird effects. This is not a theoretic warning, it happend to me and it is not nice.
When you run it using reflection from your code, you are most likely in the EDT, so your algorithm runs completely before the GUI gets updated again (which also happens on the EDT). Thats why you see only the final result of the algorithm.
The correct way to do this would be:
Run the algorithm in a seperate thread and make sure all changes to your myArray Component happen in the EDT, using SwingUtilities.invokeAndWait or SwingUtilities.invokeLater