Data transfer using Bluetooth in android - java

I am developing an application in which first I have to search available Bluetooth devices and make connection. I have done this task. After this, one new Activity opens in which there is one Edittext and one Button. I have developed the below code. It is not giving any output.
I am passing data using MAC address of connected device.
java file...
import java.io.IOException;
import java.io.OutputStream;
import java.util.UUID;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.ContentValues;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
#SuppressLint("NewApi")
public class NewMessage extends Activity {
Button btn;
EditText et;
String message1="Hello";//on button click by default
BluetoothAdapter mBluetoothAdapter1 = null;;
// BluetoothAdapter mBluetoothAdapter;
public static String MacAddress;
#Override
public void onCreate(Bundle mSavedInstanceState) {
super.onCreate(mSavedInstanceState);
setContentView(R.layout.message);
btn = (Button) findViewById(R.id.btn);
et = (EditText) findViewById(R.id.et);
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
mBluetoothAdapter1 = BluetoothAdapter.getDefaultAdapter();
byte[] toSend=message1.getBytes();
try
{
final UUID applicationUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
BluetoothDevice device=mBluetoothAdapter1.getRemoteDevice(MacAddress);
BluetoothSocket socket=device.createInsecureRfcommSocketToServiceRecord(applicationUUID);
OutputStream mmout=socket.getOutputStream();
mmout.write(toSend);
mmout.flush();
mmout.close();
socket.close();
Toast.makeText(getBaseContext(), MacAddress, 10000).show();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
/*private void sendDataToPairedDevice(String message ,BluetoothDevice device){
byte[] toSend = message.getBytes();
try
{
BluetoothSocket socket = device.createInsecureRfcommSocketToServiceRecord(applicationUUID);
OutputStream mmOutStream = socket.getOutputStream();
mmOutStream.write(toSend);
// Your Data is sent to BT connected paired device ENJOY.
} catch (IOException e) {
e.printStackTrace();
}
}*/
}
xml file
<?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" >
<EditText
android:id="#+id/et"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="#string/hint">
<requestFocus />
</EditText>
<Button
android:id="#+id/btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/send" />
</LinearLayout>
Please do help me...
Here is my code, which has the problem..
public void onClick(View v) {
// TODO Auto-generated method stub
mBluetoothAdapter1 = BluetoothAdapter.getDefaultAdapter();
byte[] toSend=message1.getBytes();
try
{
final UUID applicationUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
BluetoothDevice device=mBluetoothAdapter1.getRemoteDevice(MacAddress);
BluetoothSocket socket=device.createInsecureRfcommSocketToServiceRecord(applicationUUID);
OutputStream mmout=socket.getOutputStream();
mmout.write(toSend);
mmout.flush();
mmout.close();
socket.close();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});

This doesn't answer your question directly but one thing I am noticing is that you have 10000 as your duration parameter for Toast.makeText(), which is invalid. It only accepts Toast.LENGTH_SHORT or Toast.LENGTH_LONG, which are actually just 0 or 1. Check the docs: http://developer.android.com/reference/android/widget/Toast.html
[EDIT]
Another error I see in your code is you pass an empty String to getRemoteDevice. Try doing getRemoteDevice("00001101-0000-1000-8000-00805F9B34FB") and see what happens. Again, read the docs: http://developer.android.com/reference/android/bluetooth/BluetoothAdapter.html#getRemoteDevice(java.lang.String)

Include the connect function.
BluetoothSocket socket=device.createInsecureRfcommSocketToServiceRecord(applicationUUID);
socket.connect(); // here
OutputStream mmout=socket.getOutputStream();

Related

how to keep scanning and writing in csv without pressing the button? Bluetooth Adapter

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" />

Android can't send PrintWriter message twice in socket with Java. It is also possible instead of sending me a Java code to send a Python code

I created a code that sends commands to a server I wrote using Python. The code only works once (the server receives what I sent the first time) but the second time it seems that nothing is sent because the server does not receive new information it keeps waiting for new information. My code:
StringBuilder Data = new StringBuilder(); // The Data to send
public void Send(View view) {
Thread send = new Thread() {
#Override
public void run() {
try {
Socket socket = new Socket("20.7.65.2", 6398); // Create connection to the server
OutputStream output = socket.getOutputStream(); // Get the key to output to server
PrintWriter writer = new PrintWriter(output, true);
writer.println(Data.toString()); // Send the data
Data.setLength(0); // Delete "Data" contant
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
};
send.start();
}
public void Continue(View view) {
Data.append("Hello from client"); // Append to "Data"
Send(null); // Run the send functionn (again)
}
}
My Python Server:
import socket, time
soc = socket.socket()
soc.bind((socket.gethostname(), 6398))
soc.listen(5)
(client, (ipNum, portNum)) = soc.accept()
print("Client connected")
while True:
message = client.recv(1024).decode()
if(message != ""):
print(message)
time.sleep(0.1)
In short, I try to run the run function twice. The first time it sends to the server and it receives the information, and the second time the server is still waiting for the information and not receiving what I sent again. Maybe it's because he's not available to receive all messages sent to him from all clients
It is also possible instead of sending me a Java code to send a Python code that will work and receive all messages from all clients
In your code, the server is only accepting a cnnection once and then it recieves from same client. But according to your question, I think your server should be able to listen to mulitple clients hence, you could use multithreading in the server. Instead of threading the client, I used button which when clicked connects with server. I also can't understand the need of threading the client. If you think, some changes are required in the answer, you could comment.
this is python server
import socket, time
import threading
soc = socket.socket()
# print(socket.)
soc.bind(("192.168.1.5", 6398))
soc.listen(5)
def info(client):
message = client.recv(1024).decode()
if(message != ""):
print(message)
return
while True:
(client, (ipNum, portNum)) = soc.accept()
print("Client connected")
threading.Thread(target=info,args=(client,)).start()
MainActivity.java
package com.example.myapplication;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
public class MainActivity extends AppCompatActivity {
StringBuilder Data = new StringBuilder(); // The Data to send
private Button btn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn= findViewById(R.id.connectBtn);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Continue();
}
});
}
public void Send() {
Thread send = new Thread() {
#Override
public void run() {
try {
Socket socket = new Socket("192.168.1.5", 6398); // Create connection to the server
OutputStream output = socket.getOutputStream(); // Get the key to output to server
PrintWriter writer = new PrintWriter(output, true);
writer.println(Data.toString()); // Send the data
Data.setLength(0); // Delete "Data" contant
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
};
send.start();
}
public void Continue() {
Data.append("Hello from client"); // Append to "Data"
Send(); // Run the send functionn (again)
}
}
Don't forget to add <uses-permission android:name="android.permission.INTERNET"/> in the AndroidManifest.xml.
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/connectBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

How to pass the value of a PHP variable within an EditText to Android Studio?

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

Android php mysql, do not operate with log

I have made application : mysql <-> Android using php.
I success to mysql with php.
http://localhost/phptest/newfile.php
id: jogi - password: 1234
id: jogi1 - password: 12341
id: jogi2 - password: 12342
but i have some trouble with connet Android.
Some code's are ignored. and does not message on log.
also android AVD not stopped but do not show any change. console do not show error, too... What can i do? or How can i check errors?
MainActivity.java
package com.example.phpmysql;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
public class MainActivity extends Activity {
private TextView result;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
result = (TextView)findViewById(R.id.text_view1);
}
public void Show_list(View view){
new SigninActivity(this,result,0).execute();
}
}
SigninActivity.java
package com.example.phpmysql;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.TextView;
public class SigninActivity extends AsyncTask<String,Void,String>{
private TextView resultField; //statusField
private int byGetOrPost = 0;
public SigninActivity(Context context,TextView resultField,int flag) {
byGetOrPost = flag;
}
protected void onPreExecute(){
}
#Override
protected String doInBackground(String... arg0) {
String myResult = null; //initiate;
if(byGetOrPost == 0){ //means by Get Method
Log.d("flag","0");
try {
URL url = new URL("http://http://localhost/phptest/newfile.php");
HttpURLConnection http = (HttpURLConnection) url.openConnection();
Log.d("where","http connect");
http.setDefaultUseCaches(false);
http.setDoInput(true);
http.setDoOutput(true);
http.setRequestMethod("POST");
http.setRequestProperty("content-type", "application/x-www-form-urlencoded");
Log.d("where","property");
//--------------------------
InputStreamReader tmp = new InputStreamReader(http.getInputStream(), "EUC-KR");
BufferedReader reader = new BufferedReader(tmp);
StringBuilder builder = new StringBuilder();
String str;
Log.d("where","inputstream");
while ((str = reader.readLine()) != null) {
builder.append(str + "\n");
}
myResult = builder.toString();
Log.d("myresult",myResult);
return myResult;
} catch (MalformedURLException e) {
//
} catch (IOException e) {
//
} // try
}
else{
}
return myResult;
}
#Override
protected void onPostExecute(String result){
if(result != null)
this.resultField.setText(result);
else
Log.d("failed", "postfailed");
}
}
This is all of my log. only one error when open but i think that AVD is connect well so it is not important.
A curious thing is that I can't find "input stream" with tag "where" in SigninActivity.java;
08-16 07:31:48.603: E/Trace(772): error opening trace file: No such file or directory (2)
08-16 07:31:49.753: D/gralloc_goldfish(772): Emulator without GPU emulation detected.
08-16 07:32:55.214: D/flag(772): 0
08-16 07:32:55.224: D/where(772): http connect
08-16 07:32:55.224: D/where(772): property
08-16 07:32:55.417: D/failed(772): postfailed
no error with application starting. If click the button 'list', no error, no stop also but no any change view. just white blank screen.
<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"
tools:context="${relativePackage}.${activityClass}" >
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginRight="26dp"
android:layout_toLeftOf="#+id/button2"
android:onClick="Show_list"
android:text="#string/Show_List" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_below="#+id/button1" >
<TextView
android:id="#+id/text_view1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="15sp" />
</LinearLayout>
you are not directly talking to mysql , your android app will receive a response from the webserver and so you need to call the webserver accessible url .
If you are in a local network give the webserver local address in
URL url = new URL("http://{webserverURL}/phptest/newfile.php");
You can get the IP from apache installed machine using ipconfig (Windows), ifconfig (linux).

