My Android multi-threaded server does not work properly - android

I'm trying to set up a score update server on my Android device. Other phones can send scores and this server needs to show the visual results by updating the score of each client. Something like this:
Now my problems are:
1- The current multi-thread approach does not work. What is wrong with it?
2- How can I differentiate people when I receive them? Maybe by having a key-value/hashmap, and update the score corresponding to each IP/socket?
package course.examples.Sensors.ShowValues;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Random;
import android.app.Activity;
import android.content.pm.ActivityInfo;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
public class test extends Activity{
// Start with some variables
int i = 0;
int people = 0;
ArrayList<Bar> diagrams;
private static ServerSocket serverSocket;
private static Socket clientSocket;
private static InputStreamReader inputStreamReader;
private static BufferedReader bufferedReader;
private static String message;
private static HashMap<String, Integer> map;
boolean isDone=false;
private TextView mXValueView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// set orientation
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
mXValueView = (TextView) findViewById(R.id.textView1);
map= new HashMap<String, Integer>();
diagrams=new ArrayList<Bar>();
// In onCreate method
// diagrams = new ArrayList<Bar>();
// draw(0,0);
// connect_draw();
new Thread(new Runnable() {
public void run() {
connect_draw();
}
}).start();
}
// Register listener
#Override
protected void onResume() {
super.onResume();
}
// Unregister listener
#Override
protected void onPause() {
super.onPause();
}
// void draw() {
// Bar d = new Bar();
// d.setColor(Color.parseColor("#118800"));
// d.setName("Test1");
// d.setValue(i);
// Bar d2 = new Bar();
// d2.setColor(Color.parseColor("#FFBB33"));
// d2.setName("Test2");
// d2.setValue(20);
// diagrams.add(d);
// diagrams.add(d2);
// BarGraph g = (BarGraph) findViewById(R.id.graph);
// g.setBars(diagrams);
// }
void draw(int hash, int score){
//the person was not existed: Create a new Bar
if(!map.containsKey(hash) ){
Bar d = new Bar();
d.setColor(Color.rgb(new Random().nextInt(255), new Random().nextInt(255), new Random().nextInt(255)));
d.setName(people++ +"");
d.setValue((float)score);
diagrams.add(d);
}
BarGraph g = (BarGraph)findViewById(R.id.graph);
g.setBars(diagrams);
}
void connect_draw() {
try {
serverSocket = new ServerSocket(8888); // Server socket
Log.i("hello","hello: Server started. Listening to the port 8888");
isDone=true;
while (true) {
clientSocket = serverSocket.accept(); // accept the client
// connection
inputStreamReader = new InputStreamReader(
clientSocket.getInputStream());
bufferedReader = new BufferedReader(inputStreamReader); // get the client message
message = bufferedReader.readLine();
final int hash=clientSocket.getInetAddress().hashCode();
// i++;
// draw(hash,Integer.parseInt(message));
mXValueView.setText(message);
Log.i("hello","hello: server received "+message+ " from "+hash);
inputStreamReader.close();
clientSocket.close();
}
}catch (IOException ex) {
Log.e("hello","hello: problem in reading message");
}
}
}
And this is the client code:
package com.lakj.comspace.simpletextclient;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class SlimpleTextClientActivity extends Activity {
private Socket client;
private PrintWriter printwriter;
private EditText textField;
private Button button;
private String messsage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_slimple_text_client);
textField = (EditText) findViewById(R.id.editText1); // reference to the text field
button = (Button) findViewById(R.id.button1); // reference to the send button
// Button press event listener
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
messsage = textField.getText().toString(); // get the text message on the text field
textField.setText(""); // Reset the text field to blank
SendMessage sendMessageTask = new SendMessage();
sendMessageTask.execute();
}
});
}
private class SendMessage extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
try {
//10.73.172.214
client = new Socket("10.73.172.214", 8888); // connect to the server
printwriter = new PrintWriter(client.getOutputStream(), true);
printwriter.write(messsage); // write the message to output stream
printwriter.flush();
printwriter.close();
client.close(); // closing the connection
} catch (UnknownHostException e) {
e.printStackTrace();
} 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;
}
}
UPDATE: I've just added a simple textView, and noticed actually I'm not updating the UI view on another thread. How should I do that? Here is the warning stuff.
06-21 14:44:31.871: E/ACDB-LOADER(257): Error: ACDB audproc returned = -8
06-21 14:44:31.871: E/ACDB-LOADER(257): Error: ACDB AudProc vol returned = -8
06-21 14:44:31.951: W/InputMethodManagerService(575): Starting input on non-focused client com.android.internal.view.IInputMethodClient$Stub$Proxy#41e1aff0 (uid=10043 pid=2841)
06-21 14:44:35.004: E/ALSADevice(257): standby handle h 0x41597050
06-21 14:44:35.054: E/ALSADevice(257): Number of modifiers 0
06-21 14:44:35.054: E/ALSADevice(257): usecase_type is 0
06-21 14:44:35.895: W/ActivityManager(575): No content provider found for permission revoke: file:///data/local/tmp/test.apk
06-21 14:44:35.895: W/ActivityManager(575): No content provider found for permission revoke: file:///data/local/tmp/test.apk
06-21 14:44:36.115: W/PackageManager(575): Code path for pkg : course.examples.Sensors.ShowValues changing from /data/app/course.examples.Sensors.ShowValues-1.apk to /data/app/course.examples.Sensors.ShowValues-2.apk
06-21 14:44:36.115: W/PackageManager(575): Resource path for pkg : course.examples.Sensors.ShowValues changing from /data/app/course.examples.Sensors.ShowValues-1.apk to /data/app/course.examples.Sensors.ShowValues-2.apk
06-21 14:44:36.315: W/ResourceType(575): Failure getting entry for 0x7f060000 (t=5 e=0) in package 0 (error -75)
06-21 14:44:36.315: W/ResourceType(575): Failure getting entry for 0x7f060000 (t=5 e=0) in package 0 (error -75)
06-21 14:44:36.315: W/InputMethodManagerService(575): Found no subtypes in a system IME: com.android.inputmethod.pinyin
06-21 14:44:36.365: W/RecognitionManagerService(575): no available voice recognition services found
06-21 14:44:36.796: W/ProcessStats(575): Skipping unknown process pid 2918
06-21 14:44:36.806: W/ProcessStats(575): Skipping unknown process pid 2923
06-21 14:44:36.806: W/ProcessStats(575): Skipping unknown process pid 2929
06-21 14:44:36.806: W/ProcessStats(575): Skipping unknown process pid 2933
06-21 14:44:37.216: E/Trace(2953): error opening trace file: No such file or directory (2)
06-21 14:44:37.356: E/hello(2953): hello: problem in reading message
06-21 14:44:37.406: E/BufferQueue(254): [Starting course.examples.Sensors.ShowValues] drainQueueLocked: BufferQueue has been abandoned!
06-21 14:44:37.486: W/IInputConnectionWrapper(869): showStatusIcon on inactive InputConnection
06-21 14:44:56.447: W/CNE(575): UNKOWN Unsolicited Event 5
06-21 14:44:59.410: E/StatusBar.NetworkController(662): updateDataNetType NETWORK_TYPE_UNKNOWN
06-21 14:44:59.450: E/StatusBar.NetworkController(662): updateDataNetType NETWORK_TYPE_UNKNOWN

