Code with no errors crashes when testing on mobile - android

I am extremely new when it comes to Android Studio but have managed to put together 2 activities which work fine under separate apps, but when joined, it crashed when the MainActivity calls AddressActivity usingIntent and startActivity.
There is another problem which maybe related or may not be. When installing the app, there are NO permissions requested.
Here is my code:
AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COURSE_LOCATION" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity
android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".AddressActivity"
android:label="login">
</activity>
</application>
MainActivity.class
package crproductionsptyltd.login;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import static crproductionsptyltd.login.R.id.driverid;
import static crproductionsptyltd.login.R.id.login;
public class MainActivity extends Activity {
EditText driverid;
Button btnOk;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
// find View-elements
btnOk = (Button) findViewById(login);
// btnOk.setOnClickListener(this)
// create click listener
View.OnClickListener oclBtnOk = new View.OnClickListener() {
#Override
public void onClick(View v) {
// change text of the TextView (tvOut)
btnOk.setText("Logging IN.....");
Intent i = new Intent(MainActivity.this, AddressActivity.class);
i.putExtra("driver_id", driverid.getText().toString());
startActivity(i);
};
};
// assign click listener to the OK button (btnOK)
btnOk.setOnClickListener(oclBtnOk);
// startActivity(new Intent(MainActivity.this, AddressActivity.class));
// Intent i = new Intent(MainActivity.this, NewActivity.class);//
// startActivity(i);
};
}
AddressActivity.class
package crproductionsptyltd.login;
import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Locale;
import android.app.Activity;
import android.content.Context;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.content.Intent;
public class AddressActivity extends Activity {
/**
* Called when the activity is first created.
*/
String lat = "", lon = "";
TextView tvView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gps);
tvView = (TextView) findViewById(R.id.tvView);
Intent intent = getIntent();
String driverid = intent.getStringExtra("driver_id");
tvView.setText("Your Driver ID is: " + driverid);
Button btnLocation = (Button) findViewById(R.id.btnLocation);
btnLocation.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
// Acquire a reference to the system Location Manager
LocationManager locationManager = (LocationManager) AddressActivity.this.getSystemService(Context.LOCATION_SERVICE);
// Define a listener that responds to location updates
LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
// Called when a new location is found by the network location provider.
lat = Double.toString(location.getLatitude());
lon = Double.toString(location.getLongitude());
TextView tv = (TextView) findViewById(R.id.txtLoc);
tv.setText("Your Location is:" + lat + "--" + lon);
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
public void onProviderEnabled(String provider) {
}
public void onProviderDisabled(String provider) {
}
};
// Register the listener with the Location Manager to receive location updates
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
}
});
Button btnSend = (Button) findViewById(R.id.btnSend);
btnSend.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
postData(lat, lon);
}
});
Button btnAdd = (Button) findViewById(R.id.btnAddress);
btnAdd.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
TextView tv = (TextView) findViewById(R.id.txtAddress);
tv.setText(GetAddress(lat, lon));
}
});
}
public void postData(String la, String lo) {
//URL url = new URL("https://www.autoflora.net/driver/gps.php?Driver_ID=877&latlong=" + lat + "*" + lon);
int TIMEOUT_VALUE = 15000;
try{
URL myUrl = new URL("https://www.autoflora.net/driver/gps.php?Driver_ID=877&latlong=" + lat + "*" + lon);
URLConnection connection = myUrl.openConnection();
connection.setConnectTimeout(TIMEOUT_VALUE);
connection.connect();
} catch (Exception e) {
}
}
public String GetAddress(String lat, String lon)
{
Geocoder geocoder = new Geocoder(this, Locale.ENGLISH);
String ret = "";
try {
List<Address> addresses = geocoder.getFromLocation(Double.parseDouble(lat), Double.parseDouble(lon), 1);
if(addresses != null) {
Address returnedAddress = addresses.get(0);
StringBuilder strReturnedAddress = new StringBuilder("Address:\n");
for(int i=0; i<returnedAddress.getMaxAddressLineIndex(); i++) {
strReturnedAddress.append(returnedAddress.getAddressLine(i)).append("\n");
}
ret = strReturnedAddress.toString();
}
else{
ret = "No Address returned!";
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
ret = "Can't get Address!";
}
return ret;
}
}
activity_login.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_horizontal"
android:orientation="vertical"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="crproductionsptyltd.login.LoginActivity">
<!-- Login progress -->
<ProgressBar
android:id="#+id/login_progress"
style="?android:attr/progressBarStyleLarge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:visibility="gone" />
<ScrollView
android:id="#+id/login_form"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:id="#+id/email_login_form"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<AutoCompleteTextView
android:id="#+id/driverid"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Driver ID"
android:inputType="textEmailAddress"
android:maxLines="1"
android:singleLine="true" />
</android.support.design.widget.TextInputLayout>
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
</android.support.design.widget.TextInputLayout>
<Button
android:id="#+id/login"
style="?android:textAppearanceSmall"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:text="Login"
android:textStyle="bold"
android:onClick="checkDriver" />
</LinearLayout>
</ScrollView>
</LinearLayout>
activity_gps.class
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/txtLoc"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView" />
<TextView
android:id="#+id/tvView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="20dp"
android:textSize="20sp">
</TextView>
<Button
android:id="#+id/btnLocation"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Get my Location" />
<Button
android:id="#+id/btnSend"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Send Location" />
<Button
android:id="#+id/btnAddress"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Try Get Street Address" />
<TextView
android:id="#+id/txtAddress"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Medium Text"
android:textAppearance="?android:attr/textAppearanceMedium" />
</LinearLayout>

