I'm new at Java and attempting to build a companion app for a video game that my friends and I play (first app!). With this app, I've built a SQLite database with several tables and attempting to call this, query it, and display this data into a table.
My Question: Edited
I created an external SQLite database and copied this to my /assets/databases/ folder. While researching I've found that most people state you have to copy this to the /data/data/Package/databases location to actually use it.
When attempting to access my data, I'm received a "table does not exist" error ONLY if I tell it to grab data. If I remove the section calling my data, the app loads fine and moves to activities fine, but is useless if I can't pull my data.
E/AndroidRuntime: FATAL EXCEPTION: main
Process: info.ndakgamers.monsterdatabasetrial, PID: 17209
java.lang.RuntimeException: Unable to start activity ComponentInfo{info.ndakgamers.monsterdatabasetrial/info.ndakgamers.monsterdatabasetrial.Anjanath}: android.database.sqlite.SQLiteException: no such table: lrgmonsters (code 1): , while compiling: SELECT monstername, element, ailments, weakness, resistances, locations FROM lrgmonsters WHERE MonsterName = 'Anjanath'
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2665)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
Caused by: android.database.sqlite.SQLiteException: no such table: lrgmonsters (code 1): , while compiling: SELECT monstername, element, ailments, weakness, resistances, locations FROM lrgmonsters WHERE MonsterName = 'Anjanath'
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
Now, before anyone brings it up, I have scoured the internet. I've read so many blogs and threads and such and it BLOWS my mind the amount of hoops I've had to go through to get a SQLite DB to work in an application.
I've ready through this: "Using your own SQLite database in Android applications"
And that's what I've been trying to use to 'copy' my SQLite database internally so I can then use it in the app to query my data from.
Below are my items:
TestDataHelper.java
package info.ndakgamers.monsterdatabasetrial;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class TestDataHelper extends SQLiteOpenHelper {
//Setting our SQL KEYS
public static final String KEY_ID = "_id";
public static final String KEY_MONSTERNAME = "monstername";
public static final String KEY_ELEMENT = "element";
public static final String KEY_AILMENTS = "ailments";
public static final String KEY_WEAKNESS = "weakness";
public static final String KEY_RESISTANCES = "resistances";
public static final String KEY_LOCATIONS = "locations";
//The Android's default system path of your application database.
private static String DB_PATH = "/data/data/info.ndakgamers.monsterdatabasetrial/databases/";
private static String DB_NAME = "MHWResearchData.db";
private static String DB_TABLE_NAME = "large_monsters";
private SQLiteDatabase myDataBase;
private final Context myContext;
private TestDataHelper testhelper;
/**
* Constructor
* Takes and keeps a reference of the passed context in order to access to the application assets and resources.
*
* #param context
*/
public String gettestData(){
String[] columns = new String[]{KEY_ID, KEY_MONSTERNAME, KEY_ELEMENT, KEY_AILMENTS, KEY_WEAKNESS, KEY_RESISTANCES, KEY_LOCATIONS};
//Cursor cursor = myDataBase.rawQuery("SELECT * FROM large_monsters WHERE monstername = 'Anjanath'",null);
Cursor cursor = myDataBase.query(DB_TABLE_NAME, columns, KEY_MONSTERNAME, null, null, null, null);
String result = "";
int iMonsterName = cursor.getColumnIndex(KEY_MONSTERNAME);
int iElement = cursor.getColumnIndex(KEY_ELEMENT);
int iAilments = cursor.getColumnIndex(KEY_AILMENTS);
int iWeakness = cursor.getColumnIndex(KEY_WEAKNESS);
int iResistances = cursor.getColumnIndex(KEY_RESISTANCES);
int iLocations = cursor.getColumnIndex(KEY_LOCATIONS);
for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()){
result = result + cursor.getString(iMonsterName) + " "
+ cursor.getString(iElement) + " "
+ cursor.getString(iAilments) + " "
+ cursor.getString(iWeakness) + " "
+ cursor.getString(iResistances) + " "
+ cursor.getString(iLocations) + "\n";
}
return result;
}
public TestDataHelper(Context context) {
super(context, DB_NAME, null, 2);
this.myContext = context;
}
/**
* Check if the database already exist to avoid re-copying the file each time you open the application.
*
* #return true if it exists, false if it doesn't
*/
private boolean checkDataBase() {
SQLiteDatabase checkDB = null;
try {
String myPath = DB_PATH + DB_NAME;
checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
} catch (SQLiteException e) {
//database does't exist yet.
}
if (checkDB != null) {
checkDB.close();
}
return checkDB != null;
}
/**
* Copies your database from your local assets-folder to the just created empty database in the
* system folder, from where it can be accessed and handled.
* This is done by transfering bytestream.
*/
private void copyDataBase() throws IOException {
//Open your local db as the input stream
InputStream myInput = myContext.getAssets().open(DB_NAME);
// Path to the just created empty db
String outFileName = DB_PATH + DB_NAME;
//Open the empty db as the output stream
OutputStream myOutput = new FileOutputStream(outFileName);
//transfer bytes from the inputfile to the outputfile
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}
//Close the streams
myOutput.flush();
myOutput.close();
myInput.close();
}
/**
* Creates a empty database on the system and rewrites it with your own database.
*/
public void createDatabase() throws IOException {
boolean dbExist = checkDataBase();
if (dbExist) {
//do nothing - database already exist
} else {
//By calling this method and empty database will be created into the default system path
//of your application so we are gonna be able to overwrite that database with our database.
this.getReadableDatabase();
try {
copyDataBase();
} catch (IOException e) {
throw new Error("Error copying database");
}
}
}
public void openDataBase() throws SQLException{
//Open the database
String myPath = DB_PATH + DB_NAME;
myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
}
#Override
public synchronized void close() {
if(myDataBase != null)
myDataBase.close();
super.close();
}
#Override
public void onCreate(SQLiteDatabase db) {
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
// Add your public helper methods to access and get content from the database.
// You could return cursors by doing "return myDataBase.query(....)" so it'd be easy
// to you to create adapters for your views.
}
Anjanath.java Where my data grab is occurring
package info.ndakgamers.monsterdatabasetrial;
import android.database.SQLException;
import android.database.sqlite.SQLiteException;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.GridView;
import android.widget.TextView;
import java.io.IOException;
public class Anjanath extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_anjanath);
TestDataHelper myDbHelper = new TestDataHelper(null);
myDbHelper = new TestDataHelper(this);
try {
myDbHelper.createDatabase();
} catch (IOException ioe) {
throw new Error("Unable to create database");
}
try {
TextView tvv = (TextView) findViewById(R.id.tvSQLInfo);
myDbHelper.openDataBase();
String newData = myDbHelper.gettestData();
myDbHelper.close();
tvv.setText(newData);
}catch(SQLiteException sqle){
throw sqle;
}
}
}
MainActivity.java
package info.ndakgamers.monsterdatabasetrial;
import android.app.Dialog;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
Button anjabtn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
anjabtn = (Button) findViewById(R.id.anjabtn);
anjabtn.setOnClickListener(this);
}
#Override
public void onClick(View myview) {
switch (myview.getId()) {
case R.id.anjabtn:
boolean testItem = true;
try {
Intent anjIntent = new Intent("info.ndakgamers.monsterdatabasetrial.ANJANATH");
startActivity(anjIntent);
}catch(Exception excep) {
testItem = false;
}finally {
if (testItem) {
Dialog dworks = new Dialog(this);
TextView tv = new TextView(this);
tv.setText("Success");
dworks.setContentView(tv);
dworks.show();
}else {
Dialog dfails = new Dialog(this);
TextView tv = new TextView(this);
tv.setText("Failure");
dfails.setContentView(tv);
dfails.show();
}
}
break;
}
}
}
Anjanath XML if anyone is curious and wants to help with how I'd sort each SQLite column to each column
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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="wrap_content"
android:orientation="vertical"
tools:context="info.ndakgamers.monsterdatabasetrial.Anjanath">
<ImageView
android:id="#+id/anjaBanner"
android:layout_width="320dp"
android:layout_height="144dp"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.0"
app:srcCompat="#drawable/anjanath_render" />
<HorizontalScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<TableLayout
android:layout_width="wrap_content"
android:layout_height="match_parent">
<TableRow
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/tblMonsterNames"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="Monster Names"
android:textAlignment="center" />
<TextView
android:id="#+id/tblElement"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="Element"
android:textAlignment="center" />
<TextView
android:id="#+id/tblAilments"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="Ailments"
android:textAlignment="center" />
<TextView
android:id="#+id/tblWeakness"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="Weakness"
android:textAlignment="center" />
<TextView
android:id="#+id/tblResistances"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="Resistances"
android:textAlignment="center" />
<TextView
android:id="#+id/tblLocations"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="Locations"
android:textAlignment="center" />
</TableRow>
<TableRow
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="#+id/tvSQLInfo"
android:layout_width="361dp"
android:layout_height="61dp"
android:text="db Data Goes Here"
tools:layout_editor_absoluteX="12dp"
tools:layout_editor_absoluteY="163dp" />
</TableRow>
</TableLayout>
</HorizontalScrollView>
</LinearLayout>
The onCreate of your Helper is empty! This means you are not creating any tables. You should create queries with a CREATE TABLE statement for each tabels you put in your database, and execute all those queries in your helper's onCreate.
Also, since you've mentioned the hard work it takes to write all this code, I'll suggest you to take a look at Room Persistence Library, it will help you a lot!
I believe that your issue is that you have copied the file in to /assets/databases/ but are just using the database name, whilst you need to include the databases sub-directory when opening the file. So instead of
InputStream myInput = myContext.getAssets().open(DB_NAME);
you would need to use :-
InputStream myInput = myContext.getAssets().open("databases/" + DB_NAME);
Alternately copy the file into the assets folder rather than the databases sub-directory.
Related
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 am creating an app and when I click login in the android simulator it says unfortunately the app has stopped but I checked my code multiple times and I don't see any errors with the code . I am following a tutorial so it should all be correct because it works for the guy doing the tutorial .
MainActivity.java :
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.EditText;
public class MainActivity extends AppCompatActivity {
EditText UsernameEt, PasswordEt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
UsernameEt = (EditText)findViewById(R.id.etUserName);
PasswordEt = (EditText)findViewById(R.id.etPassword);
}
public void OnLogIn(View view) {
String username = UsernameEt.getText().toString();
String password = PasswordEt.getText().toString();
String type = "login";
BackgroundWorker backgroundWorker = new BackgroundWorker(this);
backgroundWorker.execute(type, username, password);
}
}
Backgroundworker.java :
import android.app.AlertDialog;
import android.content.Context;
import android.os.AsyncTask;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
public class BackgroundWorker extends AsyncTask<String,Void,String> {
Context context;
AlertDialog alertDialog;
BackgroundWorker (Context ctx) {
context = ctx;
}
#Override
protected String doInBackground(String... params) {
String type = params[0];
String login_url = "http://192.168.1.7/login.php";
if (type.equals("login")){
try {
String user_name = params[1];
String password = params[2];
URL url = new URL(login_url);
HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
String post_data = URLEncoder.encode("user_name" , "UTF-8")+"="+URLEncoder.encode(user_name , "UTF-8")+"&"
+URLEncoder.encode("user_pass" , "UTF-8")+"="+URLEncoder.encode(password , "UTF-8");
bufferedWriter.write(post_data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"));
String result="";
String line;
while((line = bufferedReader.readLine())!= null ){
result += line;
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return result;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPreExecute() {
alertDialog = new AlertDialog.Builder(context).create();
alertDialog.setTitle("Login Status");
}
#Override
protected void onPostExecute(String result) {
alertDialog.setMessage(result);
alertDialog.show();
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
}
Login button in content_main.xml :
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="LogIn"
android:id="#+id/login"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:onClick="OnLogIn"
/>
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:hint="Username"
android:ems="10"
android:id="#+id/etUserName"
android:layout_below="#+id/textView"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textPassword"
android:ems="10"
android:hint="Password"
android:id="#+id/etPassword"
android:layout_below="#+id/etUserName"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
login.php :
<?php
require"db.php";
$user_name = "user";
$password = "pass";
$mysql_qry = "select * from users where username = '$user_name' and password = '$password';";
$result = mysqli_query($conn, $mysql_qry);
if(mysqli_num_rows($result) > 0) {
echo"login success";
}
else {
echo"not success";
}
?>
Error :
Caused by: java.lang.NullPointerException: Attempt to invoke virtual
method 'android.text.Editable android.widget.EditText.getText()' on a
null object reference
at com.example.User.App.MainActivity.OnLogIn(MainActivity.java:22)
(line 22 mainactivity: String username =
UsernameEt.getText().toString();)
Once you fix the app crashing, such as making sure activity_main.xml (or content_main, if you have one) contains those two button ids that you've used in the code, you have a second problem with the server as well.
Your PHP file always uses user:pass as the credentials to try to login to the database, and never receives anything else.
If you would like to get the values that android set in the POST request, you can do like so
if (isset($_POST['user_name']) && isset($_POST['user_pass'])) {
// receiving the post params
$name = $_POST['user_name'];
$password = $_POST['user_pass'];
// TODO: Call database function
There is no problem in server side. Here, NullPointerException in EditText means you are getting value from Edittext, that is not initialized.
Possible cause of NullPointerException is:
You are using multi-screen layout. That means your each layout has multiple copy in multiple layout folder. And your device suitable folder not contains desired EditText.
Solution:
make sure etUserName is in your desired xml.
Hi guys i have tried some codes but none work i was hoping if someone could help me. Bellow i will put my code
AndroidManisfest:
<?xml version="1.0" encoding="utf-8"?
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.andre.marques.moldartsqlserver">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".InicioActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".OrdemFabricoActivity"></activity>
</application>
</manifest>
activity_ordemfabrico.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:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:id="#+id/EnterPays_atomPaysList"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
tools:listitem="#layout/ofselect"
android:layout_below="#+id/layout_inf" >
</ListView>
</LinearLayout>
ofselect.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="?android:listPreferredItemHeightSmall"
android:orientation="horizontal"
android:showDividers="middle"
android:divider="?android:dividerVertical"
android:dividerPadding="8dp"
android:gravity="center">
<TextView android:id="#+id/Codart"
style="?android:textAppearanceMedium"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:paddingLeft="?android:listPreferredItemPaddingLeft" />
<TextView android:id="#+id/quantidade"
style="?android:textAppearanceMedium"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content" />
</LinearLayout>
ConnectionClass:
public class ConnectionClass {
String ip;
String classs;
String db;
String un;
String password;
public ConnectionClass() {
classs = "net.sourceforge.jtds.jdbc.Driver";
db = "DatabaseName";
un = "user";
password = "XXXXXXXX";
ip = "192.xxx.x.xxx";
}
public ConnectionClass(String Ip, String Classs, String Db, String Un, String Password) {
ip = Ip;
classs = Classs;
db = Db;
un = Un;
password = Password;
}
public String getip() {
return ip;
}
public String getclasss() {
return classs;
}
public String getdb() {
return db;
}
public String getun() {
return un;
}
public String getpassword() {
return password;
}
public void setip(String Ip) {
ip = Ip;
}
public void setdb(String Db) {
db = Db;
}
public void setclasss(String Classs) {
classs = Classs;
}
public void setun(String Un) {
un = Un;
}
public void setpassword(String Password) {
password = Password;
}
}
OrdemFabricoActivity:
public class OrdemFabricoActivity extends Activity {
ConnectionClass connectionclass;
ListView lst;
SimpleAdapter ADAhere;
String usernameS;
String datets;
String call, db, un, passwords;
Connection connect;
ResultSet rs;
#SuppressLint("NewApi")
private Connection CONN(String _user, String _pass, String _DB, String _server) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
Connection conn = null;
String ConnURL = null;
try {
Class.forName("net.sourceforge.jtds.jdbc.Driver");
ConnURL = "jdbc:jtds:sqlserver://" + _server + ";" + "databaseName=" + _DB + ";user=" + _user + ";password=" + _pass + ";";
conn = DriverManager.getConnection(ConnURL);
} catch (SQLException se) {
Log.e("ERRO", se.getMessage());
} catch (ClassNotFoundException e) {
Log.e("ERRO", e.getMessage());
} catch (Exception e) {
Log.e("ERRO", e.getMessage());
}
return conn;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ordemfabrico);
lst = (ListView) findViewById(R.id.EnterPays_atomPaysList);
/************* CONNECTION DATABASE VARIABLES ***************/
connectionclass = new ConnectionClass();
call = connectionclass.getip();
un = connectionclass.getun();
passwords = connectionclass.getpassword();
db = connectionclass.getdb();
connect = CONN(un, passwords, db, call);
String querycmd = "select NUMOF, COD_ART, DESC_ART, OBSERVACOES, QUANT from tabof where tabof.ID_TO <> 5";
try {
Statement statement = connect.createStatement();
rs = statement.executeQuery(querycmd);
List<Map<String, String>> data = null;
data = new ArrayList<Map<String, String>>();
while (rs.next()) {
Map<String, String> datanum = new HashMap<String, String>();
datanum.put("A", rs.getString("COD_ART"));
//datanum.put("B", rs.getString("QUANT"));
data.add(datanum);
}
String[] fromwhere = { "A" };
int[] viewswhere = { R.id.Codart };
ADAhere = new SimpleAdapter(OrdemFabricoActivity.this, data, R.layout.ofselect, fromwhere, viewswhere);
lst.setAdapter(ADAhere);
} catch (SQLException e) {
Toast.makeText(OrdemFabricoActivity.this, e.getMessage().toString(), Toast.LENGTH_LONG).show();
}
}
}
This is my code the result that i get with this code it is when i go to this activity my phone screen is black and nothing happen. I wanted to put in the labels Codart and quant the value of some camps of the database if someone know how to do this please help me.
I observed from your code, you are trying to connect database using JDBC driver. JDBC is not supported by android.
But Oracle provide the JDBC driver for android.
https://docs.oracle.com/cd/E17076_04/html/installation/build_android_jdbc.html
According oracle docs, you must have knowledge of NDK to build and configure the JDBC. I think its too complex process to configure. JDBC is very slow compared to SQLITE because no extra server configuration required to access data from sqlite database.
If your purpose is to store data in local database you must prefer SQLite3 , that is embedded with android,fast accessing and recommended by Google. Its too easy to use.
You can not create connection with sql server and android directly. If you want to store data on local database and then want to show record in listview, use sqlite. You can use following tutorial.
HOMEDATABASEAndroid SQLite Database Tutorial
Android SQLite Database Tutorial
If you really want to store data in sql-server, you must use client-server connection. Create web-services to access data from server, and consume it in android and populate the listview. For example, PHP and MySQL. Refer this tutorial
I thinks it help you.
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).
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();