We cannot see what your client send. We see that your server reads one line and then closes the client. The server then increments variable i. The server does nothing with the info in the received line. Every client should place an identifier in that line followed by a score. The server would then decode identifier and score from that line. You are displaying a diagram but it is not yours?

Related

How to connect to phpmyadmin database using OkHttp3 in Android [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 3 years ago.
I’m new to Android, in order to prepare for my last school exam, I was asked to put an Android application solution using an external database on phpmyadmin ( wampserver).
My connection is done in the MainActivity file, using OkHttp3 and overriding AsyncTask with a request on an external php file for the authentification.
After a few days of work the connection still doesn’t work and my tests are coming soon, every launch of the android application is in debug mode and here are my error logs when i'm trying to connect :
E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #1
Process: com.example.brobert.biorelai, PID: 6002
java.lang.RuntimeException: An error occurred while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:354)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:383)
at java.util.concurrent.FutureTask.setException(FutureTask.java:252)
at java.util.concurrent.FutureTask.run(FutureTask.java:271)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:245)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
at java.lang.Thread.run(Thread.java:764)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String okhttp3.Response.toString()' on a null object reference
at com.example.brobert.biorelai.MainActivity$BackTaskAuthentification.doInBackground(MainActivity.java:76)
at com.example.brobert.biorelai.MainActivity$BackTaskAuthentification.doInBackground(MainActivity.java:46)
at android.os.AsyncTask$2.call(AsyncTask.java:333)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:245) 
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167) 
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641) 
at java.lang.Thread.run(Thread.java:764) 
I/Process: Sending signal. PID: 6002 SIG: 9
Disconnected from the target VM, address: 'localhost:8600', transport:
'socket'
I already tried to add the internet permission via the AndroidManifest.xml :
<uses-permission android:name="android.permission.INTERNET"/>
To add the okhttp3 dependencies and put the proxy option on auto-detect.
MoreOver with the log function i verified that my EditText was working and my variable request too.
I think the error is on the line 70-71 of my MainActivity file :
response = client.newCall(request).execute();
responseStr = response.body().toString();
My MainActivity File code :
package com.example.brobert.biorelai;
import android.annotation.SuppressLint;
import android.os.AsyncTask;
import android.util.Log;
import android.view.View.OnClickListener;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
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.EditText;
import android.widget.Toast;
import org.json.JSONException;
import org.json.JSONObject;
import okhttp3.*;
public class MainActivity extends AppCompatActivity {
String responseStr;
OkHttpClient client = new OkHttpClient();
String textLogin1;
String mdp1;
Response response;
RequestBody formBody;
Request request;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button buttonValiderAuthentification = (Button)
findViewById(R.id.button2);
buttonValiderAuthentification.setOnClickListener(new
View.OnClickListener() {
#Override
public void onClick(View v){
new BackTaskAuthentification().execute();
}
});
}
private class BackTaskAuthentification extends AsyncTask<Void, Void,
Void> {
#Override
protected void onPreExecute() {
final EditText textLogin = findViewById(R.id.login1);
final EditText textMdp = findViewById(R.id.mdp1);
textLogin1 = textLogin.getText().toString();
mdp1 = textMdp.getText().toString();
}
#Override
protected Void doInBackground(Void... params){
try {
formBody = new FormBody.Builder()
.add("login", textLogin1)
.add("mdp", mdp1)
.build();
request = new Request.Builder()
.url("http://127.0.0.1/bio- relais/controleurMobil/json.php")
.post(formBody)
.build();
response = client.newCall(request).execute();
responseStr = response.body().toString();
} catch (Exception e) {
Log.d("test", textLogin1);
Log.d("test1", mdp1);
Log.d("test3", request.toString());
Log.d("test2", response.toString());
}
return null;
}
#Override
protected void onPostExecute(Void result) {
if (responseStr.compareTo("false") != 0){
try {
JSONObject membre = new JSONObject(responseStr);
String nom = membre.getString("nomM");
Intent intent = new Intent(MainActivity.this,
MainProducteurActivity.class);
intent.putExtra("membre", membre.toString());
startActivity(intent);}
catch(JSONException e){
Toast.makeText(MainActivity.this, "Erreur de connexion !",
Toast.LENGTH_SHORT).show();
}
}else{
Toast.makeText(MainActivity.this, "Login ou mot de
passe non valide !",
Toast.LENGTH_SHORT).show();
}
}
}
}
A request is made on a local url http:///127.0.0.1/bio-relais/controleurMobil/json.php containing the code :
require_once '. /lib/autoloadMobil.php';
print(json_encode(MembreDAO::authentication($_POST['login'],
$_POST['mdp'])));
to pass the login and mdp of my Text edit in my method of the class MembreDao "authentification" containing the code :
public static function authentification($login, $mdp){
try{
$sql="select login, nomM ,prenomM
from MEMBRE
where login = :login
and mdp = :mdp ";
$requetePrepa = DBConnex::getInstance()->prepare($sql);
$mdp = md5($mdp);
$requetePrepa->bindParam("login", $login);
$requetePrepa->bindParam("mdp", $mdp);
$requetePrepa->execute();
$reponse = $requetePrepa->fetch(PDO::FETCH_ASSOC);
}catch(Exception $e){
$reponse = "";
}
return $reponse;
}
The expected result is a working authentification allowing the user present in the database to access to the interface of the MainProducteurActivity.
Thank you very much in advance for your help.
I finally found the problem, i was trying to connect to my localhost personal computer url on the avd with :
.url("http://127.0.0.1/bio- relais/controleurMobil/json.php")
But for the avd the localhost url of my json.php file is :
.url("http://10.0.2.2/bio-relais/controleurMobil/json.php")
( Localhost for avd = 10.0.2.2 ) .