Based on your code, the app will crash here: i.putExtra("driver_id", driverid.getText().toString()), resulting in a NullPointerException. It crashes because you don't have an initialisation for EditText driverid; in onCreate and thus, it will throw an exception when used uninitialised.
To fix the problem you have to update the field in onCreate:
driverid = (EditText) findViewById(driverid);

I think, to use android.support.design.widget.TextInputLayout
you should use these dependencies
compile 'com.android.support:appcompat-v7:22.2.0'
compile 'com.android.support:design:22.2.0'
& also please correct
btnOk = (Button) findViewById(R.id.login); //wrongly added
driverid = (EditText) findViewById(R.id.driverid); // not added

Related

whenever i try to start the webview activity though a button it says the app has stopped

I am trying to create an app that implements the webview activity whenever you press a button but. Whenever I press it gives me an, unfortunately, message instead of going to it. Everything seems to be right and I put it through the debugger and it gave me the error "E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.time_app, PID: 7599
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.time_app/com.example.time_app.Browser}: android.view.InflateException: Binary XML file line #8: Error inflating class android.webkit.WebView".It says the problem is at line 42 in the browser.java file which is "setContentView(R.layout.activity_browser);".Ive checked all of my lines of code and it all seems right.
Browser.java
package com.example.time_app;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import java.util.Calendar;
import java.util.Date;
public class Browser extends AppCompatActivity {
//creating the webview variable
WebView wb;
//the end variable takes in the finshed load time(it is a long function because of the number length
long end;
//this is just a varibale to be used for the alert code
final Context context = this;
//this is the total number converted as a string because the alert function does not take in float
String numberAsString;
//the start variable takes in the start load time(it is a long function because of the number length
long start;
//The total variable takes in the substraction of the end and start and is a float variale do to its shorter length
float total;
Date end_Time;
Date start_Time;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_browser);
wb = (WebView) findViewById(R.id.webview);
wb.setWebViewClient(new WebViewClient() {
//this function records the load time
public void onPageStarted(WebView view, String url, Bitmap favicon) {
start = System.currentTimeMillis();
start_Time = Calendar.getInstance().getTime();
}
//This function will take in the finished load time and create an alert
#RequiresApi(api = Build.VERSION_CODES.O)
public void onPageFinished(WebView view, String url) {
end = System.currentTimeMillis();
total=end-start;
end_Time = Calendar.getInstance().getTime();
// Total is the difference in milliseconds.
// Dividing by 1000, you convert it to seconds
numberAsString = String.valueOf(total/1000);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
context);
// set title
alertDialogBuilder.setTitle("Your Load Time");
// set dialog message
alertDialogBuilder
.setMessage("Elapsed Time:"+numberAsString+"\n"+"Start Time:"+start_Time+"\n"+"EndTime:"+end_Time+"\n")
.setCancelable(false)
.setNegativeButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// if this button is clicked, just close
// the dialog box and do nothing
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
}
});
//declaring and setting the web setting variable
WebSettings webSettings = wb.getSettings();
//setting up the javascript to allow thw browser to use javascript
webSettings.setJavaScriptEnabled(true);
//loading url
wb.loadUrl("https://www.aa.com");
}
}
activity_browser.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Browser">
<WebView
android:id="#+id/webview"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout >
Manual_menu.java
package com.example.time_app;
import androidx.appcompat.app.AppCompatActivity;
import java.util.ArrayList;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
public class Manual_menu extends AppCompatActivity {
public ListView lv;
public EditText nametxt;
public Button addbtn,updatebtn,deletebtn,submit;
public ArrayList<String> names=new ArrayList<String>();
public ArrayAdapter<String> adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_manual_menu);
lv=(ListView) findViewById(R.id.Listview1);
nametxt=(EditText) findViewById(R.id.nametxt);
addbtn=(Button) findViewById(R.id.addbtn);
updatebtn=(Button) findViewById(R.id.updatebtn);
deletebtn=(Button) findViewById(R.id.deletebtn);
submit=(Button) findViewById(R.id.Submit_btn);
//adapter
adapter=new ArrayAdapter<String>(this, android.R.layout.simple_list_item_single_choice,names);
lv.setAdapter(adapter);
//Set Selected Item
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
nametxt.setText(names.get(i));
}
});
//add button event
addbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
add();
}
});
//update button event
updatebtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
update();
}
});
//delete button event
deletebtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
delete();
}
});
//clear button event
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
openActivityDecision();
}
});
}
//add
private void add()
{
String name=nametxt.getText().toString();
if(!name.isEmpty() && name.length()>0)
{
//Add
adapter.add(name);
//Refresh
adapter.notifyDataSetChanged();
nametxt.setText("");
Toast.makeText(getApplicationContext(), "Added " +name,Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(getApplicationContext(), "!!Nothing to Add " +name,Toast.LENGTH_SHORT).show();
}
}
//Update
private void update()
{
String name=nametxt.getText().toString();
int pos=lv.getCheckedItemPosition();
if(!name.isEmpty() && name.length()>0)
{
//Remove Item
adapter.remove(names.get(pos));
//insert
adapter.insert(name,pos);
//refresh
adapter.notifyDataSetChanged();
Toast.makeText(getApplicationContext(), "Updated " +name,Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(getApplicationContext(), "!!Nothing to Update " ,Toast.LENGTH_SHORT).show();
}
}
//delete
private void delete()
{
int pos=lv.getCheckedItemPosition();
if(pos > -1)
{
//remove
adapter.remove(names.get(pos));
//refresh
adapter.notifyDataSetChanged();
nametxt.setText("");
Toast.makeText(getApplicationContext(), "Deleted " ,Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(getApplicationContext(), "!!Nothing to delete " ,Toast.LENGTH_SHORT).show();
}
}
//Submit
private void openActivityDecision()
{
Intent intent=new Intent(this, Browser.class);
startActivity(intent);
}
}
activity_manual_menu.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".Manual_menu">
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginTop="35dp"
android:text="Name :"
/>
<EditText
android:id="#+id/nametxt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignTop="#+id/textView1"
android:ems="10"
/>
<ListView
android:id="#+id/Listview1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView1"
android:layout_below="#+id/addbtn"
android:choiceMode="singleChoice"
android:layout_marginTop="20dp">
</ListView>
<Button
android:id="#+id/addbtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/Listview1"
android:layout_below="#+id/nametxt"
android:layout_marginTop="19dp"
android:text="add" />
<Button
android:id="#+id/updatebtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/Listview1"
android:layout_toRightOf="#+id/addbtn"
android:layout_marginTop="19dp"
android:text="Update" />
<Button
android:id="#+id/Submit_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/Listview1"
android:layout_alignParentRight="true"
android:layout_marginTop="19dp"
android:text="Submit" />
<Button
android:id="#+id/deletebtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/Listview1"
android:layout_toRightOf="#+id/updatebtn"
android:layout_marginTop="19dp"
android:text="Delete" />
</RelativeLayout>
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.time_app">
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".File_menu"></activity>
<activity android:name=".Browser" />
<activity android:name=".file_load" />
<activity android:name=".Manual_menu" />
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>

Trouble in getting Location in Android SDK

I am new to Android, trying to implement Location Based Service but, I am getting errors. I am getting confused now.
Here are my files:
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.om.locationdemo.MainActivity">
<Button
android:text="Get Location"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:id="#+id/button" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello World!"
android:id="#+id/textView"
android:textStyle="bold"
android:textAlignment="center"
android:textSize="20sp"
android:layout_below="#+id/button"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="37dp" />
<Button
android:text="Button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="137dp"
android:id="#+id/button2" />
</RelativeLayout>
**AndroidManifest.xml**
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.om.locationdemo">
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.INTERNET"/>
</activity>
</application>
</manifest>
MainActivity.java
package com.example.om.locationdemo;
import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.test.mock.MockContentProvider;
import android.test.mock.MockContext;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
Button b1, b2;
TextView tv;
LocationManager lmngr;
LocationListener llm;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1 = (Button) findViewById(R.id.button);
b2 = (Button) findViewById(R.id.button2);
tv = (TextView) findViewById(R.id.textView);
lmngr = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
llm = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
tv.setText("Latitude = " + location.getLatitude() + " Longitude's = " + location.getLongitude());
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
Toast.makeText(MainActivity.this, "Please Enable Location Service", Toast.LENGTH_LONG).show();
}
};
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
lmngr.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, llm);
}
});
b2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
lmngr.requestLocationUpdates
(LocationManager.NETWORK_PROVIDER,0, 0, llm);
}
});
}
}