Bluetooth Sends Sensor Data Only once

So for my research, I have to send accelometer data to an arduino mega as a constant stream. I have the module connected to the arduino via serial. However, when I ran the code, it only runs once. I tried to place the Bluetooth connect part of the code inside my on accuracy change part of my code, but it keeps freezing the device. Here's my code:
package com.example.arduino_bluetooth2;
//=================================================================================================
//Imports
//=================================================================================================
import java.io.IOException;
import java.io.OutputStream;
import java.util.Set;
import java.util.UUID;
import android.os.Bundle;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.view.Menu;
import android.widget.TextView;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
public class MainActivity extends Activity implements SensorEventListener {
// Setup necessary sensor objects
private Sensor acc;
private SensorManager sm;
private TextView t1;
private double value;
// Bluetooth Object
private BluetoothAdapter bAdapter;
private BluetoothDevice device;
private BluetoothSocket mmServerSocket;
private OutputStream btoutput;
private static final UUID SPP_UUID = UUID
.fromString("00001101-0000-1000-8000-00805F9B34FB");
private static final int DISCOVERY_REQUEST = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
accelerometer_initialization();
bluetooth_initialization();
}
// Setsup the accelerometer object
private void accelerometer_initialization() {
sm = (SensorManager) getSystemService(SENSOR_SERVICE);
acc = sm.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
sm.registerListener(this, acc, SensorManager.SENSOR_DELAY_NORMAL);
}
// Setup bluetooth object
private void bluetooth_initialization() {
bAdapter = BluetoothAdapter.getDefaultAdapter();
startActivityForResult(new Intent(
BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE),
DISCOVERY_REQUEST);
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mReceiver, filter);
bAdapter.startDiscovery();
}
#Override
public void onSensorChanged(SensorEvent event) {
value = event.values[0];
}
#Override
public void onAccuracyChanged(Sensor arg0, int arg1) {
}
final BroadcastReceiver mReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
if (BluetoothDevice.ACTION_FOUND.equals(intent.getAction())) {
device = intent
.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
if (new String(device.getName()).equals("BT UART")) {
bAdapter.cancelDiscovery();
try {
BluetoothSocket test = null;
test = device
.createInsecureRfcommSocketToServiceRecord(SPP_UUID);
mmServerSocket = test;
mmServerSocket.connect();
String message = Double.toString(value);
byte[] send = message.getBytes();
btoutput = mmServerSocket.getOutputStream();
btoutput.write(send);
btoutput.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
};
};
}
I am not sure you should creating and connecting the bluetooth socket in the broadcast receiver. I do the bluetooth connection management in the onResume() of the activity.
Also I use a thread to manage getting data from the serial data connection between the arduino and the device, it is spawned off and runs continuously in the background. There is a write method to send data out that i call from the activity
/* Call this from the main activity to send data to the remote device */
public void write(String message) {
System.out.println("...Data to send: " + message + "...");
byte[] msgBuffer = message.getBytes();
try {
mmOutStream.write(msgBuffer);
} catch (IOException e) {
System.out.println("...Error data send: " + e.getMessage() + "...");
}
}
then the run() method of the tread takes care of getting data back
See my answer in this thread for an example
Error with receiving xml strings via bluetooth in Android
Good luck!
Check out this page from arduino: http://arduino.cc/en/Reference/Loop
The problem is that it only goes once because it is not in a loop that continues forever until the device is shut off or told otherwise.

Categories

Resources