Android php mysql, do not operate with log - java

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).

Related

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

Cannot pull data from a SQLite DB

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.

Client (Android) & Server (Localhost console) communication issue

I am not a seasoned Java and Android practitioner, however, I will try to explain my issue clearly.
Non-descriptive explanation of what is needed:
Client: Android app, Server: Localhost
Client ---> Server, i.e., clients sends something to server.
Client <--- Server
Client ---> Server
Client <--- Server
Basically what's supposed to happen is RSA key exchanged led by encrypted AES key exchange.
Descriptive explanation:
Both client and server are generating RSA key-pair and they intend to send the public key (post conversion to strings), to each other, in a localhost environment, using Client-Server model, on a button click from my Android app.
Here is my code, which is seeming to work in Telnet, however, it is not the same when it comes to Android. In other words, it is printing the statements I put in to verify failures.
MainActivity.java file:
package com.avineshwar.secureclient;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.Reader;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
public class MainActivity extends AppCompatActivity {
private Socket client;
private PrintWriter printwriter;
private Button button;
private TextView textView;
private String messsage;
SecureRandom random;
KeyPairGenerator keyPairGenerator;
KeyPair keyPair;
PrivateKey privateKey;
PublicKey publicKey;
InputStreamReader inputStreamReader;
BufferedReader bufferedReader = null;
String server = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.button1);
textView = (TextView) findViewById(R.id.textView);
// Button press event listener
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
random = new SecureRandom();
keyPairGenerator = null;
try {
keyPairGenerator = KeyPairGenerator.getInstance("RSA");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
keyPairGenerator.initialize(2048, random);
keyPair = keyPairGenerator.generateKeyPair();
privateKey = keyPair.getPrivate();
publicKey = keyPair.getPublic();
messsage = String.valueOf(publicKey);
SendMessage sendMessageTask = new SendMessage();
sendMessageTask.execute();
if (server == null || server == "null") {
server = "null";
textView.setText(server);
} else {
textView.setText(server);
}
}
}
);
}
private class SendMessage extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
try {
try {
client = new Socket("192.168.1.169", 4444); // connect to the server
} catch (IOException e) {
e.printStackTrace();
}
printwriter = null;
printwriter = new PrintWriter(client.getOutputStream(), true);
printwriter.write(messsage);
inputStreamReader = null;
inputStreamReader = new InputStreamReader(client.getInputStream());
bufferedReader = new BufferedReader(inputStreamReader);
server = bufferedReader.readLine();
StringBuilder stringBuilder = new StringBuilder();
while ((server = bufferedReader.readLine()) != null) {
stringBuilder.append(server + "\n");
}
server = stringBuilder.toString();
client.close();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
//#Override
//public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
// getMenuInflater().inflate(R.menu.slimple_text_client, menu);
// return true;
// }
}
SecureServer.java file:
import com.sun.corba.se.impl.protocol.giopmsgheaders.Message;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import javax.crypto.KeyGenerator;
import javax.crypto.KeyGeneratorSpi;
import sun.nio.cs.Surrogate;
public class SecureServer {
private static ServerSocket serverSocket;
private static Socket clientSocket;
private static InputStreamReader inputStreamReader;
private static BufferedReader bufferedReader;
private static String message;
public static void main(String[] args) throws NoSuchAlgorithmException {
SecureRandom random = new SecureRandom();
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
keyPairGenerator.initialize(2048, random);
KeyPair keyPair = keyPairGenerator.generateKeyPair();
PrivateKey privateKey = keyPair.getPrivate();
PublicKey publicKey = keyPair.getPublic();
try {
serverSocket = new ServerSocket(4444); // Server socket
} catch (IOException e) {
System.out.println("Could not listen on port: 4444");
}
System.out.println("Server started listening on the port 4444");
while (true) {
try {
clientSocket = serverSocket.accept(); // accept the client connection
inputStreamReader = null;
inputStreamReader = new InputStreamReader(clientSocket.getInputStream());
bufferedReader = new BufferedReader(inputStreamReader); // get the client message
message = bufferedReader.readLine();
if (message == null || message == "null") {
message = "null";
}
System.out.println(message);
PrintWriter out = null;
out = new PrintWriter(clientSocket.getOutputStream(), true);
message = publicKey.toString();
out.write(message);
System.out.println(message);
out.close();
clientSocket.close();
} catch (IOException ex) {
System.out.println("Problem in message reading");
}
}
}
}
activity_main.xml file:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Press to send RSA key"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Text"
android:id="#+id/textView"
android:layout_centerVertical="true"
android:layout_alignParentStart="true" />
</RelativeLayout>
AndroidManifest.xml file:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.avineshwar.secureclient">
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
I do understand one thing though, however, I am not sure if it is correct and that is until I don't close my PrintWriter object in the Android app, the data is not going to be reflected on the server side, however, even if I do that, it is just solving one part of the scene, i.e., data from Android to server. I am not sure about any specific manner of collecting the data being sent from server though it is working for Telnet, i.e., both to and fro.
In SecureServer.java file, this statement,
inputStreamReader.close();
If put before these statements,
out = new PrintWriter(clientSocket.getOutputStream(), true);
message = publicKey.toString();
out.write(message);
System.out.println(message);
is throwing a handled IOException, which says Problem in message reading.
Apart from this, what I have observed is that in case we are writing anything to a socket, the "output to socket" stream has to be immediately closed as well, i.e., we cannot deal with any other stream related to that socket until this stream is closed.
A higher-level view of, my experience with, and approach to, the problem:
Program structure has to be in opposite direction.
When client sends something, server should be in a receiving state and vice-versa.
For that to be possible, any previous state has to be completed.
My client is sending some data to server (which is being received as well).
Server on receiving that data, wants to send some data back.
For that, server has to open an output stream for the same socket through which he read the data. I assume we shouldn't close the previously opened input stream before doing this because it never worked for me that way.
Server does the job of creating an input stream and then writing the data to the input stream.
However, parallely, in the client Android app, it is also expecting the data from server at socket's input stream. I assumed when server will send the data, this stream will receive it (and display it in a text view widget).
Right now, this idea/implementation seeming to work for Telnet (client) and Server.
In the past, data transfer from server to Android app has worked for me though. If there is just one-way transfer from server to client (Android app), it works.

Unable to do PHP+MySQL login with POST request

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.

Data transfer using Bluetooth in android

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();

Categories

Resources