longitude and latitude acquiring (Android) + reverse geocoding

So i put together a few snippets that i found here and there; aiming to make a more complex app, however, at one point i was able to obtain the the longitude and latitude number, but once I've tried supply those number to the reverse GeoCoding mechanism, i have not been able to get the Long and Lat numbers and the app crashes after i click the button (which does the reverse geocoding)
package com.example.com.example;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
import android.app.Activity;
import android.content.Context;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
Button myLocation;
TextView myAddress;
TextView textLat;
TextView textLong;
double latHolder = 0.0;
double longHolder = 0.0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myLocation= (Button) findViewById(R.id.location);
myAddress = (TextView)findViewById(R.id.address);
textLat = (TextView)findViewById(R.id.textLat); ///COORDINATION VARIABLES1
textLong = (TextView)findViewById(R.id.textLong);///2
LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE); //gets it from the Operating system
LocationListener ll = new mylocationlistener();
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, ll); //LOCATION UPDATED LINKED
if(lm.isProviderEnabled(LocationManager.GPS_PROVIDER))
{
textLat.setText("GPS ONLINE (PLEASE WAIT)");
textLong.setText("GPS ONLINE (PLEASE WAIT)");
}
else
{
textLat.setText("GPS OFFLINE");
textLong.setText("GPS OFFLINE");
}
myLocation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
getMyLocationAddress();
}
});
}
///////////COORDIATION ACQUIRING DOWN HERE
private class mylocationlistener implements LocationListener
{
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
if(location != null)
{
double pLat = location.getLatitude();
double pLong = location.getLongitude();
textLat.setText(Double.toString(pLat));
textLong.setText(Double.toString(pLong));
latHolder = pLat;
longHolder = pLong;
}
}
#Override
public void onStatusChanged(String provider, int status,
Bundle extras) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
}
public void getMyLocationAddress() {
Geocoder geocoder= new Geocoder(this, Locale.ENGLISH);
try {
//Place your latitude and longitude
List<Address> addresses = geocoder.getFromLocation(latHolder,longHolder, 1);
if(addresses != null) {
Address fetchedAddress = addresses.get(0);
StringBuilder strAddress = new StringBuilder();
for(int i=0; i<fetchedAddress.getMaxAddressLineIndex(); i++) {
strAddress.append(fetchedAddress.getAddressLine(i)).append("\n");
}
myAddress.setText("I am at: " +strAddress.toString());
}
else
myAddress.setText("No location found..!");
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(getApplicationContext(),"Could not get address..!", Toast.LENGTH_LONG).show();
}
}
}
Here is my Manafist with all permissions which should be enough
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.com.example"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="21" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<permission android:name="com.example.permission.MAPS_RECEIVE" android:protectionLevel="signature"/>
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
and last but not lease my xml layout
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<TextView
android:id="#+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="LATITUDE" />
<Button
android:id="#+id/location"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/address"
android:layout_below="#+id/address"
android:layout_marginTop="79dp"
android:text="get_location" />
<TextView
android:id="#+id/address"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/title"
android:layout_below="#+id/title"
android:layout_marginTop="135dp" />
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/title"
android:layout_below="#+id/title"
android:layout_marginTop="44dp"
android:text="LONGITUD" />
<TextView
android:id="#+id/textLong"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView1"
android:layout_below="#+id/textView1"
android:layout_marginTop="26dp" />
<TextView
android:id="#+id/textLat"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/title"
android:layout_below="#+id/title" />
</RelativeLayout>
DO PLEASE NOTE! i have added two global variables called LongHolder and LatHolder to pass the values of the GPS straight to the reverse geocoding. I believe they failed their purpose but if you need to test random selected Coordinates yourself, remember to remove them. THANK YOU