My android phone is not sending signals to the arduino uno or maybe the arduino uno card is not communicating to the servo motor sg90

I am uploading the code of both the android-studio as well as the arduino uno.. It seems right but somehow it doesn't work
Android Studio code :
package com.example.chintan.doorlock;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Set;
import java.util.UUID;
import android.os.Handler;
public class MainActivity extends AppCompatActivity {
private final String DEVICE_ADDRESS = "00:21:13:01:ED:10"; //MAC Address of Bluetooth Module
private final UUID PORT_UUID = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb");
private BluetoothDevice device;
private BluetoothSocket socket;
private OutputStream outputStream;
private InputStream inputStream;
Thread thread;
byte buffer[];
boolean stopThread;
boolean connected = false;
String command;
Button lock_state_btn, bluetooth_connect_btn;
TextView lock_state_text;
ImageView lock_state_img;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lock_state_btn = (Button) findViewById(R.id.lock_state_btn);
bluetooth_connect_btn = (Button) findViewById(R.id.bluetooth_connect_btn);
lock_state_text = (TextView) findViewById(R.id.lock_state_text);
lock_state_img = (ImageView) findViewById(R.id.lock_state_img);
bluetooth_connect_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v){
if(BTinit()) //initialises bluetooth
{
BTconnect(); //connects android code to arduino
beginListenForData();
// The code below sends the number 3 to the Arduino asking it to send the current state of the door lock so the lock state icon can be updated accordingly
command = "3";
try
{
outputStream.write(command.getBytes());
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
});
lock_state_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v){
if(connected == false)
{
Toast.makeText(getApplicationContext(), "Please establish a connection with the bluetooth servo door lock first", Toast.LENGTH_SHORT).show();
}
else
{
command = "1";
try
{
outputStream.write(command.getBytes()); // Sends the number 1 to the Arduino. For a detailed look at how the resulting command is handled, please see the Arduino Source Code
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
});
}
void beginListenForData() // begins listening for any incoming data from the Arduino
{
final Handler handler = new Handler();
stopThread = false;
buffer = new byte[1024];
Thread thread = new Thread(new Runnable()
{
public void run()
{
while(!Thread.currentThread().isInterrupted() && !stopThread)
{
try
{
int byteCount = inputStream.available();
if(byteCount > 0)
{
byte[] rawBytes = new byte[byteCount];
inputStream.read(rawBytes);
final String string = new String(rawBytes, "UTF-8");
handler.post(new Runnable()
{
public void run()
{
if(string.equals("3"))
{
lock_state_text.setText("Lock State: LOCKED"); // Changes the lock state text
lock_state_img.setImageResource(R.drawable.locked_icon); //Changes the lock state icon
}
else if(string.equals("4"))
{
lock_state_text.setText("Lock State: UNLOCKED");
lock_state_img.setImageResource(R.drawable.unlocked_icon);
}
}
});
}
}
catch (IOException ex)
{
stopThread = true;
}
}
}
});
thread.start();
}
#Override
protected void onStart()
{
super.onStart();
}
}
And this is my arduino source code :
//Android-controlled Arduino Bluetooth Servo Door Lock by uscv
#include <Servo.h>
#include <EEPROM.h>
Servo servo;
char state;
void setup() {
// put your setup code here, to run once:
servo.attach(7);
if(EEPROM.read(0) == 1) // Reads the EEPROM value stored to know what state the door lock was in before it was last turned off
{ // An EEPROM value of 1 means UNLOCKED and a value of 2 means LOCKED
servo.write(0); // Rotates the servo to the unlocked position
delay(200);
}
else if(EEPROM.read(0) == 2)
{
servo.write(75); // Rotates the servo to the locked position
delay(200);
}
Serial.begin(9600);
}
void loop() {
// put your main code here, to run repeatedly:
if(Serial.available() > 0)
{
char data;
data = Serial.read(); // The variable data is used to store the value sent by the Android app
switch(data)
{
case '1':
if(EEPROM.read(0) == 1) //An EEPROM value of 1 means it is currently unlocked
{
EEPROM.write(0, 2); // Writes the number 2 to address 0 on the Arduino's EEPROM. This value will be used by the Arduino to remember the last state the door lock was in
Serial.print("3"); // Sends the number 3 to the Android app. To see what this does, please see the Android Studio Project file
servo.write(75);
delay(15);
}
else if(EEPROM.read(0) == 2) //An EEPROM value of 2 means it i currently locked
{
EEPROM.write(0, 1); // Writes the number 1 to address 0 on the Arduino's EEPROM. This value will be used by the Arduino to remember the last state the door lock was in
Serial.print("4"); // Sends the number 4 to the Android app. The number sent will be used by the app to update the locked/unlocked icon
servo.write(0);
delay(15);
}
break;
case '3':
if(EEPROM.read(0) == '1')
{
Serial.print("4");
}
else if(EEPROM.read(0) == '2')
{
Serial.print("3");
}
break;
}
}
}
So, first the android app will start bluetooth, then connect to the arduino uno card and then perform the following functions:
1. "3" sent from android phone to arduino
2. received either "4" or "3" based on its status from arduino uno to android
3. Change the lock image on the android phone
4. send "1" from the android phone to the arduino
5. Change the status of the servo motor sg90 from its current position
Now, my android application is error-free and connects to the arduino uno and also is able to start the bluetooth of the phone. It establishes the connection but does not change the position of the servo motor sg90. I dont understand the problem what should we do?
You are calling EEPROM.read() before initializating the EEPROM. In other words for example in your setup() you are checking whether you EEPROM address 0 contains a certain value rather than initialization it with a certain value. Then
in your loop(), again you are checking whether EEPROM address contains a certain value before any value is written to the EEPROM and thus you will never reach the EEPROM write part because your if statements always returns false. So, start first by writing a value to EEPROM address 0.

