Hi I posted a question concerning the same topic a while ago, after following your advices I can feel that I'm getting closed to solving my problem. The App does is now crashing as I click on the button with the following error message in the monitor:
FATAL EXCEPTION: main
Process: com.example.apple.myapp1, PID: 10081
java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:255)
at java.util.ArrayList.get(ArrayList.java:308)
at com.example.apple.myapp1.MainActivity$1.onClick(MainActivity.java:62)
MainActivity.java
package com.example.apple.myapp1;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;
import java.util.Locale;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.location.Address;
import android.location.Geocoder;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.telephony.gsm.GsmCellLocation;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.view.View.OnClickListener;
public class MainActivity extends Activity {
double lats, lons;
Geocoder geocoder;
double lat = lats;
double lon = lons;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btnGetLocation = (Button) findViewById(R.id.button1);
btnGetLocation.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
ProgressDialog mProgressDialog = new ProgressDialog(MainActivity.this);
mProgressDialog.setMessage("Fetching location...");
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
mProgressDialog.show();
geocoder = new Geocoder(MainActivity.this, Locale.getDefault());
List<Address> addresses = null;
try {
addresses = geocoder.getFromLocation(lat, lon, 1);
} catch (IOException e) {
e.printStackTrace();
}
if (addresses != null) {
String address = addresses.get(0).getAddressLine(0);
String city = addresses.get(0).getLocality();
String state = addresses.get(0).getAdminArea();
String country = addresses.get(0).getCountryName();
String postalCode = addresses.get(0).getPostalCode();
String knownName = addresses.get(0).getFeatureName();
mProgressDialog.dismiss();
TextView cellText = (TextView) findViewById(R.id.cellText);
cellText.setText(address);
} else {
mProgressDialog.dismiss();
TextView cellText = (TextView) findViewById(R.id.cellText);
cellText.setText("Error");
}
}
});
}
}
activity_main.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" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Please click the button below to get your location" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Click Me" />
<TextView
android:id="#+id/cellText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="" />
<TextView
android:id="#+id/lacationText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="" />
</LinearLayout>
in the condition if (addresses != null) { } you should also check for the length of the addresses, since there might be 0.
if (addresses != null && addresses.size() > 0) {
String address = addresses.get(0).getAddressLine(0);
String city = addresses.get(0).getLocality();
String state = addresses.get(0).getAdminArea();
String country = addresses.get(0).getCountryName();
String postalCode = addresses.get(0).getPostalCode();
String knownName = addresses.get(0).getFeatureName();
mProgressDialog.dismiss();
TextView cellText = (TextView) findViewById(R.id.cellText);
cellText.setText(address);
} else {
mProgressDialog.dismiss();
TextView cellText = (TextView) findViewById(R.id.cellText);
cellText.setText("Error");
}
if it wasn't able to find at least one address you should consider showing the user an empty state.
It also seems like you forgot to initialize your latitude and longitude before calling addresses = geocoder.getFromLocation(lat, lon, 1);
To properly initialize this, do the following:
Location location = intent.getParcelableExtra(__YOUR_PACKAGE_NAME__ + ".LOCATION_DATA_EXTRA");
lat = location.getLatitude();
lon = location.getLongitude();
If you need any more help check out this page from android. It should hold all information you need.
EDIT:
I kind of assumed you we're further in the process, but it seems you have only tried to get the location of a latLong position, which you have never obtained. To achieve obtaining the address you will have to have the user's lcoation first.
Again, the page mentioned above should explain everything you need to obtain the location, but make sure of the following:
1. Have the permission to access the user's location (for Android 6+ use Runtime permissions)
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.google.android.gms.location.sample.locationupdates" >
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
</manifest>
2. Get an instance of the GoogleApi and ave your activity implement some callbacks
For the Callbacks
public class YourActivity extends AppCompatActivity implements
ConnectionCallbacks, OnConnectionFailedListener
Then in your OnCreate() create an instance of GoogleApiClient.
protected GoogleApiClient mGoogleApiClient;
public void onCreate(Bundle savedInstanceState) {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mGoogleApiClient.connect();
}
3. Obtain the location from the GoogleApiClient
Do this by implementing the callbacks properly.
/**
* Represents a geographical location.
*/
protected Location mLastLocation;
#Override
public void onConnected(Bundle connectionHint) {
// Gets the best and most recent location currently available, which may be null
// in rare cases when a location is not available.
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (mLastLocation != null) {
// Determine whether a Geocoder is available.
if (!Geocoder.isPresent()) {
Toast.makeText(this, "no geocoder available", Toast.LENGTH_LONG).show();
return;
}
}
}
4. Now obtain the lat long and try to obtain the address as attempted before.
lat = mLastLocation.getLatitude();
lon = mLastLocation.getLongitude();
geocoder = new Geocoder(MainActivity.this, Locale.getDefault());
List<Address> addresses = null;
try {
addresses = geocoder.getFromLocation(lat, lon, 1);
} catch (IOException e) {
e.printStackTrace();
}
This should be enough to obtain the actual adress of the device and ask the geocoder for the addresses. I altered the example a bit to simplify for this question. Google's example handles fetching the address a bit more clean. Note that you will also have to disconnect the GoogleApi when stopping your activity and such. Again I recommend reading the entire Tutorial page. You can find en example of their implementation on this page on GitHub
Related
So I did a bluetooth scanner app in android studio and I want to store data in a csv. the problem is that I want to remove the button and the app to keep scanning and write in csv. Right now it scans automatically but I have to press the button in order to create and write in csv. Can you help me with implementing a method for automatically writing? I tried using the btn.setPressed(true) and btn.performClick() but it didn't work. Here is MainActivity and activity_xm. The manifest has all permissions and in gradle.app has minSDK 28 AND targetSDK 32.
package com.example.blutut;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
Bluetooth bluetooth = new Bluetooth();
private BluetoothAdapter BTAdapter = BluetoothAdapter.getDefaultAdapter();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
registerReceiver(receiver, new IntentFilter(BluetoothDevice.ACTION_FOUND));
Button btn = findViewById(R.id.btnDetect);
}
private final BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
int rssi = intent.getShortExtra(BluetoothDevice.EXTRA_RSSI, Short.MIN_VALUE);
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
String name = device.getName();
TextView txt = findViewById(R.id.textView);
txt.setText(txt.getText() + name + " => " + rssi + "dBm\n");
String entry = "\n" + String.format("%d", rssi);
try {
File path = new File("/storage/emulated/0/Download");
File file = new File(path + "/bluetooth.csv");
FileOutputStream f = new FileOutputStream(file, true);
try {
f.write(entry.getBytes());
f.flush();
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
};
public void btnClick(View view) {
if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.BLUETOOTH_SCAN) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
BTAdapter.startDiscovery();
return;
}
}
}
/// activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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"
tools:context=".MainActivity">
<Button
android:id="#+id/btnDetect"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="btnClick"
android:text="Button"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/btnDetect" />
I wanted to ask you if you know how to pass the value of a variable in PHP into an EditText in android studio?
Let me explain better, I have an android application in which there are 2 forms in which information is entered and saved in a MySQL database.
The database has a table for the first form and a table for the second form, these two tables are linked and then the second table has an external key that is associated with the primary key of the first table that is inserted with the first form.
What I can not do is that once I entered the data in the first table and I got the primary key through mysqli Insert_id (), I do not know how to pass the value of the variable in $ People_id within an edittext present in the second form .
Below I leave my android code, there is a problem in the code of the second form because the data entered does not arrive to the PHP script.
So by summarizing the problem, does anyone know how to pass the primary key obtained with mysql insert id in the php file and put this value in the EditText present in the second form?
The first form save data into table 'Persone', the fields in this table are :
id (PK)
Name and Surname (VARCHAR)
The second form saves the data in the table 'Persone2', the fields in this table are :
idP2 (PK)
FK_persone (Foreign Key)
Squadra, Ruolo and Numero_maglia (VARCHAR)
PS. In the second form the data are saved in the table 'People2', the fields 'Ruolo', 'Squadra' and 'Numero_maglia' are entered by the user, but the field 'id_People2' must already be inserted (the variable value must be there $ _SESSION ['People_id'] = $ People_id; value I get from the PHP script of the first form).
The first form works, idata are saved in the DataBase, but the second Form does not work, there is a problem on the android studio .JAVA file, but I do not understand what problem :(
the java file of the first form is :
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.widget.Toast;
import java.net.FileNameMap;
import java.util.HashMap;
public class Activity1 extends AppCompatActivity {
private EditText nome, cognome;
private Button registrazione, login;
//REGISTRAZIONE
String F_Name_Holder, L_Name_Holder;
String finalResult ;
String HttpURLRegister = "http://provaord.altervista.org/NEW/RRR.php";
Boolean CheckEditText ;
ProgressDialog progressDialog;
HashMap<String,String> hashMap = new HashMap<>();
HttpParse httpParse = new HttpParse();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_1);
nome = (EditText)findViewById(R.id.editText6);
cognome = (EditText)findViewById(R.id.editText7);
registrazione = (Button)findViewById(R.id.button5);
login = (Button)findViewById(R.id.button3);
registrazione.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Checking whether EditText is Empty or Not
CheckEditTextIsEmptyOrNot();
if(CheckEditText){
// If EditText is not empty and CheckEditText = True then this block will execute.
UserRegisterFunction(F_Name_Holder,L_Name_Holder);
}
else {
// If EditText is empty then this block will execute .
Toast.makeText(Activity1.this, "Please fill all form fields.", Toast.LENGTH_LONG).show();
}
}
});
}
//REGISTRAZIONE
public void CheckEditTextIsEmptyOrNot(){
F_Name_Holder = nome.getText().toString();
L_Name_Holder = cognome.getText().toString();
if(TextUtils.isEmpty(F_Name_Holder) || TextUtils.isEmpty(L_Name_Holder) )
{
CheckEditText = false;
}
else {
CheckEditText = true ;
}
}
//REGISTRATION
#RequiresApi(api = Build.VERSION_CODES.CUPCAKE)
public void UserRegisterFunction(final String Nome, final String Cognome){
class UserRegisterFunctionClass extends AsyncTask<String,Void,String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = ProgressDialog.show(Activity1.this,"Loading Data",null,true,true);
}
#Override
protected void onPostExecute(String httpResponseMsg) {
super.onPostExecute(httpResponseMsg);
progressDialog.dismiss();
Toast.makeText(Activity1.this,httpResponseMsg.toString(), Toast.LENGTH_LONG).show();
if(httpResponseMsg.equalsIgnoreCase("Registration Successfully")){
finish();
Intent intent = new Intent(Activity1.this, Activity2.class);
startActivity(intent);
}
}
//REGISTRATION
#Override
protected String doInBackground(String... params) {
hashMap.put("Nome",params[0]);
hashMap.put("Cognome",params[1]);
finalResult = httpParse.postRequest(hashMap, HttpURLRegister);
return finalResult;
}
}
UserRegisterFunctionClass userRegisterFunctionClass = new UserRegisterFunctionClass();
userRegisterFunctionClass.execute(Nome,Cognome);
}
}
The java file of the second form is :
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.widget.Toast;
import java.net.FileNameMap;
import java.util.HashMap;
public class Activity2 extends AppCompatActivity {
private EditText id, squadra, ruolo, numeromaglia;
private Button registrazionee;
//REGISTRAZIONE
String Squadra_Holder, Ruolo_Holder, Numero_Maglia_Holder;
String finalResult ;
String HttpURLRegister = "http://provaord.altervista.org/NEW/R22.php";
Boolean CheckEditText ;
ProgressDialog progressDialog;
HashMap<String,String> hashMap = new HashMap<>();
HttpParse httpParse = new HttpParse();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_2);
// id = (EditText)findViewById(R.id.editText6);
squadra = (EditText)findViewById(R.id.editText7);
ruolo = (EditText)findViewById(R.id.editText3);
numeromaglia = (EditText)findViewById(R.id.editText4);
registrazionee = (Button)findViewById(R.id.button55);
registrazionee.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Checking whether EditText is Empty or Not
CheckEditTextIsEmptyOrNot();
if(CheckEditText){
// If EditText is not empty and CheckEditText = True then this block will execute.
UserRegisterFunction(Squadra_Holder, Ruolo_Holder, Numero_Maglia_Holder);
}
else {
// If EditText is empty then this block will execute .
Toast.makeText(Activity2.this, "Please fill all form fields.", Toast.LENGTH_LONG).show();
}
}
});
}
//REGISTRAZIONE
public void CheckEditTextIsEmptyOrNot(){
Squadra_Holder = squadra.getText().toString();
Ruolo_Holder = ruolo.getText().toString();
Numero_Maglia_Holder = numeromaglia.getText().toString();
if(TextUtils.isEmpty(Squadra_Holder) || TextUtils.isEmpty(Ruolo_Holder) || TextUtils.isEmpty(Numero_Maglia_Holder) )
{
CheckEditText = false;
}
else {
CheckEditText = true ;
}
}
//REGISTRATION
#RequiresApi(api = Build.VERSION_CODES.CUPCAKE)
public void UserRegisterFunction(final String Squadra, final String Ruolo, final String Numero_maglia){
class UserRegisterFunctionClass extends AsyncTask<String,Void,String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = ProgressDialog.show(Activity2.this,"Loading Data",null,true,true);
}
#Override
protected void onPostExecute(String httpResponseMsg) {
super.onPostExecute(httpResponseMsg);
progressDialog.dismiss();
Toast.makeText(Activity2.this,httpResponseMsg.toString(), Toast.LENGTH_LONG).show();
if(httpResponseMsg.equalsIgnoreCase("Registration Successfully")){
finish();
Intent intent = new Intent(Activity2.this, Activity3.class);
startActivity(intent);
}
}
//REGISTRATION
#Override
protected String doInBackground(String... params) {
hashMap.put("Squadra",params[0]);
hashMap.put("Ruolo",params[1]);
hashMap.put("Numero_maglia",params[2]);
finalResult = httpParse.postRequest(hashMap, HttpURLRegister);
return finalResult;
}
}
UserRegisterFunctionClass userRegisterFunctionClass = new UserRegisterFunctionClass();
userRegisterFunctionClass.execute(Squadra, Ruolo, Numero_maglia);
}
}
The java code for the HttpParse.java file is this:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
/**
* Created by Juned on 3/3/2017.
*/
public class HttpParse {
String FinalHttpData = "";
String Result ;
BufferedWriter bufferedWriter ;
OutputStream outputStream ;
BufferedReader bufferedReader ;
StringBuilder stringBuilder = new StringBuilder();
URL url;
public String postRequest(HashMap<String, String> Data, String HttpUrlHolder) {
try {
url = new URL(HttpUrlHolder);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setReadTimeout(14000);
httpURLConnection.setConnectTimeout(14000);
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoInput(true);
httpURLConnection.setDoOutput(true);
outputStream = httpURLConnection.getOutputStream();
bufferedWriter = new BufferedWriter(
new OutputStreamWriter(outputStream, "UTF-8"));
bufferedWriter.write(FinalDataParse(Data));
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
if (httpURLConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
bufferedReader = new BufferedReader(
new InputStreamReader(
httpURLConnection.getInputStream()
)
);
FinalHttpData = bufferedReader.readLine();
}
else {
FinalHttpData = "Something Went Wrong";
}
} catch (Exception e) {
e.printStackTrace();
}
return FinalHttpData;
}
public String FinalDataParse(HashMap<String,String> hashMap2) throws UnsupportedEncodingException {
for(Map.Entry<String,String> map_entry : hashMap2.entrySet()){
stringBuilder.append("&");
stringBuilder.append(URLEncoder.encode(map_entry.getKey(), "UTF-8"));
stringBuilder.append("=");
stringBuilder.append(URLEncoder.encode(map_entry.getValue(), "UTF-8"));
}
Result = stringBuilder.toString();
return Result ;
}
}
The PHP file for the first form:
<?php
session_start();
if($_SERVER['REQUEST_METHOD']=='POST'){
include 'C.php';
$con = mysqli_connect($HostName,$HostUser,$HostPass,$DatabaseName);
$Nome = $_POST['Nome'];
$Cognome = $_POST['Cognome'];
$CheckSQL = "SELECT * FROM Persone WHERE Nome = '$Nome'";
$check = mysqli_fetch_array(mysqli_query($con,$CheckSQL));
if(isset($check)){
echo 'Utente già registrato';
}
else{
$Sql_Query = "INSERT INTO Persone (Nome, Cognome) values ('$Nome','$Cognome')";
if(mysqli_query($con,$Sql_Query))
{
echo 'Registration Successfully';
$People_id = mysqli_insert_id($con);
$_SESSION ['People_id'] = $People_id;
}
else
{
echo 'Something went wrong';
}
}
mysqli_close($con);
}
?>
The PHP file for the second form:
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
session_start();
print_r($_POST);
if($_SERVER['REQUEST_METHOD']=='POST'){
include 'C.php';
$con = mysqli_connect($HostName,$HostUser,$HostPass,$DatabaseName);
$Squadra = $_POST['Squadra'];
$Ruolo = $_POST['Ruolo'];
$Numero_maglia = $_POST['Numero_maglia'];
$CheckSQL = "SELECT * FROM Persone, Persone2 WHERE Persone2.FK_persone = '" . ($_SESSION ['People_id']). "'";;
$check = mysqli_fetch_array(mysqli_query($con,$CheckSQL));
if(isset($check)){
echo 'Utente già registrato';
}
else{
$Sql_Query = "INSERT INTO Persone2 (FK_persone, Squadra, Ruolo, Numero_maglia) values ('" . ($_SESSION ['People_id']). "','$Squadra', '$Ruolo', '$Numero_maglia')";
if(mysqli_query($con,$Sql_Query))
{
echo 'Registration Successfully';
}
else
{
echo 'Something went wrong';
}
}
mysqli_close($con);
}
?>
The file XML to second form :
<android.support.constraint.ConstraintLayout 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"
tools:context="com.example.bruzi.myord.Activity2">
<EditText
android:id="#+id/editText6"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="32dp"
android:layout_marginStart="32dp"
android:layout_marginTop="32dp"
android:ems="10"
android:hint="ID_People2"
android:inputType="textPersonName"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<EditText
android:id="#+id/editText7"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="32dp"
android:layout_marginStart="32dp"
android:layout_marginTop="32dp"
android:ems="10"
android:hint="Squadra"
android:inputType="textPersonName"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/editText6" />
<EditText
android:id="#+id/editText3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="32dp"
android:layout_marginStart="32dp"
android:layout_marginTop="32dp"
android:ems="10"
android:hint="Ruolo"
android:inputType="textPersonName"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/editText7" />
<EditText
android:id="#+id/editText4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="32dp"
android:layout_marginStart="32dp"
android:layout_marginTop="32dp"
android:ems="10"
android:hint="Numero maglia"
android:inputType="textPersonName"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/editText3" />
<Button
android:id="#+id/button55"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_marginBottom="32dp"
android:layout_marginEnd="32dp"
android:layout_marginStart="32dp"
android:layout_marginTop="32dp"
android:background="#android:color/holo_blue_light"
android:text="Registrazione"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/editText4" />
</android.support.constraint.ConstraintLayout>
It is a long journey, here are the steps:
First: You need to make sure that the php server returns the values needed in xml or json format, you can do so by creating a web service if you want.
Second: From android application you need to communicate with the web service using http post or get.
Third: The response coming back from the web service should be parsed by your android app. the parser will read the response and give you the needed fields values (there are many parsing packages available)
Forth: after getting the values, you can choose to store them in a preference or sqlite table (for future use) or directly send them to the next activity using intent.
When mastering this technique you will be able to make any kind of mobile app that needs a back-end server.
Good luck
I have been struggling to fix this issue, but nothing I have found online has worked. I have gotten an unrestricted key for my project, but the map will still not display correctly. The status that is returned is considered OK, but nothing displays. I have also made sure to enable both APIs for that key. Below are some pictures showing what it looks like followed by my code. If I need to include any other code just comment on what you need. I'm also using the Google Direction Library found here https://github.com/akexorcist/Android-GoogleDirectionLibrary
After the button is clicked, it goes to the correct area, but everything is grey so I believe there is a problem with my google maps.
Dependencies
dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
compile 'com.android.support:appcompat-v7:24.2.1'
compile 'com.android.support:design:24.2.1'
compile 'com.android.support:recyclerview-v7:24.2.1'
compile 'com.akexorcist:googledirectionlibrary:1.0.5'
testCompile 'junit:junit:4.12'
}
XML Fragment
<?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_directions"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="<did not show my package>.Directions">
<fragment
android:id="#+id/map_fragment"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="<did not show my package>.MapsActivity" />
<Button
android:id="#+id/get_directions_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:text="Get Directions" />
</RelativeLayout>
Directions.java
import android.graphics.Color;
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.support.v4.app.FragmentActivity;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import com.akexorcist.googledirection.DirectionCallback;
import com.akexorcist.googledirection.GoogleDirection;
import com.akexorcist.googledirection.constant.TransportMode;
import com.akexorcist.googledirection.model.Direction;
import com.akexorcist.googledirection.model.Route;
import com.akexorcist.googledirection.util.DirectionConverter;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.LatLngBounds;
import com.google.android.gms.maps.model.MarkerOptions;
import java.util.ArrayList;
public class Directions extends AppCompatActivity implements OnMapReadyCallback,
View.OnClickListener, DirectionCallback
{
private GoogleMap googleMap;
private LatLng origin = new LatLng(29.572813, -97.984900);
private LatLng destination;
private Button get_directions_btn;
private String serverKey = "<server key not shown>";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_directions);
// origin = new LatLng(29.572813, -97.984900);
Bundle bundle = getIntent().getExtras();
double destLatitude = bundle.getDouble("latitude");
double destLongitude = bundle.getDouble("longitude");
Log.d("Latitude", "Latitude is: " + destLatitude);
Log.d("Longitude", "Longitude is:" + destLongitude);
destination = new LatLng(destLatitude, destLongitude);
get_directions_btn = (Button) findViewById(R.id.get_directions_btn);
get_directions_btn.setOnClickListener(this);
((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map_fragment)).getMapAsync(this);
}
public void onMapReady(GoogleMap googleMap) {
this.googleMap = googleMap;
}
public void onClick(View v) {
int id = v.getId();
if (id == R.id.get_directions_btn) {
requestDirection();
}
}
public void requestDirection() {
Log.d("RequestOrigin", "Origin inside request: " + origin);
Log.d("RequestDestination", "Destination inside request: " + destination);
Snackbar.make(get_directions_btn, "Direction Requesting...", Snackbar.LENGTH_SHORT).show();
GoogleDirection.withServerKey(serverKey)
.from(origin)
.to(destination)
.transportMode(TransportMode.DRIVING)
.execute(this);
}
public void onDirectionSuccess(Direction direction, String rawBody) {
Log.d("Status","Direction Status is:" +direction.getStatus());
Snackbar.make(get_directions_btn, "Success with status : " + direction.getStatus(), Snackbar.LENGTH_SHORT).show();
if (direction.isOK()) {
Route route = direction.getRouteList().get(0);
Log.d("Route ", "Route is: " + route);
Log.d("Origin Marker", "Origin Marker: " + origin);
Log.d("Destination Marker", "Destination Marker: " + destination);
googleMap.addMarker(new MarkerOptions().position(origin));
googleMap.addMarker(new MarkerOptions().position(destination));
ArrayList<LatLng> directionPositionList = route.getLegList().get(0).getDirectionPoint();
googleMap.addPolyline(DirectionConverter.createPolyline(this, directionPositionList, 5, Color.RED));
setCameraWithCoordinationBounds(route);
get_directions_btn.setVisibility(View.GONE);
}
else{
Log.d("Status","Direction Status is:" +direction.getStatus());
Snackbar.make(get_directions_btn, direction.getStatus(), Snackbar.LENGTH_SHORT).show();
}
}
public void onDirectionFailure(Throwable t) {
Snackbar.make(get_directions_btn, t.getMessage(), Snackbar.LENGTH_SHORT).show();
}
private void setCameraWithCoordinationBounds(Route route) {
LatLng southwest = route.getBound().getSouthwestCoordination().getCoordination();
LatLng northeast = route.getBound().getNortheastCoordination().getCoordination();
LatLngBounds bounds = new LatLngBounds(southwest, northeast);
googleMap.animateCamera(CameraUpdateFactory.newLatLngBounds(bounds, 100));
}
}
Manifest meta data
<meta-data android:name="com.google.android.geo.API_KEY"
android:value="#string/google_maps_key"/>
Manifest Permissions
<uses-permission android:name="android.permission.GET_ACCOUNTS"/>
<uses-permission android:name="android.permission.READ_PROFILE"/>
<uses-permission android:name="android.permission.READ_CONTACTS"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.INTERNET"/>
Anyway you can try to apply custom style to Google Map. For map style JSON preparing you can use Styling Wizard and save JSON file with style description (e.g. map_style.json) into res/raw folder. And than apply custom style in onMapReady() callback:
public class MainActivity extends AppCompatActivity implements OnMapReadyCallback {
private GoogleMap mGoogleMap;
private MapFragment mapFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mapFragment = (MapFragment) getFragmentManager()
.findFragmentById(R.id.map_fragment);
mapFragment.getMapAsync(this);
}
#Override
public void onMapReady(GoogleMap googleMap) {
mGoogleMap = googleMap;
try {
// Customise the styling of the base map using a JSON object defined
// in a raw resource file.
boolean success = mGoogleMap.setMapStyle(
MapStyleOptions.loadRawResourceStyle(
this, R.raw.map_style));
if (!success) {
Log.e(TAG, "Style parsing failed.");
}
} catch (Resources.NotFoundException e) {
Log.e(TAG, "Can't find style. Error: ", e);
}
}
}
The following code is from a Google maps activity to find a particular location on user input.It works fine but crashes when there is no persistent internet connection.Please help me fix this problem.
The MainActivity.java class looks like this:
import android.location.Address;
import android.location.Geocoder;
import android.os.AsyncTask;
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.EditText;
import android.widget.Toast;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import java.io.IOException;
import java.util.List;
public class MainActivity
extends FragmentActivity {
GoogleMap googleMap;
MarkerOptions markerOptions;
LatLng latLng;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SupportMapFragment supportMapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
// Getting a reference to the map
googleMap = supportMapFragment.getMap();
// Getting reference to btn_find of the layout activity_main
Button btn_find = (Button) findViewById(R.id.btn_find);
// Defining button click event listener for the find button
OnClickListener findClickListener = new OnClickListener() {
#Override
public void onClick(View v) {
EditText etLocation = (EditText) findViewById(R.id.et_location);
// Getting user input location
String location = etLocation.getText().toString();
if (location != null && !location.equals("")) {
new GeocoderTask().execute(location);
}
}
};
// Setting button click event listener for the find button
btn_find.setOnClickListener(findClickListener);
}
// An AsyncTask class for accessing the GeoCoding Web Service
private class GeocoderTask
extends AsyncTask<String, Void, List<Address>> {
#Override
protected List<Address> doInBackground(String... locationName) {
// Creating an instance of Geocoder class
Geocoder geocoder = new Geocoder(getBaseContext());
List<Address> addresses = null;
try {
// Getting a maximum of 3 Address that matches the input text
addresses = geocoder.getFromLocationName(locationName[0], 3);
} catch (IOException e) {
e.printStackTrace();
}
return addresses;
}
#Override
protected void onPostExecute(List<Address> addresses) {
if (addresses == null || addresses.size() == 0) {
Toast.makeText(getBaseContext(), "No Location found", Toast.LENGTH_SHORT).show();
}
// Clears all the existing markers on the map
googleMap.clear();
// Adding Markers on Google Map for each matching address
for (int i = 0; i < addresses.size(); i++) {
Address address = (Address) addresses.get(i);
// Creating an instance of GeoPoint, to display in Google Map
latLng = new LatLng(address.getLatitude(), address.getLongitude());
String addressText = String.format("%s, %s", address.getMaxAddressLineIndex() > 0 ? address.getAddressLine(0) : "", address.getCountryName());
markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title(addressText);
googleMap.addMarker(markerOptions);
// Locate the first location
if (i == 0) {
googleMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
}
}
}
}
}
And this is my crash report:
02-25 17:17:42.157 4312-4312/aravindaby.myapp123 E/test: Exception
02-25 17:17:42.157 4312-4312/aravindaby.myapp123 E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.NullPointerException
at aravindaby.myapp123.MainActivity$GeocoderTask.onPostExecute(MainActivity.java:100)
at aravindaby.myapp123.MainActivity$GeocoderTask.onPostExecute(MainActivity.java:72)
at android.os.AsyncTask.finish(AsyncTask.java:631)
at android.os.AsyncTask.access$600(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4793)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:808)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:575)
at dalvik.system.NativeStart.main(Native Method)
In the case of no internet connection, address is null. So after showing Toast message, you should return the control.
if(addresses==null || addresses.size()==0){
Toast.makeText(getBaseContext(), "No Location found", Toast.LENGTH_SHORT).show();
return;
}
I've created an application in which, when I click a button, it gives me my gps coordinates. In the simulator it works with no problem, but when I've tried it on a mobile phone a had the next 2 scenarios: when I had the GPS activated, nothing happened, and when i didn't had the GPS connected, it said "Gps Disabled"
Here is my code so far:
This is the .java file: (Saver.java):
package com.example.lifesaver;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class Saver extends Activity {
Button b;
Location newLocation = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_saver);
b = (Button) findViewById(R.id.button1);
// We use LocationManager class to obtain GPS locations
LocationManager mlocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
LocationListener mlocListener = new MyLocationListener();
mlocManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 0, 0, mlocListener);
b.setOnClickListener(new OnClickListener(){
public void onClick(View v)
{
if (newLocation != null) {
String Text = "Current location is: " + "Latitud = "
+ newLocation.getLatitude() + "Longitud = "
+ newLocation.getLongitude();
Toast.makeText(getApplicationContext(), Text,
Toast.LENGTH_SHORT).show();
}
}
});
}
//MyLocationListener class
public class MyLocationListener implements LocationListener
{
public void onLocationChanged(Location loc)
{
newLocation = loc;
}
public void onProviderDisabled(String provider)
{
Toast.makeText(getApplicationContext(), "Gps Disabled", Toast.LENGTH_SHORT).show();
}
public void onProviderEnabled(String provider)
{
Toast.makeText(getApplicationContext(), "Gps Enabled", Toast.LENGTH_SHORT).show();
}
public void onStatusChanged(String provider, int status, Bundle extras)
{
}
}
}
And the .xml file(activity_saver.xml):
<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=".Saver" >
<Button
android:id="#+id/button1"
android:layout_width="60dp"
android:layout_height="60dp"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:background="#drawable/circle"
android:onClick="onClick"/>
</RelativeLayout>
Also, i've added this in the AndroidManifest.xml file:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION">
</uses-permission>
Are you trying to turn on GPS programmatically ?
It won't work above versions 4.0. You have to turn it on manually.
Use my code :-
Android - How to get the user current location every time based on sim Network
You have to wait for the GPS to get a fix. onLocationChanged may not be triggered for several minutes from a cold start. If you are inside a building you may never get a fix. There is no such facility as 'get my position via GPS immediately'.