Can anybody tell me the xmls for this program

(ANDROID GPS)
actually i am new in android and since i am a c++ programmer so am facing some difficulty in this program which is to take the gps location of the android mobile and send it as sms to the given number. but since it is in java so please can someone tell me what the different XML for this program will be...i mean the string and main xmls
package com.adzz.gps;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.content.Context;
import android.telephony.SmsManager;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import android.view.View.OnClickListener;
public class MainActivity extends Activity {
String m;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
LocationManager manager= (LocationManager)
this.getSystemService(Context.LOCATION_SERVICE);
LocationListener listener =new LocationListener() {
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onLocationChanged(Location location) {
final String phoneNumber="9453603045";
double lat1=location.getLatitude();
Double d1= new Double(lat1);
double longi1=location.getLongitude();
Double d2=new Double(longi1);
m="latitude = "+ d1.toString() + "and latitude = "+ d2.toString();
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(phoneNumber, null, m, null, null);
TextView lat= (TextView) findViewById(R.id.lat);
TextView longi=(TextView) findViewById(R.id.longi);
lat.setText("latitude = "+lat1);
longi.setText("longitude ="+longi1);
}
};
manager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 25,
listener);
Button b= (Button) findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Toast toast=Toast.makeText(Main.this, m, 5000);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/lat"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp" />
<TextView
android:id="#+id/longi"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp" />
<Button
android:id="#id/button1"
android:layout_gravity="center"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
First you need to create main.xml in layout folder in res directory. This is the main layout which is loading in your Activity , take two TextView inside main.xml with id named as lat and longi. main.xml is given below.
<?xml version="1.0" encoding="utf-8"?>
<TextView
android:id="#+id/lat"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="195dp"
android:text="Lattitude" />
<TextView
android:id="#+id/longi"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView2"
android:layout_alignParentTop="true"
android:layout_marginTop="82dp"
android:text="Longitude" />

