Android Fragment activity shown fullscreen - android-activity

I have a question regarding a fragment layout of an OSM Map. I'd like to display the fragment within the activity in full screen modus.
However, the map is only shown on two thirds of the screen.
How can this be achieved?
Can this be done only be editing the .xml file or do I need to make any changes at the manifest or main activity as well?
Here the .xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical" >
<fragment
android:id="#+id/map"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="8.01" >
</fragment>
</LinearLayout>
Here is the MapFragment.java file:
package com.example.uadclient;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Patter
import org.osmdroid.DefaultResourceProxyImpl;
import org.osmdroid.ResourceProxy;
import org.osmdroid.bonuspack.overlays.ExtendedOverlayItem;
import org.osmdroid.bonuspack.overlays.ItemizedOverlayWithBubble;
import org.osmdroid.bonuspack.overlays.Polyline;
import org.osmdroid.bonuspack.routing.Road;
import org.osmdroid.bonuspack.routing.RoadManager;
import org.osmdroid.bonuspack.routing.RoadNode;
import org.osmdroid.tileprovider.tilesource.TileSourceFactory;
import org.osmdroid.util.GeoPoint;
import org.osmdroid.views.MapController;
import org.osmdroid.views.MapView;
import org.osmdroid.views.overlay.ItemizedIconOverlay;
import org.osmdroid.views.overlay.Overlay;
import org.osmdroid.views.overlay.OverlayItem;
import org.osmdroid.views.overlay.PathOverlay;
import android.app.Fragment;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import com.example.uadclient.R;
public class MapFragment extends Fragment {
private MapController mMapController;
private MapView mMapView;
private ItemizedIconOverlay<OverlayItem> myLocationOverlay;
protected ItemizedOverlayWithBubble<ExtendedOverlayItem> roadNodes;
protected PathOverlay roadOverlay;
FileInputStream fis = null;
private ResourceProxy mResourceProxy;
private LocationManager mLocMgr;
String s = "";
String s1 = "";
String s2 = "";
String lon = "";
String lat = "";
int mIncr = 10000;
int counter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
mResourceProxy = new DefaultResourceProxyImpl(inflater.getContext().getApplicationContext());
mMapView = new MapView(inflater.getContext(), 256, mResourceProxy);
//read GPS data from file
readfromFile();
readfromFile2();
readfromFile();
String str1;
str1 = s1.toString();
readfromFile2();
String str2;
str2 = s2.toString();
try {
countLines();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
lon = str1;
lat = str2;
while (counter > 0){ //Anzahl Zeilen -> Anzahl der Punkte
double var_lon = Double.parseDouble(lon);
double var_lat = Double.parseDouble(lat);
View v = inflater.inflate(R.layout.meetfragment, null);
mMapView = (MapView) v.findViewById(R.id.mapview);
mMapView.setTileSource(TileSourceFactory.MAPNIK);
mMapView.setBuiltInZoomControls(true);
mMapView.setMultiTouchControls(true);
mMapController = mMapView.getController();
mMapController.setZoom(13);
GeoPoint point1 = new GeoPoint(var_lat, var_lon);
GeoPoint point2 = new GeoPoint(52.120310618246236, 9.905589604799236); // centre map
GeoPoint point3 = new GeoPoint(52.11712212336459, 9.899281049195961);
mMapController.setCenter(point1);
//mMapController.setCenter(point3);
ArrayList<OverlayItem> items = new ArrayList<OverlayItem>(3);
// Put overlay icon on the centre
items.add(new OverlayItem("Here", "SampleDescription", point1));
/* items.add(new OverlayItem("Here", "SampleDescription", point2));
items.add(new OverlayItem("Here", "SampleDescription", point3));*/
ArrayList<GeoPoint> waypoints = new ArrayList<GeoPoint>(3);
waypoints.add(point1);
waypoints.add(point2);
waypoints.add(point3);
// new UpdateRoadTask().execute(waypoints);
if (savedInstanceState == null){
//Test road service at first launch:
getRoadAsync(point1, point2);
} else {
Road mRoad = null;
updateUIWithRoad(mRoad);
}
this.myLocationOverlay = new ItemizedIconOverlay<OverlayItem>(items,
new ItemizedIconOverlay.OnItemGestureListener<OverlayItem>() {
#Override
public boolean onItemSingleTapUp(final int index,
final OverlayItem item) {
return true;
}
#Override
public boolean onItemLongPress(final int index,
final OverlayItem item) {
return false;
}
}, mResourceProxy);
this.mMapView.getOverlays().add(this.myLocationOverlay);
counter--;
return v;
}
return container;}
public void getRoadAsync(GeoPoint start, GeoPoint destination){
ArrayList<GeoPoint> waypoints = new ArrayList<GeoPoint>(2);
waypoints.add(start);
//intermediate waypoints can be added here:
//waypoints.add(new GeoPoint(48.226, -1.9456));
waypoints.add(destination);
new UpdateRoadTask().execute(waypoints);
}
void updateUIWithRoad(Road road){
List<Overlay> mapOverlays = mMapView.getOverlays();
if (roadOverlay != null){
mapOverlays.remove(roadOverlay);
}
if (road.mStatus == Road.STATUS_DEFAULT)
Toast.makeText(mMapView.getContext(), "We have a problem to get the route", Toast.LENGTH_SHORT).show();
roadOverlay = RoadManager.buildRoadOverlay(road, mMapView.getContext());
Overlay removedOverlay = mapOverlays.set(1, roadOverlay);
//we set the road overlay at the "bottom", just above the MapEventsOverlay,
//to avoid covering the other overlays.
mapOverlays.add(removedOverlay);
putRoadNodes(road);
mMapView.invalidate();
}
private void putRoadNodes(Road road){
roadNodes.removeAllItems();
Drawable marker = getResources().getDrawable(R.drawable.marker_node);
int n = road.mNodes.size();
TypedArray iconIds = getResources().obtainTypedArray(R.array.direction_icons);
for (int i=0; i<n; i++){
RoadNode node = road.mNodes.get(i);
String instructions = (node.mInstructions==null ? "" : node.mInstructions);
ExtendedOverlayItem nodeMarker = new ExtendedOverlayItem(
"Step " + (i+1), instructions,
node.mLocation, this);
nodeMarker.setSubDescription(road.getLengthDurationText(node.mLength, node.mDuration));
nodeMarker.setMarkerHotspot(OverlayItem.HotspotPlace.CENTER);
nodeMarker.setMarker(marker);
int iconId = iconIds.getResourceId(node.mManeuverType, R.drawable.ic_empty);
if (iconId != R.drawable.ic_empty){
Drawable icon = getResources().getDrawable(iconId);
nodeMarker.setImage(icon);
}
roadNodes.addItem(nodeMarker);
}
}
/**
* Async task to get the road in a separate thread.
*/
private class UpdateRoadTask extends AsyncTask<Object, Void, Road> {
protected Road doInBackground(Object... params) {
#SuppressWarnings("unchecked")
ArrayList<GeoPoint> waypoints = (ArrayList<GeoPoint>)params[0];
//RoadManager roadManager = new GoogleRoadManager();
RoadManager roadManager = new OSRMRoadManager();
/*
RoadManager roadManager = new MapQuestRoadManager();
Locale locale = Locale.getDefault();
roadManager.addRequestOption("locale="+locale.getLanguage()+"_"+locale.getCountry());
*/
return roadManager.getRoad(waypoints);
}
private void putRoadNodes(Road road){
ItemizedOverlayWithBubble<ExtendedOverlayItem> roadNodes = null;
roadNodes.removeAllItems();
Drawable marker = getResources().getDrawable(R.drawable.marker_node);
int n = road.mNodes.size();
TypedArray iconIds = getResources().obtainTypedArray(R.array.direction_icons);
for (int i=0; i<n; i++){
RoadNode node = road.mNodes.get(i);
String instructions = (node.mInstructions==null ? "" : node.mInstructions);
ExtendedOverlayItem nodeMarker = new ExtendedOverlayItem(
"Step " + (i+1), instructions,
node.mLocation, this);
nodeMarker.setSubDescription(road.getLengthDurationText(node.mLength, node.mDuration));
nodeMarker.setMarkerHotspot(OverlayItem.HotspotPlace.CENTER);
nodeMarker.setMarker(marker);
int iconId = iconIds.getResourceId(node.mManeuverType, R.drawable.ic_empty);
if (iconId != R.drawable.ic_empty){
Drawable icon = getResources().getDrawable(iconId);
nodeMarker.setImage(icon);
}
roadNodes.addItem(nodeMarker);
}
}
}
public void onFinish(Bundle savedInstanceState) {
super.getActivity().finish();
}
public void onDestroy() {
super.onDestroy();
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
public int countLines() throws IOException {
File file = new File(Environment.getExternalStorageDirectory().getPath()+"/GPSdata.txt");
InputStream is = new BufferedInputStream(new FileInputStream(file));
try {
byte[] c = new byte[1024];
int readChars = 0;
boolean empty = true;
while ((readChars = is.read(c)) != -1) {
empty = false;
for (int i = 0; i < readChars; ++i) {
if (c[i] == '\n') {
++counter;
}
}
}
return (counter == 0 && !empty) ? 1 : counter;
} finally {
is.close();
}
}
public String readfromFile() {
// Read from file
BufferedReader bufferedReader = null;
// Pattern being checked for lattidude
Pattern p1 = Pattern.compile("[0-9]{1}.[0-9]+");
Matcher m;
// Der Pfad zur Textdatei
File file = new File(Environment.getExternalStorageDirectory()
.getPath() + "/GPSdata.txt");
try {
// Der BufferedReader erwartet einen FileReader.
// Diesen kann man im Konstruktoraufruf erzeugen.
bufferedReader = new BufferedReader(new FileReader(file));
String line;
String str = null;
// null wird bei EOF oder Fehler zurueckgegeben
while ((line = bufferedReader.readLine()) != null) {
// Zeile auf der Konsole ausgeben
// Pattern currently being checked for
m = p1.matcher(line);
if (m.find()) {
str = m.group();
// arrayList1.add(str);
}
System.out.println(line);
s1 = str;
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (null != bufferedReader) {
try {
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return s1;
}
public String readfromFile2() {
// Read from file
BufferedReader bufferedReader = null;
// Pattern being checked for longitude
Pattern p = Pattern.compile("[0-9]+.[0-9]+");
Matcher m;
// Der Pfad zur Textdatei
File file = new File(Environment.getExternalStorageDirectory()
.getPath() + "/GPSdata.txt");
try {
// Der BufferedReader erwartet einen FileReader.
// Diesen kann man im Konstruktoraufruf erzeugen.
bufferedReader = new BufferedReader(new FileReader(file));
String line;
String str1 = null;
// null wird bei EOF oder Fehler zurueckgegeben
while ((line = bufferedReader.readLine()) != null) {
// Zeile auf der Konsole ausgeben
// Pattern currently being checked for
m = p.matcher(line);
while (m.find()) {
str1 = m.group();
//arrayList2.add(str1);
}
System.out.println(line);
s2 = str1;
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (null != bufferedReader) {
try {
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return s2;
}
/*public void readLine(){
try {
BufferedReader in = new BufferedReader(new FileReader("GPSdata.txt"));
String zeile = null;
while ((zeile = in.readLine()) != null){
System.out.println("Gelesene Zeile:" + zeile);
}
} catch (IOException ex) {
ex.printStackTrace();
}
}*/
}
and here is the mainfest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.uadclient"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="14"
android:targetSdkVersion="14" />
<permission
android:name="in.wptrafficanalyzer.LocationGoogleMapV2Demo.permission.MAPS_RECEIVE"
android:protectionLevel="signature"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.INTERACT_ACROSS_USERS_FULL"/>
<uses-permission android:name="android.permission.SET_DEBUG_APP"></uses-permission>
<uses-feature
android:glEsVersion="0x00020000"
android:required="true"/>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.bosch.uadclient.MainMenuActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name="com.bosch.uadclient.LocationProviderService" >
</service>
</application>
</manifest>
Best Wishes

Related

how to send location in android device to server (php) automaticlly

I have to send location(latitude & longitude) from android device to server (php) automatically (every 2 min)
and for this work I am using JobSchedulerCompat for service to send location.
But after this send locations to the server only after the application run, I want to send locations to the server continuously.
How can I achieve that?
Here is my code so far:
GpsTracker.java
public class GPSTracker extends Service {
private final Context mContext;
boolean isGPSEnabled = false;
boolean isNetworkEnabled = false;
boolean canGetLocation = false;
Location location; // location
double latitude; // latitude
double longitude; // longitude
// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters
// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute
// Declaring a Location Manager
protected LocationManager locationManager;
public GPSTracker(Context context) {
this.mContext = context;
getLocation();
}
LocationListener locationListenerNetwork = new LocationListener() {
public void onLocationChanged(Location location) {
}
public void onProviderDisabled(String provider) {}
public void onProviderEnabled(String provider) {}
public void onStatusChanged(String provider, int status, Bundle extras) {}
};
LocationListener locationListenerGps = new LocationListener() {
public void onLocationChanged(Location location) {
}
public void onProviderDisabled(String provider) {}
public void onProviderEnabled(String provider) {}
public void onStatusChanged(String provider, int status, Bundle extras) {}
};
public Location getLocation() {
try {
locationManager = (LocationManager) mContext
.getSystemService(LOCATION_SERVICE);
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
try {
isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
}catch (Exception ex){
ex.printStackTrace();
}
if (!isGPSEnabled && !isNetworkEnabled) {
// no network provider is enabled
} else {
this.canGetLocation = true;
if (isNetworkEnabled) {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, locationListenerNetwork);
Toast.makeText(mContext,"Network Enabled",Toast.LENGTH_SHORT).show();
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
if (isGPSEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, locationListenerGps);
//Log.d("GPS Enabled", "GPS Enabled");
Toast.makeText(mContext,"GPS Enabled",Toast.LENGTH_SHORT).show();
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return location;
}
public void stopUsingGPS(){
if(locationManager != null){
locationManager.removeUpdates(locationListenerGps);
}
}
public double getLatitude(){
if(location != null){
latitude = location.getLatitude();
}
return latitude;
}
public double getLongitude(){
if(location != null){
longitude = location.getLongitude();
}
return longitude;
}
public boolean canGetLocation() {
return this.canGetLocation;
}
#Override
public IBinder onBind(Intent arg0) {
return null;
}
}
MyService.java
public class MyService extends JobService{
String code;
#Override
public boolean onStartJob(JobParameters params) {
code=readsavefile(getApplicationContext(),"Code2","Error");
//Toast.makeText(getApplicationContext(),code,Toast.LENGTH_SHORT).show();
new SendLocation(this,params,getApplicationContext()).execute(code);
//Toast.makeText(getApplicationContext(),"Start",Toast.LENGTH_SHORT).show();
//jobFinished(params, false);
return true;
}
public static String readsavefile(Context context,String pname,String dvalue){
SharedPreferences shared=context.getSharedPreferences("GetCodeService", Context.MODE_PRIVATE);
return shared.getString(pname,dvalue);
}
#Override
public boolean onStopJob(JobParameters params) {
return false;
}
private static class SendLocation extends AsyncTask<String, Void, String> {
MyService myService;
JobParameters jobParameters;
Context _context;
GPSTracker gps;
double lat,lon;
public SendLocation(MyService myService,JobParameters jobParameters,Context context){
this._context=context;
gps=new GPSTracker(context);
if (gps.canGetLocation){
lat=gps.getLatitude();
lon=gps.getLongitude();
}
this.myService=myService;
this.jobParameters=jobParameters;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... strings) {
String link = Config.IP_Config + "Hatef/getlocation.php";
HttpClient httpclint = new DefaultHttpClient();
HttpPost httppost = new HttpPost(link);
try {
JSONObject jsonobj = new JSONObject();
jsonobj.put("latitude", lat+"");
jsonobj.put("longitude", lon+"");
jsonobj.put("code", strings[0]);
List<NameValuePair> namevaluepair = new ArrayList<NameValuePair>();
namevaluepair.add(new BasicNameValuePair("req", jsonobj.toString()));
httppost.setEntity(new UrlEncodedFormEntity(namevaluepair, HTTP.UTF_8));
HttpResponse response = httpclint.execute(httppost);
InputStream inputstream = response.getEntity().getContent();
BufferedReader br = null;
StringBuilder sb = new StringBuilder();
String line;
try {
br = new BufferedReader(new InputStreamReader(inputstream));
while ((line = br.readLine()) != null) {
sb.append(line);
}
} catch (Exception ex) {
ex.printStackTrace();
}
return sb.toString();
} catch (Exception ex) {
ex.printStackTrace();
return null;
}
}
#Override
protected void onPostExecute(String s) {
myService.jobFinished(jobParameters, false);
}
}
}
Run Service
JobInfo.Builder builder=new JobInfo.Builder(100,new ComponentName(this,MyService.class));
builder.setPeriodic(10000)
.setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY)
.setPersisted(true);
mJobScheduler.schedule(builder.build());
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher2"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".Main"
android:label="#string/app_name"
android:screenOrientation="portrait" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".second_page"
android:screenOrientation="portrait" >
</activity>
<service android:name=".MyService"
android:permission="android.permission.BIND_JOB_SERVICE"
android:exported="true"
/>
</application>

Data in Adapter but not loding in Listview | converted Listactivity to ListFragment

I have converted Many Activities to Fragment, all are working fine except one. In the Previous version of this java file, it was extending ListActivity, now I have replaced it with ListFragment. Initially it was giving a nullPointerException, but with help of this post, I managed to remove error. Now it is fetching data in Adapter but not in listview (which I checked by printing it in log). So I need to show data in listview.
Here is Java code:
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.GradientDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.ListFragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import java.io.InputStreamReader;
import java.net.URL;
import java.io.BufferedReader;
import java.net.URLConnection;
import android.support.v4.app.Fragment;
public class listtojson extends ListFragment {
private ProgressDialog pDialog;
// URL to get contacts JSON
// public static String url = "http://www.newsvoice.in/upload_audio_sawdhan/listFileDir.php";
public static String url = "http://www.newsvoice.in/upload_audio_sawdhan/listnews.php";
//public static String url = "http://www.newsvoice.in/sites/listNewsSites.php";
// JSON Node names
private static final String TAG_CONTACTS = "contacts";
private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";
private static final String TAG_SIZE = "size";
private static final String TAG_PHONE_URL = "url";
private static final String TAG_FILETYPE = "filetype";
private static final String TAG_FILETYPETXT = "filetypetxt";
private static final String TAG_DETAILS = "details";
private static final String TAG_FILEPATH = "filepath";
private static final String TAG_LOCATION = "location";
private static final String TAG_DATETIME = "datetime";
private static final String TAG_USERNAME = "username";
private static final String TAG_HIGHALERT= "highalert";
// public ImageLoader imageLoader;
public int ssid ;
// contacts JSONArray
JSONArray contacts = null;
public TextView view1;
ListView lv;
// Hashmap for ListView
ArrayList<HashMap<String, String>> contactList;
View fragment;
LinearLayout llLayout;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
FragmentActivity faActivity = (FragmentActivity) super.getActivity();
llLayout = (LinearLayout) inflater.inflate(R.layout.listnewsjson, container, false);
contactList = new ArrayList<HashMap<String, String>>();
fragment = inflater.inflate(R.layout.listnewsjson, container, false);
return llLayout;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
lv = (ListView) fragment.findViewById(android.R.id.list);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String name = ((TextView) view.findViewById(R.id.name))
.getText().toString();
String size = ((TextView) view.findViewById(R.id.size))
.getText().toString();
String description = ((TextView) view.findViewById(R.id.url))
.getText().toString();
String details = ((TextView) view.findViewById(R.id.details))
.getText().toString();
String location = ((TextView) view.findViewById(R.id.location))
.getText().toString();
String datetime = ((TextView) view.findViewById(R.id.datetime))
.getText().toString();
String filetype = ((TextView) view.findViewById(R.id.filetypetxt))
.getText().toString();
String username = ((TextView) view.findViewById(R.id.username))
.getText().toString();
//String highalert = ((TextView) view.findViewById(R.id.highalert)).getText().toString();
//ImageView thumb_image=(ImageView)view.findViewById(R.id.filetype);
// ImageView image = (ImageView) view.findViewById(R.id.filetype);
// thumb image
//= String filetype = ((ImageView) view.findViewById(R.id.filetype))
//= .getText().toString();
// Starting single contact activity
/* Intent in = new Intent(getApplicationContext(),
fileDownloader.class);
in.putExtra(TAG_NAME, name);
in.putExtra(TAG_SIZE, cost);
in.putExtra(TAG_PHONE_URL, description);
startActivity(in);
*/
Intent in = new Intent(getActivity().getApplicationContext(), jsondetailActivity.class);
// passing sqlite row id
//= in.putExtra(TAG_ID, sqlite_id);
in.putExtra(TAG_ID, String.valueOf(id));
in.putExtra(TAG_NAME, name);
in.putExtra(TAG_DETAILS, details);
in.putExtra(TAG_LOCATION, location);
in.putExtra(TAG_DATETIME, datetime);
in.putExtra(TAG_FILETYPE, filetype);
in.putExtra(TAG_PHONE_URL, description);
in.putExtra(TAG_SIZE, size);
in.putExtra(TAG_USERNAME, username);
startActivity(in);
}
});
// Calling async task to get json
new GetContacts().execute();
//return llLayout;
}
/**
* Async task class to get json by making HTTP call
* */
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Loading People News");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
try {
// Making a request to url and getting response
// String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
URL requestUrl = new URL(url);
Log.e("Debug", " Sapp 1 : " + requestUrl.toString());
URLConnection con = requestUrl.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
StringBuilder sb=new StringBuilder();
//Reader rd=new Readable(in);
int cp;
try {
while((cp=in.read())!=-1){
sb.append((char)cp);
}}
catch(Exception e){
}
String jsonStr=sb.toString();
Log.e("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
contacts = jsonObj.getJSONArray(TAG_CONTACTS);
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String size = c.getString(TAG_SIZE);
String url = c.getString(TAG_PHONE_URL);
String details = c.getString(TAG_DETAILS);
String location = c.getString(TAG_LOCATION);
String datetime = c.getString(TAG_DATETIME);
String filetype = c.getString(TAG_FILETYPE);
String username = c.getString(TAG_USERNAME);
String highalert = c.getString(TAG_HIGHALERT);
HashMap<String, String> contact = new HashMap<String, String>();
// adding each child node to HashMap key => value
contact.put(TAG_ID, id);
contact.put(TAG_NAME, name);
contact.put(TAG_SIZE, size);
contact.put(TAG_PHONE_URL, url);
contact.put(TAG_DETAILS, details);
contact.put(TAG_LOCATION, location);
contact.put(TAG_DATETIME, datetime);
contact.put(TAG_FILETYPE, filetype);
contact.put(TAG_FILETYPETXT, filetype);
contact.put(TAG_USERNAME, username);
contact.put(TAG_HIGHALERT, highalert);
// Log.e("Debug", " Sapp 7 : " + name);
// adding contact to contact list
contactList.add(contact);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
}catch(Exception ec){
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
getActivity(), contactList,
R.layout.list_selector, new String[] { TAG_NAME, TAG_SIZE,
TAG_PHONE_URL,TAG_FILETYPE, TAG_FILETYPETXT,TAG_DETAILS,TAG_LOCATION,TAG_DATETIME, TAG_USERNAME, TAG_HIGHALERT}, new int[] { R.id.name,
R.id.size, R.id.url, R.id.filetype,R.id.filetypetxt, R.id.details, R.id.location, R.id.datetime, R.id.username, R.id.highalert });
Log.e("Debug", " Sapp 10" + TAG_NAME+contactList.toString());
//Here it is printing the array in Log
//Problem seems here
SimpleAdapter.ViewBinder viewBinder = new SimpleAdapter.ViewBinder() {
#Override
public boolean setViewValue(View view, Object data,
String textRepresentation) {
Log.e("Debug", " Sapp 11"+view.getId());
if (view.getId() == R.id.name) {
((TextView) view).setText((String) data);
return true;
} else if (view.getId() == R.id.size) {
((TextView) view).setText((String) data);
} else if (view.getId() == R.id.url) {
((TextView) view).setText((String) data);
} else if (view.getId() == R.id.details) {
((TextView) view).setText((String) data);
} else if (view.getId() == R.id.location) {
((TextView) view).setText((String) data);
} else if (view.getId() == R.id.datetime) {
((TextView) view).setText((String) data);
} else if (view.getId() == R.id.filetypetxt) {
((TextView) view).setText((String) data);
} else if (view.getId() == R.id.username) {
((TextView) view).setText((String) data);
} else if (view.getId() == R.id.highalert) {
GradientDrawable gd = new GradientDrawable();
gd.setColor(0xffff0000); // Changes this drawbale to use a single color instead of a gradient
gd.setCornerRadius(0);
gd.setSize(10,20);
// view.findViewById(R.id.name).setBackgroundDrawable(gd);
String halert=(String.valueOf((String) data));
if(halert.equals("1")) {
((TextView) view).setText(" ");
((TextView) view).setBackgroundDrawable(gd);
return true;
}
else { return true; }
} else if (view.getId() == R.id.filetype) {
// (view1 = (TextView) findViewById(R.id.filetypetxt)).setText((String) data);
Resources res =getResources();
String tnew=(String.valueOf((String) data));
String tst=tnew;
int sidd=0;
// Log.e("Debug", " Sapp 7:"+(String)data+":");
if(tst.equals("c")) { ssid = R.drawable.ca; }
else if(tst.equals("d")) { ssid = R.drawable.da; }
else if(tst.equals("e")) { ssid = R.drawable.ea; }
//s=2130837566;
Log.e("Debug", " Sapp 8 :"+ssid+":");
Bitmap bmp = BitmapFactory.decodeResource(res, ssid);
BitmapDrawable ob = new BitmapDrawable(getResources(), bmp);
((ImageView) view).setImageDrawable(ob);
((ImageView) view).setImageBitmap(bmp);
return true;
}
return false;
}
};
((SimpleAdapter) adapter).setViewBinder(viewBinder);
lv.setAdapter(adapter);
registerForContextMenu(lv);
}
}
public static String getFileSize(long size) {
if (size <= 0)
return "0";
final String[] units = new String[] { "B", "KB", "MB", "GB", "TB" };
int digitGroups = (int) (Math.log10(size) / Math.log10(1024));
return new DecimalFormat("#,##0.#").format(size / Math.pow(1024, digitGroups)) + " " + units[digitGroups];
}
}
and Here is xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<!-- Main ListView
Always give id value as list(#android:id/list)
-->
<ListView
android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:divider="#b5b5b5"
android:dividerHeight="1dp"
android:listSelector="#drawable/list_selector"
/>
</LinearLayout>
Some suggestions:
No need for View fragment; and its initialization: fragment = inflater.inflate(R.layout.listnewsjson, container, false); Remove them.
Replace lv = (ListView) fragment.findViewById(android.R.id.list); with lv = getListView();. getListView() is a method defined by ListFragment that returns the fragment's ListView.
IMPORTANT: Replace lv.setAdapter(adapter); in onPostExecute() with setListAdapter(adapter);. From documentation of ListFragment:
You must use ListFragment.setListAdapter() to associate the list with an adapter. Do not directly call ListView.setAdapter() or else important initialization will be skipped.
Modify setViewValue() method of viewBinder to:
#Override
public boolean setViewValue(View view, Object data,
String textRepresentation) {
Log.e("Debug", " Sapp 11" + view.getId());
if (view.getId() == R.id.highalert) {
GradientDrawable gd = new GradientDrawable();
gd.setColor(0xffff0000); // Changes this drawbale to use a single color instead of a gradient
gd.setCornerRadius(0);
gd.setSize(10, 20);
// view.findViewById(R.id.name).setBackgroundDrawable(gd);
String halert = (String.valueOf((String) data));
if (halert.equals("1")) {
((TextView) view).setText(" ");
((TextView) view).setBackgroundDrawable(gd);
} else {
// TODO: Should remove gradient color here because views are recycled.
}
return true;
}
if (view.getId() == R.id.filetype) {
// (view1 = (TextView) findViewById(R.id.filetypetxt)).setText((String) data);
Resources res = getResources();
String tnew = (String.valueOf((String) data));
String tst = tnew;
int sidd = 0;
// Log.e("Debug", " Sapp 7:"+(String)data+":");
if (tst.equals("c")) {
ssid = R.drawable.ca;
} else if (tst.equals("d")) {
ssid = R.drawable.da;
} else if (tst.equals("e")) {
ssid = R.drawable.ea;
}
//s=2130837566;
Log.e("Debug", " Sapp 8 :" + ssid + ":");
Bitmap bmp = BitmapFactory.decodeResource(res, ssid);
BitmapDrawable ob = new BitmapDrawable(getResources(), bmp);
((ImageView) view).setImageDrawable(ob);
((ImageView) view).setImageBitmap(bmp);
return true;
}
return false;
}
ViewBinder only needs to handle cases where you need to do something extra (like setting background color or loading images based on passed-in data values in your case) than just simply binding values to views. Ordinary binding of values to views is provided by SimpleAdapter by default.

Bluetooth Connection : Evolute Impress Printer not printing data

I have an issue of connecting bluetooth device through mobile and i can able to send bytes as Outputstream but i cant able to retrive print from Evolute impress printer.Please help me how to get the print
Problem:
how to check evolute printer whether its reciving data which i sent.
Main.java
public class Main extends Activity implements Runnable {
protected static final String TAG = "TAG";
private static final int REQUEST_CONNECT_DEVICE = 1;
private static final int REQUEST_ENABLE_BT = 2;
Button mScan, mPrint, mDisc,check;
BluetoothAdapter mBluetoothAdapter;
private UUID applicationUUID = UUID
.fromString("00001101-0000-1000-8000-00805F9B34FB");
private ProgressDialog mBluetoothConnectProgressDialog;
private BluetoothSocket mBluetoothSocket;
BluetoothDevice mBluetoothDevice;
#Override
public void onCreate(Bundle mSavedInstanceState) {
super.onCreate(mSavedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.main);
mScan = (Button) findViewById(R.id.Scan);
check = (Button)findViewById(R.id.check);
mScan.setOnClickListener(new View.OnClickListener() {
public void onClick(View mView) {
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter == null) {
Toast.makeText(Main.this, "Message1", 2000).show();
} else {
if (!mBluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(
BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent,
REQUEST_ENABLE_BT);
} else {
ListPairedDevices();
Intent connectIntent = new Intent(Main.this,
DeviceListActivity.class);
startActivityForResult(connectIntent,
REQUEST_CONNECT_DEVICE);
}
}
}
});
mPrint = (Button) findViewById(R.id.mPrint);
mPrint.setOnClickListener(new View.OnClickListener() {
public void onClick(View mView) {
Thread t = new Thread() {
public void run() {
try {
OutputStream os = mBluetoothSocket
.getOutputStream();
String BILL = "";
BILL = "\nInvoice No: ABCDEF28060000005" + " "
+ "04-08-2011\n";
BILL = BILL
+ "-----------------------------------------";
BILL = BILL + "\n\n";
BILL = BILL + "Total Qty:" + " " + "2.0\n";
BILL = BILL + "Total Value:" + " "
+ "17625.0\n";
BILL = BILL
+ "-----------------------------------------\n";
os.write(BILL.getBytes());
//This is printer specific code you can comment ==== > Start
// Setting height
int gs = 29;
os.write(intToByteArray(gs));
int h = 104;
os.write(intToByteArray(h));
int n = 162;
os.write(intToByteArray(n));
// Setting Width
int gs_width = 29;
os.write(intToByteArray(gs_width));
int w = 119;
os.write(intToByteArray(w));
int n_width = 2;
os.write(intToByteArray(n_width));
// Print BarCode
int gs1 = 29;
os.write(intToByteArray(gs1));
int k = 107;
os.write(intToByteArray(k));
int m = 73;
os.write(intToByteArray(m));
String barCodeVal = "ASDFC028060000005";// "HELLO12345678912345012";
System.out.println("Barcode Length : "
+ barCodeVal.length());
int n1 = barCodeVal.length();
os.write(intToByteArray(n1));
for (int i = 0; i < barCodeVal.length(); i++) {
os.write((barCodeVal.charAt(i) + "").getBytes());
}
//printer specific code you can comment ==== > End
} catch (Exception e) {
Log.e("Main", "Exe ", e);
}
}
};
t.start();
}
});
mDisc = (Button) findViewById(R.id.dis);
mDisc.setOnClickListener(new View.OnClickListener() {
public void onClick(View mView) {
if (mBluetoothAdapter != null)
mBluetoothAdapter.disable();
}
});
}// onCreate
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
try {
if (mBluetoothSocket != null)
mBluetoothSocket.close();
} catch (Exception e) {
Log.e("Tag", "Exe ", e);
}
}
#Override
public void onBackPressed() {
try {
if (mBluetoothSocket != null)
mBluetoothSocket.close();
} catch (Exception e) {
Log.e("Tag", "Exe ", e);
}
setResult(RESULT_CANCELED);
finish();
}
public void onActivityResult(int mRequestCode, int mResultCode,
Intent mDataIntent) {
super.onActivityResult(mRequestCode, mResultCode, mDataIntent);
switch (mRequestCode) {
case REQUEST_CONNECT_DEVICE:
if (mResultCode == Activity.RESULT_OK) {
Bundle mExtra = mDataIntent.getExtras();
String mDeviceAddress = mExtra.getString("DeviceAddress");
Log.v(TAG, "Coming incoming address " + mDeviceAddress);
mBluetoothDevice = mBluetoothAdapter
.getRemoteDevice(mDeviceAddress);
mBluetoothConnectProgressDialog = ProgressDialog.show(this,
"Connecting...", mBluetoothDevice.getName() + " : "
+ mBluetoothDevice.getAddress(), true, false);
Thread mBlutoothConnectThread = new Thread(this);
mBlutoothConnectThread.start();
// pairToDevice(mBluetoothDevice); This method is replaced by
// progress dialog with thread
}
break;
case REQUEST_ENABLE_BT:
if (mResultCode == Activity.RESULT_OK) {
ListPairedDevices();
Intent connectIntent = new Intent(Main.this,
DeviceListActivity.class);
startActivityForResult(connectIntent, REQUEST_CONNECT_DEVICE);
} else {
Toast.makeText(Main.this, "Message", 2000).show();
}
break;
}
}
private void ListPairedDevices() {
Set<BluetoothDevice> mPairedDevices = mBluetoothAdapter
.getBondedDevices();
if (mPairedDevices.size() > 0) {
for (BluetoothDevice mDevice : mPairedDevices) {
Log.v(TAG, "PairedDevices: " + mDevice.getName() + " "
+ mDevice.getAddress());
}
}
}
public void run() {
try {
mBluetoothSocket = mBluetoothDevice
.createRfcommSocketToServiceRecord(applicationUUID);
mBluetoothAdapter.cancelDiscovery();
mBluetoothSocket.connect();
mHandler.sendEmptyMessage(0);
} catch (IOException eConnectException) {
Log.d(TAG, "CouldNotConnectToSocket", eConnectException);
closeSocket(mBluetoothSocket);
return;
}
}
private void closeSocket(BluetoothSocket nOpenSocket) {
try {
nOpenSocket.close();
Log.d(TAG, "SocketClosed");
} catch (IOException ex) {
Log.d(TAG, "CouldNotCloseSocket");
}
}
private Handler mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
mBluetoothConnectProgressDialog.dismiss();
Toast.makeText(Main.this, "DeviceConnected", 5000).show();
}
};
public static byte intToByteArray(int value) {
byte[] b = ByteBuffer.allocate(4).putInt(value).array();
for (int k = 0; k < b.length; k++) {
System.out.println("Selva [" + k + "] = " + "0x"
+ UnicodeFormatter.byteToHex(b[k]));
}
return b[3];
}
public byte[] sel(int val) {
ByteBuffer buffer = ByteBuffer.allocate(2);
buffer.putInt(val);
buffer.flip();
return buffer.array();
}
DeviceListActivity
public class DeviceListActivity extends Activity
{
protected static final String TAG = "TAG";
private BluetoothAdapter mBluetoothAdapter;
private ArrayAdapter<String> mPairedDevicesArrayAdapter;
#Override
protected void onCreate(Bundle mSavedInstanceState)
{
super.onCreate(mSavedInstanceState);
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setContentView(R.layout.device_list);
setResult(Activity.RESULT_CANCELED);
mPairedDevicesArrayAdapter = new ArrayAdapter<String>(this, R.layout.device_name);
ListView mPairedListView = (ListView) findViewById(R.id.paired_devices);
mPairedListView.setAdapter(mPairedDevicesArrayAdapter);
mPairedListView.setOnItemClickListener(mDeviceClickListener);
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
Set<BluetoothDevice> mPairedDevices = mBluetoothAdapter.getBondedDevices();
if (mPairedDevices.size() > 0)
{
findViewById(R.id.title_paired_devices).setVisibility(View.VISIBLE);
for (BluetoothDevice mDevice : mPairedDevices)
{
mPairedDevicesArrayAdapter.add(mDevice.getName() + "\n" + mDevice.getAddress());
}
}
else
{
String mNoDevices = "None Paired";//getResources().getText(R.string.none_paired).toString();
mPairedDevicesArrayAdapter.add(mNoDevices);
}
}
#Override
protected void onDestroy()
{
super.onDestroy();
if (mBluetoothAdapter != null)
{
mBluetoothAdapter.cancelDiscovery();
}
}
private OnItemClickListener mDeviceClickListener = new OnItemClickListener()
{
public void onItemClick(AdapterView<?> mAdapterView, View mView, int mPosition, long mLong)
{
mBluetoothAdapter.cancelDiscovery();
String mDeviceInfo = ((TextView) mView).getText().toString();
String mDeviceAddress = mDeviceInfo.substring(mDeviceInfo.length() - 17);
Log.v(TAG, "Device_Address " + mDeviceAddress);
Bundle mBundle = new Bundle();
mBundle.putString("DeviceAddress", mDeviceAddress);
Intent mBackIntent = new Intent();
mBackIntent.putExtras(mBundle);
setResult(Activity.RESULT_OK, mBackIntent);
finish();
}
};
}
}
UnicodeFormatter:
public class UnicodeFormatter {
static public String byteToHex(byte b) {
// Returns hex String representation of byte b
char hexDigit[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'a', 'b', 'c', 'd', 'e', 'f' };
char[] array = { hexDigit[(b >> 4) & 0x0f], hexDigit[b & 0x0f] };
return new String(array);
}
static public String charToHex(char c) {
// Returns hex String representation of char c
byte hi = (byte) (c >>> 8);
byte lo = (byte) (c & 0xff);
return byteToHex(hi) + byteToHex(lo);
}
}
Manifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.printapplication"
android:versionCode="1"
android:versionName="1.0" >
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.BLUETOOTH" />
<permission
android:name="android.permission.BLUETOOTH"
android:label="BLUETOOTH" >
</permission>
<permission android:name="android.permission.BLUETOOTH_ADMIN" >
</permission>
<uses-sdk
android:minSdkVersion="15"
android:targetSdkVersion="21" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".Main"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".DeviceListActivity"
android:label="#string/app_name" >
</activity>
</application>
</manifest>

Google maps API v2 Android, not drawing polygon when offline

I have a test application that I draw a Polygon using google maps API.
The problem is that, when I have no cache of any maps (new installed application) the Polygon does not draw.
Its not a problem not having the maps loaded, but I do need the Polygons drawn in my screen.
Is there a way I can do that?
Sry for my bad english
Heres the code I have:
package ngvl.testegmaps_v2;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Random;
import ngvl.testegmaps_v2.VO.GeoPosicionamento;
import ngvl.testegmaps_v2.VO.Layer;
import ngvl.testegmaps_v2.VO.Secao;
import ngvl.testegmaps_v2.VO.Talhao;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnMapClickListener;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Polygon;
import com.google.android.gms.maps.model.PolygonOptions;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
public class MainActivity extends FragmentActivity {
private List<Secao> secoes;
private List<Polygon> poligonos = new ArrayList<Polygon>();
private HashMap<String,Object[]> informacoes = new HashMap<String,Object[]>();
private GoogleMap map;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SupportMapFragment fragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
map = fragment.getMap();
map.getUiSettings().setRotateGesturesEnabled(false);
// Setting a click event handler for the map
LatLng latLng = new LatLng(-20.9957152, -47.3241304);
// map.addMarker(new
// MarkerOptions().position(latLng).icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_launcher)).title("Av. Paulista").snippet("São Paulo"));
configuraPosicao(map, latLng);
Button button = (Button)findViewById(R.id.button1);
// Register the onClick listener with the implementation above
button.setOnClickListener(mCorkyListener);
}
private void configuraPosicao(GoogleMap map, LatLng latLng) {
/*
* 3D map.moveCamera( CameraUpdateFactory.newLatLngZoom(latLng, 15));
* map.animateCamera( CameraUpdateFactory.zoomTo(10), 2000, null);
*
* CameraPosition cameraPosition = new CameraPosition.Builder()
* .target(latLng) .zoom(17) .bearing(90) .tilt(45) .build();
*
* map.animateCamera( CameraUpdateFactory.newCameraPosition(
* cameraPosition));
*/
map.setMapType(GoogleMap.MAP_TYPE_NONE);
// map.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 17.0f));
map.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 15));
try {
String json = readFileAsString("geo.json");
Gson gson = new Gson();
this.secoes = gson.fromJson(json, new TypeToken<List<Secao>>() {
}.getType());
json = null;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
escrevePoligons(map);
}
private String readFileAsString(String fileName) throws IOException {
InputStream is = getAssets().open(fileName);
if (is != null) {
StringBuilder sb = new StringBuilder();
String line;
try {
BufferedReader reader = new BufferedReader(
new InputStreamReader(is, "UTF-8"));
while ((line = reader.readLine()) != null) {
sb.append(line).append("\n");
}
} finally {
is.close();
}
return sb.toString();
} else {
return "";
}
}
private void escrevePoligons(GoogleMap map) {
float stroke = (float) 1.5;
for (Secao secao : secoes) {
for (Talhao talhao : secao.getTalhoes()) {
for (Layer layer : talhao.getLayers()) {
// PolygonOptions rectOptions = new PolygonOptions();
List<LatLng> latlngs = new ArrayList<LatLng>();
for (GeoPosicionamento geoPosicionamento : layer.getGeoPosicionamentos()) {
latlngs.add(new LatLng(geoPosicionamento.getLatitude()
.setScale(7, BigDecimal.ROUND_HALF_EVEN)
.doubleValue(), geoPosicionamento
.getLongitude()
.setScale(7, BigDecimal.ROUND_HALF_EVEN)
.doubleValue()));
}
int color = 0x1F00FF00;
int color2 = 0x5F000000;
PolygonOptions polygonOptions = new PolygonOptions()
.fillColor(color).addAll(latlngs)
.strokeColor(color2).strokeWidth(stroke);
Polygon p = map.addPolygon(polygonOptions);
poligonos.add(p);
informacoes.put( p.getId(), new Object[]{ secao, talhao , layer } );
//System.out.println(polygonOptions.getPoints());
polygonOptions = null;
latlngs = null;
}
}
}
this.secoes = null;
// String mUrl =
// "https://khms0.google.com.br/kh/v=124&src=app&z={z}&x={x}&y={y}";
// MyUrlTileProvider mTileProvider = new MyUrlTileProvider(256, 256,
// mUrl);
// mTileProvider.tilesRange();
// map.addTileOverlay(new
// TileOverlayOptions().tileProvider(mTileProvider).zIndex(-1f));
//String mUrl = "http://a.tile.openstreetmap.org/{z}/{x}/{y}.png";
//MyUrlTileProvider mTileProvider = new MyUrlTileProvider(256, 256, mUrl);
//map.addTileOverlay(new TileOverlayOptions().tileProvider(mTileProvider).zIndex(-1f));
map.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(-20.9957152, -47.3241304), 14));
// TileProvider tileProvider = TileProviderFactory.getTileProvider();
// map.addTileOverlay(new
// TileOverlayOptions().tileProvider(tileProvider));
// map.moveCamera(CameraUpdateFactory.newLatLngZoom(new
// LatLng(-20.9957152, -47.3241304), 15));
map.setOnMapClickListener(new OnMapClickListener()
{
public void onMapClick(LatLng point)
{
Polygon p = isPointInPolygon(point);
if( p != null){
p.setFillColor(getRandomColor());
Object[] clicado = informacoes.get( p.getId() );
Secao secao_clicada = (Secao) clicado[0];
Talhao talhao_clicada = (Talhao) clicado[1];
Layer layer_clicada = (Layer) clicado[2];
//System.out.println(secao_clicada);
//System.out.println(talhao_clicada);
//System.out.println(layer_clicada);
//System.out.println("=======================");
StringBuilder texto = new StringBuilder();
texto.append("Seção: " + secao_clicada.getDesc() + "\n");
texto.append("Talhão: " + talhao_clicada.getTalhao() + "\n");
texto.append("Variedade: " + talhao_clicada.getVariedade() + " - " + talhao_clicada.getDescVariedade() + "\n");
texto.append("Layer: " + layer_clicada.getSequencia() + "\n");
//Toast.makeText(MainActivity.this, texto , Toast.LENGTH_LONG).show();
addMarker(point,texto);
}//else
//Toast.makeText(MainActivity.this,"Clicou fora da Área de um Poligono", Toast.LENGTH_LONG).show();
}
});
}
public void addMarker(LatLng point, StringBuilder texto) {
/*map.addMarker(new MarkerOptions().position(point).icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_launcher))
.title("Caracteristicas: ")
.snippet( texto );
*/
Toast.makeText(MainActivity.this, texto , Toast.LENGTH_LONG).show();
}
private Polygon isPointInPolygon(LatLng tap) {
for( Polygon p : poligonos){
int intersectCount = 0;
List<LatLng> vertices = p.getPoints();
for(int j=0; j<vertices.size()-1; j++) {
if( rayCastIntersect(tap, vertices.get(j), vertices.get(j+1)) ) {
intersectCount++;
}
}
if(((intersectCount % 2) == 1)){
return p;
}
}
return null;// odd = inside, even = outside;
}
private boolean rayCastIntersect(LatLng tap, LatLng vertA, LatLng vertB) {
double aY = vertA.latitude;
double bY = vertB.latitude;
double aX = vertA.longitude;
double bX = vertB.longitude;
double pY = tap.latitude;
double pX = tap.longitude;
if ( (aY>pY && bY>pY) || (aY<pY && bY<pY) || (aX<pX && bX<pX) ) {
return false; // a and b can't both be above or below pt.y, and a or b must be east of pt.x
}
double m = (aY-bY) / (aX-bX); // Rise over run
double bee = (-aX) * m + aY; // y = mx + b
double x = (pY - bee) / m; // algebra is neat!
return x > pX;
}
private OnClickListener mCorkyListener = new OnClickListener() {
public void onClick(View v) {
// do something when the button is clicked
map.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(-20.9957152, -47.3241304), 14));
}
};
public int getRandomColor() {
int color;
Random rnd = new Random();
color = Color.argb(255, rnd.nextInt(256), rnd.nextInt(256),
rnd.nextInt(256));
return color;
}
}
Setting map type to MAP_TYPE_NONE like example above does not solve the problem
I will this as marked solved by using Maps Forge Open Source API
If someone did with Google Maps Api please share and I would change the answer.
The answer I found is that its impossible to render or access anything without rendering the map first (online or via cache)
This is actually a bug of GoogleMaps Api v2 for Android.
It is referenced here:
https://code.google.com/p/gmaps-api-issues/issues/detail?id=5017
Star it if you want to accelerate the bug fix!