Reading file from AVD sd card and displaying text view

I have a text file that has this information
Casino Canberra;21 Binara Street, Canberra ACT, 2601;Canberra Casino is a casino located in Civic in the central part of the Australian capital city of Canberra. The Casino is relatively small compared with other casinos in Australia.;(02) 6257 7074;www.canberracasino.com.au
National Museum of Canberra;Parkes Place, Canberra ACT, 2601;The National Museum of Australia explores the land, nation and people of Australia. Open 9am - 5pm every day except Christmas Day. General admission free.;(02) 6240 6411;www.nga.gov.au
which is stored in the sdcard
after this i retrieve the values using this method
package au.edu.canberra.g30813706;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import android.app.Activity;
import android.os.Environment;
public class FileReader extends Activity{{
ArrayList<read> sInfo = new ArrayList<read>();
ArrayList<String> sLines = new ArrayList<String>();
String line;
String[] saLineElements;
String txtName = "AccomodationTxt.txt";
File root = Environment.getExternalStorageDirectory();
File path = new File(root, "CanberraTourism/" + txtName);
try {
BufferedReader br = new BufferedReader (
new InputStreamReader(
new FileInputStream(path)));
while ((line = br.readLine()) != null)
{
sLines.add(line);
//The information is split into segments and stored into the array
saLineElements = line.split(";");
//for (int i = 0; i < saLineElements.length; i++)
// sInfo.add(new read(saLineElements[i]));
sInfo.add(new read(saLineElements[0], saLineElements[1], saLineElements[3], saLineElements[4], saLineElements[5]));
}
br.close();
}
catch (FileNotFoundException e) {
System.err.println("FileNotFoundException: " + e.getMessage());
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}}
}
But i also have and object class to store each individual item into
package au.edu.canberra.g30813706;
public class read {
public String name;
public String address;
public String info;
public String phone;
public String www;
public read (String name, String address, String info, String phone, String www)
{
this.name = name;
this.address = address;
this.info = info;
this.phone = phone;
this.www = www;
}
}
The only issue im having is trying to display the information in a text view which i have no idea how to call the values i need
This is where im trying to insert it
package au.edu.canberra.g30813706;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import au.edu.canberra.g30813706.FileReader;
import au.edu.canberra.g30813706.read;
public class Accommodation_info extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.accommodation_layout);
}}
You should probably look into using the Application class. You can think of Application as a GUI-less activity which works like the model in a program following the MVC pattern. You can put all of your read objects into a data structure in your Application and then access them with accessors and mutators of your own design.
Take a look at this official doc.
As your code stands, you can only access your instances of read by obtaining a reference to your FileReader class, but your two activities are separate entities. You'd have to do something like this:
// This is the main activity and should be launched first
// Check your manifest to make sure it launches with this activity
package au.edu.canberra.g30813706;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import au.edu.canberra.g30813706.FileReader;
import au.edu.canberra.g30813706.read;
public class Accommodation_info extends Activity
{
// Declare the file reader so you'll have a reference
FileReader reader;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.accommodation_layout);
// Instantiate the file reader
reader = new FileReader();
// Now you can access the array inside FileReader
// obviously, you need to have a text view called my_textView defined in the
// layout file associated with this activity
TextView myTextView = (TextView)findViewById(R.id.my_textView);
// displays the first element in FileReader's array list
myTextView.setText((String)reader.get(0));
}}
At the moment, you might be in a bit deep for your current understanding of Android and/or Java. I would encourage you to follow as many code examples as possible, get comfortable with Android and then go back to your project when you have a little more experience.