Android battery level

I have a problem with an application that sends coordinates via SMS.
When I added the battery level, the application stopped working after catching the fix.
(Coordinates not on display, but they are via SMS.)
Please help.
ZoltrixGPSActivity
package com.zoltrix.gps;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class ZoltrixGPSActivity extends Activity {
// Here I added a level of battery (1)
private TextView contentTxt;
private BroadcastReceiver mBatInfoReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context arg0, Intent intent) {
// TODO Auto-generated method stub
int level = intent.getIntExtra("level", 0);
contentTxt.setText(String.valueOf(level) + "%");
}
};
// end
TextView textLat;
TextView textLong;
TextView textAlt;
TextView textPro;
TextView textAcc;
TextView textSpeed;
public String onLocat;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Here I added a level of battery (2)
contentTxt = (TextView) this.findViewById(R.id.battery);
this.registerReceiver(this.mBatInfoReceiver, new IntentFilter(
Intent.ACTION_BATTERY_CHANGED));
// end
Button btn1 = (Button) findViewById(R.id.buttonExit);
btn1.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// exit
finish();
System.exit(0);
}
});
textLat = (TextView) findViewById(R.id.textLat);
textLong = (TextView) findViewById(R.id.textLong);
textAlt = (TextView) findViewById(R.id.textAlt);
textPro = (TextView) findViewById(R.id.textPro);
textAcc = (TextView) findViewById(R.id.textAcc);
textSpeed = (TextView) findViewById(R.id.textSpeed);
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
LocationListener ll = new mylocationlistener();
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, ll);
}
class mylocationlistener implements LocationListener {
public void onLocationChanged(Location location) {
if (location != null) {
double pLong = location.getLongitude();
double pLat = location.getLatitude();
double pAlt = location.getAltitude();
String PPro = location.getProvider();
float PAcc = location.getAccuracy();
float PSpeed = location.getSpeed();
textLat.setText(Double.toString(pLat));
textLong.setText(Double.toString(pLong));
textAlt.setText(Double.toString(pAlt));
textPro.setText(PPro);
textAcc.setText(Float.toString(PAcc));
textSpeed.setText(Double.toString(PSpeed));
Intent i = new Intent(ZoltrixGPSActivity.this,
SendSMSActivity.class);
i.putExtra("lon", Double.toString(pLong));
i.putExtra("lat", Double.toString(pLat));
i.putExtra("alt", Double.toString(pAlt));
i.putExtra("acc", Float.toString(PAcc));
i.putExtra("spe", Float.toString(PSpeed));
startActivity(i);
}
}
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
}
SendSMSActivity
package com.zoltrix.gps;
import android.app.Activity;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.view.View;
import android.widget.Button;
public class SendSMSActivity extends Activity {
Button btnSendSMS;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btnSendSMS = (Button) findViewById(R.id.btnSendSMS);
btnSendSMS.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v) {
Bundle extras = getIntent().getExtras();
String LON = extras.getString("lon");
String LAT = extras.getString("lat");
String ALT = extras.getString("alt");
String ACC = extras.getString("acc");
String SPE = extras.getString("spe");
sendSMS("510104727", "LON" + LON + "#" + "LAT" + LAT + "#"
+ "ALT" + ALT + "#" + "ACC" + ACC + "#" + "SPE" + SPE);
}
});
}
// ---sends an SMS message to another device---
private void sendSMS(String phoneNumber, String message) {
SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage(phoneNumber, null, message, null, null);
}
}
Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.zoltrix.gps"
android:versionCode="1"
android:versionName="1.2" >
<uses-sdk
android:minSdkVersion="4"
android:targetSdkVersion="8" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS" />
<uses-permission android:name="android.permission.RECEIVE_SMS" />
<uses-permission android:name="android.permission.SEND_SMS" />
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name" >
<activity
android:name="com.zoltrix.gps.SendSMSActivity"
android:label="#string/app_name" >
</activity>
<activity
android:name="com.zoltrix.gps.ZoltrixGPSActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Loyout
<?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:gravity="top"
android:orientation="vertical" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Latitude"
android:textAppearance="?android:attr/textAppearanceSmall" />
<TextView
android:id="#+id/textLat"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Longitude "
android:textAppearance="?android:attr/textAppearanceSmall" />
<TextView
android:id="#+id/textLong"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Alt"
android:textAppearance="?android:attr/textAppearanceSmall" />
<TextView
android:id="#+id/textAlt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="#+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Provider"
android:textAppearance="?android:attr/textAppearanceSmall" />
<TextView
android:id="#+id/textPro"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="#+id/textView5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Accuracy (m)" />
<TextView
android:id="#+id/textAcc"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="#+id/text344"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Speed (m/s)" />
<TextView
android:id="#+id/textSpeed"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="#+id/battery"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""
android:textAppearance="?android:attr/textAppearanceLarge" />
<Button
android:id="#+id/btnSendSMS"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Send" />
<Button
android:id="#+id/buttonExit"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Exit" />
</LinearLayout>
LogCat
http://pastebin.com/whhdHsyw
Try adding the android.permission.BATTERY_STATS permission to your code.
<uses-permission android:name="android.permission.BATTERY_STATS" />
// Put this Code into your MainActivity where you want to show level
private BroadcastReceiver mBatInfoReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context c, Intent i) {
int level = i.getIntExtra("level", 0);
ProgressBar pb = (ProgressBar) findViewById(R.id.progressbar);
pb.setProgress(level);
TextView tv = (TextView) findViewById(R.id.textfield);
tv.setText("Battery Level: " + Integer.toString(level) + "%");
}
};
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
registerReceiver(mBatInfoReceiver, new IntentFilter(
Intent.ACTION_BATTERY_CHANGED));
}
// Please Add the given below code into manifest:
<uses-permission android:name="android.permission.BATTERY_STATS" />

Categories

Resources