capturing the image using android camera [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Calling camera from an activity, capturing an image and uploading to a server
i am very new to android, i am trying to capture the image after that i placed that image into image view,its working on emulator but in device it crashes it shows the message force close even it cannot open the camera activity.the following is my code.
please help me how to solve this problem.thank you.
package com.gss.android;
package com.gss.android;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
public class Pictures extends Activity{
Button btnsave,btnnewpic;
protected ImageView image;
protected String _path;
File sdImageMainDirectory;
private static final int IMAGE_CAPTURE = 0;
protected boolean _taken = true;
private Uri imageUri;
protected static final String PHOTO_TAKEN = "photo_taken";
private static final int CAMERA_PIC_REQUEST = 1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.pictures);
btnsave=(Button)findViewById(R.id.btnsave);
btnnewpic=(Button)findViewById(R.id.btnnewpic);
btnnewpic.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
startCameraActivity2();
}
});
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if ( requestCode == CAMERA_PIC_REQUEST){
if (resultCode == RESULT_OK){
switch (resultCode) {
case 0:
finish();
break;
case -1:
try {
StoreImage(this, Uri.parse(data.toURI()),
sdImageMainDirectory);
Log.e("file path", "stiring file") ;
} catch (Exception e) {
e.printStackTrace();
}
finish();
}
}
} else if ( requestCode == IMAGE_CAPTURE) {
if (resultCode == RESULT_OK){
Log.d("ANDRO_CAMERA","Picture taken!!!");
ImageView image = (ImageView) findViewById(R.id.image);
image.setImageURI(imageUri);
}
}
}
protected void startCameraActivity2()
{
Log.d("ANDRO_CAMERA", "Starting camera on the phone...");
String fileName = "testphoto.jpg";
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, fileName);
values.put(MediaStore.Images.Media.DESCRIPTION,
"Image capture by camera");
values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
imageUri = getContentResolver().insert(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
startActivityForResult(intent, IMAGE_CAPTURE);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
if (savedInstanceState.getBoolean(Pictures.PHOTO_TAKEN)) {
_taken = true;
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
outState.putBoolean(Pictures.PHOTO_TAKEN, _taken);
}
public static void StoreImage(Context mContext, Uri imageLoc, File imageDir) {
Bitmap bm = null;
try {
bm = MediaStore.Images.Media.getBitmap(mContext.getContentResolver(), imageLoc);
FileOutputStream out = new FileOutputStream(imageDir);
bm.compress(Bitmap.CompressFormat.JPEG, 100, out);
Log.e("file dir",imageDir.toString());
bm.recycle();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
I think this is a problem related to the emulator and not the physical device.
I used this code and I got a bitmap:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
captureButton = (Button)findViewById(R.id.capture);
captureButton.setOnClickListener(listener);
imageView = (ImageView)findViewById(R.id.image);
destination = new File(Environment.getExternalStorageDirectory(),"image.jpg");
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == REQUEST_IMAGE && resultCode == Activity.RESULT_OK) {
//Bitmap userImage = (Bitmap)data.getExtras().get("data");
try {
FileInputStream in = new FileInputStream(destination);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 10; //Downsample 10x
Bitmap userImage = BitmapFactory.decodeStream(in, null, options);
imageView.setImageBitmap(userImage);
} catch (Exception e) {
e.printStackTrace();
}
}
}
private View.OnClickListener listener = new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//Add extra to save full-image somewhere
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(destination));
Toast.makeText(JMABarcodeScannerActivity.this, Uri.fromFile(destination).toString(), Toast.LENGTH_SHORT).show();
startActivityForResult(intent, REQUEST_IMAGE);
}
};
}
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">
<Button
android:id="#+id/capture"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Take a Picture"
/>
<ImageView
android:id="#+id/image"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:scaleType="centerInside"
/>
</LinearLayout>