FTPS connection in android

I am new to android, i want to download the files from FTPs server, On emulater i am able to download files but when i try on target board it is giving error at ftp.auth(SSLFTPClient.AUTH_TLS);
Below is the my code, please suggest me where i am wrong.
package com.android.ftp;
import java.io.File;
import android.app.Activity;
import android.os.Bundle;
import com.enterprisedt.net.ftp.FTPClientInterface;
import com.enterprisedt.net.ftp.FTPConnectMode;
import com.enterprisedt.net.ftp.FTPTransferType;
import com.enterprisedt.net.ftp.ssl.SSLFTPClient;
import com.enterprisedt.util.debug.Level;
import com.enterprisedt.util.debug.Logger;
public class Ftp_testActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
String host = "ftp.xyz.com";
String username = "abcd";
String password = "pqr";
String filename = "/mnt/sdcard/video1/747.3gp";
// set up logger so that we get some output
Logger log = Logger.getLogger(Ftp_testActivity.class);
Logger.setLevel(Level.INFO);
SSLFTPClient ftp = null;
try {
// create client
log.info("Creating FTPS (explicit) client");
ftp = new SSLFTPClient();
// disable standard SSL closure
log.info("Setting configuration flags");
ftp.setConfigFlags(SSLFTPClient.ConfigFlags.DISABLE_SSL_CLOSURE);
// set remote host
log.info("Setting remote host");
ftp.setRemoteHost(host);
ftp.setRemotePort(21);
// turn off server validation
log.info("Turning off server validation");
ftp.setValidateServer(false);
// connect to the server
log.info("Connecting to server " + host);
ftp.connect();
// switch to SSL on control channel
log.info("Switching to FTPS (explicit mode)");
ftp.auth(SSLFTPClient.AUTH_TLS);
// log in
log.info("Logging in with username=" + username + " and password="
+ password);
ftp.login(username, password);
log.info("Logged in");
ftp.setConnectMode(FTPConnectMode.PASV);
ftp.setType(FTPTransferType.ASCII);
putGetDelete(filename, ftp);
log.info("Successfully transferred in ASCII mode");
// Shut down client
log.info("Quitting client");
ftp.quit();
log.info("Example complete");
} catch (Exception e) {
e.printStackTrace();
}
}
private static void putGetDelete(String name, FTPClientInterface ftp)
throws Exception {
ftp.put(name, name);
ftp.get(name + ".copy", name);
ftp.delete(name);
File file = new File(name + ".copy");
file.delete();
}
}
You should try:
ftp.setRemotePort(990);
where 990 is port SSL default.

Bluetooth Detection Problems in Samsung Galaxy Tab using Android Bluetooth API

I have a problem detecting zero class bluetooth devices with my Galaxy Tab using the Android Bluetooth API. It simply does not "see" some devices although I can detect them with my phone or computer. Has anyone run into this problem? I´m writing an app which depends on pairing with a device through bluetooth and some help in this regard would be most appreciated.
Note: This solution will only work with old Android OSs, due to it's need for access to the device logs.
Yes! I have exactly the same problem, abeit on a Samsung Galaxy S, and LG Optimus One. I wrote a class you can reuse to fix this, no idea if it will work on the Galaxy Tab, but you can try:
package com.yourpackagename;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import android.app.Activity;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.AsyncTask;
// This class exists due to a bug in the Broadcomm bluetooth stack, which is
// used by many Android smart-phone manufacturers (LG, Samsung HTC etc.). That
// bug prevents discovery of ALL bluetooth devices that report their Class of Device (CoD)
// code as 0x00, which prevent many SPP (Serial Port Profile) devices from working.
//
// See: http://www.google.com/codesearch/p?hl=en#4hzE-Xyu5Wo/vendor/brcm/adaptation/dtun/dtunc_bz4/dtun_hcid.c&q=%22Device%20[%25s]%20class%20is%200x00%20-%20skip%20it.%22&sa=N&cd=1&ct=rc
// And: http://stackoverflow.com/questions/4215398/bluetooth-device-not-discoverable
// And: http://www.reddit.com/r/Android/comments/hao6p/my_experience_with_htc_support_eu_anyone_has/
//
// How to use (from your Activity class):
//
// (new BluetoothClassZeroDiscoveryTask(this, new BluetoothDiscoveryCallback())).execute();
//
// Where BluetoothDiscoveryCallback is a class defined e.g. in your Activity. The call method
// will be called after the discovery task completes, and is passed the complete list
// of paired bluetooth devices, including those that are undiscoverable due to the above bug.
//
// private class BluetoothDiscoveryCallback implements Action<ArrayList<BluetoothDevice>>
// {
// public void call(ArrayList<BluetoothDevice> devices)
// {
// // Now you have the list of ALL available devices,
// // including those that report class 0x00.
// }
// }
//
// // Java equivalent of the built-in Action from C#.
// public interface Action<T>
// {
// void call(T target);
// }
//
public class BluetoothClassZeroDiscoveryTask extends AsyncTask<Void, Void, Void>
{
// This is the well-known ID for bluetooth serial port profile (SPP) devices.
public static final UUID BluetoothSerialUuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
private Activity _parent;
private boolean _discoveryComplete = false;
private Action<ArrayList<BluetoothDevice>> _callback;
private ArrayList<BluetoothDevice> _devices = new ArrayList<BluetoothDevice>();
private Calendar _discoveryStartTime;
private SimpleDateFormat _logDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.SSS");
private BluetoothAdapter _adapter;
private ProgressDialog _progressDialog;
public BluetoothClassZeroDiscoveryTask(Activity parent, Action<ArrayList<BluetoothDevice>> callback)
{
_callback = callback;
_parent = parent;
_adapter = BluetoothAdapter.getDefaultAdapter();
IntentFilter foundFilter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
_parent.registerReceiver(mReceiver, foundFilter);
IntentFilter finishedFilter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
_parent.registerReceiver(mReceiver, finishedFilter);
// This task performs a scan for bluetooth devices, which
// takes ~ 12 seconds, so show an indeterminate progress bar.
_progressDialog = ProgressDialog.show(_parent, "", "Discovering bluetooth devices...", true);
}
// Kicks off bluetooth discovery.
#Override
protected Void doInBackground(Void... params)
{
_discoveryStartTime = Calendar.getInstance();
_adapter.startDiscovery();
while (!_discoveryComplete)
{
try
{
Thread.sleep(500);
}
catch (InterruptedException e) { }
}
_adapter.cancelDiscovery();
return null;
}
// Provide notification of results to client.
#Override
protected void onPostExecute(Void result)
{
_progressDialog.dismiss();
_parent.unregisterReceiver(mReceiver);
_callback.call(_devices);
}
// Handler for bluetooth discovery events.
private final BroadcastReceiver mReceiver = new BroadcastReceiver()
{
#Override
public void onReceive(Context context, Intent intent)
{
String action = intent.getAction();
if (BluetoothDevice.ACTION_FOUND.equals(action))
{
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
// If it's already paired, skip it, (we'll add it after the scan completes).
if (device.getBondState() != BluetoothDevice.BOND_BONDED)
{
_devices.add(device);
}
}
else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action))
{
// Add all already-paired devices to the list.
for (BluetoothDevice device : _adapter.getBondedDevices())
{
_devices.add(device);
}
// Trawl through the logs to find any devices that were skipped >:(
try
{
Process process = Runtime.getRuntime().exec("logcat -d -v time *:E");
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(process.getInputStream()));
String line;
Pattern pattern = Pattern.compile("(.{18}).*\\[(.+)\\] class is 0x00 - skip it.");
while ((line = bufferedReader.readLine()) != null)
{
Matcher matcher = pattern.matcher(line);
if (matcher.find())
{
// Found a blocked device, check if it was newly discovered.
// Android log timestamps don't contain the year!?
String logTimeStamp = Integer.toString(_discoveryStartTime.get(Calendar.YEAR)) + "-" + matcher.group(1);
Date logTime = null;
try
{
logTime = _logDateFormat.parse(logTimeStamp);
}
catch (ParseException e) { }
if (logTime != null)
{
if (logTime.after(_discoveryStartTime.getTime()))
{
// Device was discovered during this scan,
// now we want to get the name of the device.
String deviceAddress = matcher.group(2);
BluetoothDevice device = _adapter.getRemoteDevice(deviceAddress);
// In order to get the name, we must attempt to connect to the device.
// This will attempt to pair with the device, and will ask the user
// for a PIN code if one is required.
try
{
BluetoothSocket socket = device.createRfcommSocketToServiceRecord(BluetoothSerialUuid);
socket.connect();
socket.close();
_devices.add(device);
}
catch (IOException e) { }
}
}
}
}
}
catch (IOException e) {}
_discoveryComplete = true;
}
}
};
}
See also:
http://zornsoftware.codenature.info/blog/pairing-spp-bluetooth-devices-with-android-phones.html

Categories

Resources