Badly confused with AsyncTask .. someone please help out .. ty - Android Studio

Am creating a form application which allows users to send a message using http POST request..Am getting a android.os.NetworkOnMainThreadException while running my program. I am fairly new to android dev. Can someone help me by rewriting the network related operation in AsyncTask. If someone can rewrite, i can learn how exactly network tasks can be done using Async. Ty
Code:
public class MainActivity extends Activity {
EditText msgTextField;
Button sendButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//make message text field object
msgTextField = (EditText) findViewById(R.id.msgTextField);
//make button object
sendButton = (Button) findViewById(R.id.sendButton);
}
public void send(View v)
{
//get message from message box
String msg = msgTextField.getText().toString();
//check whether the msg empty or not
if(msg.length()>0) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("localhost");
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("id", "01"));
nameValuePairs.add(new BasicNameValuePair("name", msg));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
httpclient.execute(httppost);
msgTextField.setText(""); //reset the message text field
Toast.makeText(getBaseContext(),"Successfully Booked!!",Toast.LENGTH_SHORT).show();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} else {
//display message if text field is empty
Toast.makeText(getBaseContext(),"All fields are required",Toast.LENGTH_SHORT).show();
}
}
}

any help ??

Hello,
Make a copy of the send(View v) method and name it sendAsync(View v, EditText msgbox).
Like this:
Code:
public Exception sendAsync(View v, EditText msgbox)
{
[B] HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("localhost");[/B]
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("id", "01"));
nameValuePairs.add(new BasicNameValuePair("name", msgbox.getText().toString()));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
httpclient.execute(httppost);
return null;
} catch (ClientProtocolException e) {
return e;
} catch (IOException e) {
return e;
}
}
Next, modify the original send(View v) method like this:
Code:
public void send(View v)
{
//get message from message box
String msg = msgTextField.getText().toString();
//check whether the msg empty or not
if(msg.length()>0) {
MyAsyncTask mAsync = new MyAsyncTask(v, getBaseContext(), msgTextField);
mAsync.execute();
} else {
//display message if text field is empty
Toast.makeText(getBaseContext(),"All fields are required",Toast.LENGTH_SHORT).show();
}
}
You can add the below code inside your activity class (outside the onCreate method)
Code:
private class MyAsyncTask extends AsyncTask<String, Void, String> {
View v;
Context context;
EditText msgbox;
Exception e = null;
public MyAsyncTask(View v_, Conext context_, EditText msgbox_){
this.v = v_;
this.context = context_;
this.msgbox = msgbox_;
}
@Override
protected String doInBackground(String... params) {
//Background operation in a separate thread
//Write here your code to run in the background thread
this.e = sendAsync(v, msgbox);
return null;
}
@Override
protected void onPostExecute(String result) {
//Called on Main UI Thread. Executed after the Background operation, allows you to have access to the UI
if(e==null){
//Successful
msgbox.setText(""); //reset the message text field
Toast.makeText(context,"Successfully Booked!!",Toast.LENGTH_SHORT).show();
}
else{
e.printStackTrace();
}
}
@Override
protected void onPreExecute() {
//Called on Main UI Thread. Executed before the Background operation, allows you to have access to the UI
}
@Override
protected void onProgressUpdate(Void... values) {
//Called on Main UI Thread
}
}
However, HttpClient is deprecated for API Level 22 and above, so you should use HttpURLConnection instead. This may help you out for using HttpURLConnection via POST or GET Method.
Now, the doInBackground method, runs in a background thread, automatically created for you, and so we send the data from there, for not crashing the UI (User Interface) of the Android App. If you want, however, to access some UI components, you can do it in the onPostExecute (it is executed after the doInBackground completes) or in the onPreExecute (it is executed before the doInBackground begins). To learn more about the AsyncTask class, check here.
AsyncTask can be used and for other purposes other than sending data over the Internet. In general, you create a class extending the AsyncTask, pass any parameters that you are going to use in the background thread (but not UI components like EditText, you can pass them though, but use them in the onPreExecute or onPostExecute methods, and not in the doInBackground method), and do the stuff you want to run in the background thread inside the doInBackground method. That way, heavy(time consuming) computations or tasks like sending data over the Internet does not make your UI to crash, meaning that the user can press any buttons (for example) without lag or without waiting for the background task to finish.

i tried .. it didnt work for me .. can u give the full code for this please ?
package com.example.formpost;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity {
EditText msgTextField;
Button sendButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.form);
//make message text field object
msgTextField = (EditText) findViewById(R.id.msgTextField);
//make button object
sendButton = (Button) findViewById(R.id.sendButton);
}
public void send(View v)
{
//get message from message box
String msg = msgTextField.getText().toString();
//check whether the msg empty or not
if(msg.length()>0) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("serverside-script.php");
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("id", "01"));
nameValuePairs.add(new BasicNameValuePair("message", msg));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
httpclient.execute(httppost);
msgTextField.setText(""); //reset the message text field
Toast.makeText(getBaseContext(),"Sent",Toast.LENGTH_SHORT).show();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} else {
//display message if text field is empty
Toast.makeText(getBaseContext(),"All fields are required",Toast.LENGTH_SHORT).show();
}
}
}
Click to expand...
Click to collapse
Thanks bro

I just made a correction on the sendAsync method. It should be as follows (I have also updated my initial post):
Code:
public Exception sendAsync(View v, EditText msgbox)
{
[B] HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("localhost");[/B]
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("id", "01"));
nameValuePairs.add(new BasicNameValuePair("name", msgbox.getText().toString()));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
httpclient.execute(httppost);
return null;
} catch (ClientProtocolException e) {
return e;
} catch (IOException e) {
return e;
}
}
(Replace "localhost" with the actual URL that will handle the POST HTTP request). Also if you are on a local network (LAN), and trying to access the localhost of your PC that is connected to the same LAN as your Android smartphone, then, you should find the local internal IP of your computer, e.g. 192.168.1.1 (you can find that from the command prompt by typing: ipconfig). It's the IPv4 Address on your ethernet or wifi (whatever connection your PC has to the router).
Also make sure that your firewall does not block the connection.
Hope it works. What is the error that you get?

try using volley library for http requests .just a few bunch of line. no need of using async tasks.it will handle it automatically
Sent from my Nexus 4 using Tapatalk

jaison thomas said:
try using volley library for http requests .just a few bunch of line. no need of using async tasks.it will handle it automatically
Sent from my Nexus 4 using Tapatalk
Click to expand...
Click to collapse
Since am new to this whole thing, i wanted to learn with this. It was the only tutorial project i could see. Its been depreciated, but still for learning purpose i wanted to execute it. Still no success.

Related

[Q] How to update a textView every second.

I have a textview that shows your amount of money and i would like the ui to update every second to visually show how much money you have in real time. Would i be able to accomplish this with a timer?, and if so what would it look like.
Hello,
You should do inside your class, outside of any method:
Code:
TextView tv;
String calculatedString;
MyAsyncTask mAsync = null;
Timer timer = null;
TimerTask task = null;
private class MyAsyncTask extends AsyncTask<String, Void, String> {
public MyAsyncTask(){
}
@Override
protected String doInBackground(String... params) {
//Background operation in a separate thread
//Write here your code to run in the background thread
//calculate here whatever you like
calculatedString = ....;
return null;
}
@Override
protected void onPostExecute(String result) {
//Called on Main UI Thread. Executed after the Background operation, allows you to have access to the UI
tv.setText(calculatedString);
}
@Override
protected void onPreExecute() {
//Called on Main UI Thread. Executed before the Background operation, allows you to have access to the UI
}
}
inside the onCreate after super and setContentView:
Code:
tv = (TextView) findViewById(R.id.tv); //your tv id here
final Handler handler = new Handler();
timer = new Timer();
task = new TimerTask() {
@Override
public void run() {
handler.post(new Runnable() {
public void run() {
MyAsyncTask mAsync = new MyAsyncTask();
mAsync.execute();
}
});
}
};
timer.schedule(task, 0, 1000); //Every 1 second
If you still need help, feel free to ask
I have attached 2 screenshots showing the errors i was given after inputting. Any idea how to fix this?
mmdeveloper10 said:
Hello,
You should do inside your class, outside of any method:
Code:
TextView tv;
String calculatedString;
MyAsyncTask mAsync = null;
Timer timer = null;
TimerTask task = null;
private class MyAsyncTask extends AsyncTask<String, Void, String> {
public MyAsyncTask(){
}
@Override
protected String doInBackground(String... params) {
//Background operation in a separate thread
//Write here your code to run in the background thread
//calculate here whatever you like
calculatedString = ....;
return null;
}
@Override
protected void onPostExecute(String result) {
//Called on Main UI Thread. Executed after the Background operation, allows you to have access to the UI
tv.setText(calculatedString);
}
@Override
protected void onPreExecute() {
//Called on Main UI Thread. Executed before the Background operation, allows you to have access to the UI
}
}
inside the onCreate after super and setContentView:
Code:
tv = (TextView) findViewById(R.id.tv); //your tv id here
final Handler handler = new Handler();
timer = new Timer();
task = new TimerTask() {
@Override
public void run() {
handler.post(new Runnable() {
public void run() {
MyAsyncTask mAsync = new MyAsyncTask();
mAsync.execute();
}
});
}
};
timer.schedule(task, 0, 1000); //Every 1 second
If you still need help, feel free to ask
Click to expand...
Click to collapse
Hello,
For the first image:
You have to import the AsyncTask.
add this
Code:
import android.os.AsyncTask;
with the other imports in your java file.
For your second image:
You haven't wrote the line
Code:
setContentView(R.layout.activity_main);
under your super.onCreate(savedInstanceState); and then the code I said above (I said that on my post )
inside onCreate, where activity_main is your xml layout. And you should have inside that layout, a TextView with an id "tv" (or whatever you like)
and then:
Code:
tv = (TextView) findViewById(R.id.tv); //your tv id here
R.id.tv must much the id you have in your layout. Replace it with the actual id of your TextView. If your id is "tv", write R.id.tv, if it is "mytv" write R.id.mytv. ( I said that on my post also)
Can you show your layout file? (XML - your activity_main.xml). You said that you have a TextView Where is your TextView?
Ok I fixed the problems stated and now only have these two errors remaining
mmdeveloper10 said:
Hello,
For the first image:
You have to import the AsyncTask.
add this
Code:
import android.os.AsyncTask;
with the other imports in your java file.
For your second image:
You haven't wrote the line
Code:
setContentView(R.layout.activity_main);
under your super.onCreate(savedInstanceState); and then the code I said above (I said that on my post )
inside onCreate, where activity_main is your xml layout. And you should have inside that layout, a TextView with an id "tv" (or whatever you like)
and then:
Code:
tv = (TextView) findViewById(R.id.tv); //your tv id here
R.id.tv must much the id you have in your layout. Replace it with the actual id of your TextView. If your id is "tv", write R.id.tv, if it is "mytv" write R.id.mytv. ( I said that on my post also)
Can you show your layout file? (XML - your activity_main.xml). You said that you have a TextView Where is your TextView?
Click to expand...
Click to collapse
Have you imported this?
Code:
import java.util.logging.Handler;
If so, change it to
Code:
import android.os.Handler;
Im not at the computer but I think that should solve my issue I will keep you updated
Sent from my HTC6525LVW using XDA Free mobile app
Hey thanks so much its working perfectly now :good:

[Help] Bluetooth app

Hi!
I have some problems with my bluetooth app. I made the setup for a bluetooth server on a Raspberry Pi and I was able to send data to it with my app, but I don't know how to receive data from the server. The server works properly, I tried with the BlueTerm 2 app and I can receive data from it. Can someone help me to implement the receiver in my app?
My code below:
Code:
package com.example.bluetooth1;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.util.UUID;
import com.example.bluetooth1.R;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends Activity {
private static final String TAG = "bluetooth1";
Button btnOn, btnOff;
private BluetoothAdapter btAdapter = null;
private BluetoothSocket btSocket = null;
private OutputStream outStream = null;
// SPP UUID service
private static final UUID MY_UUID = UUID.fromString("94f39d29-7d6d-437d-973b-fba39e49d4ee");
// MAC-address of Bluetooth module (you must edit this line)
private static String address = "00:1A:7D:DA:71:14";
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnOn = (Button) findViewById(R.id.btnOn);
btnOff = (Button) findViewById(R.id.btnOff);
btAdapter = BluetoothAdapter.getDefaultAdapter();
checkBTState();
btnOn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
sendData("esti un prost");
//Toast.makeText(getBaseContext(), "Turn on LED", Toast.LENGTH_SHORT).show();
}
});
btnOff.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
sendData("cel mai prost");
// Toast.makeText(getBaseContext(), "Turn off LED", Toast.LENGTH_SHORT).show();
}
});
}
private BluetoothSocket createBluetoothSocket(BluetoothDevice device) throws IOException {
if(Build.VERSION.SDK_INT >= 10){
try {
final Method m = device.getClass().getMethod("createInsecureRfcommSocketToServiceRecord", new Class[] { UUID.class });
return (BluetoothSocket) m.invoke(device, MY_UUID);
} catch (Exception e) {
Log.e(TAG, "Could not create Insecure RFComm Connection",e);
}
}
return device.createRfcommSocketToServiceRecord(MY_UUID);
}
@Override
public void onResume() {
super.onResume();
// Set up a pointer to the remote node using it's address.
BluetoothDevice device = btAdapter.getRemoteDevice(address);
try {
btSocket = createBluetoothSocket(device);
} catch (IOException e1) {
errorExit("Fatal Error", "In onResume() and socket create failed: " + e1.getMessage() + ".");
}
btAdapter.cancelDiscovery();
try {
btSocket.connect();
} catch (IOException e) {
try {
btSocket.close();
} catch (IOException e2) {
}
}
try {
outStream = btSocket.getOutputStream();
} catch (IOException e) {
errorExit("Fatal Error", "In onResume() and output stream creation failed:" + e.getMessage() + ".");
}
}
private void checkBTState() {
// Check for Bluetooth support and then check to make sure it is turned on
// Emulator doesn't support Bluetooth and will return null
if(btAdapter==null) {
errorExit("Fatal Error", "Bluetooth not support");
} else {
if (btAdapter.isEnabled()) {
Log.d(TAG, "...Bluetooth ON...");
} else {
//Prompt user to turn on Bluetooth
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, 1);
}
}
}
private void errorExit(String title, String message){
Toast.makeText(getBaseContext(), title + " - " + message, Toast.LENGTH_LONG).show();
finish();
}
private void sendData(String message) {
byte[] msgBuffer = message.getBytes();
try {
outStream.write(msgBuffer);
} catch (IOException e) {
String msg = "In onResume() and an exception occurred during write: " + e.getMessage();
if (address.equals("00:00:00:00:00:00"))
msg = msg + ".\n\nUpdate your server address from 00:00:00:00:00:00 to the correct address on line 35 in the java code";
msg = msg + ".\n\nCheck that the SPP UUID: " + MY_UUID.toString() + " exists on server.\n\n";
errorExit("Fatal Error", msg);
}
}
}

Help please : )

Hello everyone,
I have a quick question.
Can someone help me with an algorithm that will:
1. Sort incoming data from Arduino transfered via Bluetooth to the Android App.
2. Sort for example, if i have 1000 data but i only want the important ones that I use to compare with my file.
Thank you guys in advance,
Cookie
cookiey89 said:
Hello everyone,
I have a quick question.
Can someone help me with an algorithm that will:
1. Sort incoming data from Arduino transfered via Bluetooth to the Android App.
2. Sort for example, if i have 1000 data but i only want the important ones that I use to compare with my file.
Thank you guys in advance,
Cookie
Click to expand...
Click to collapse
You'll need a script for that, so keep asking for help because I am unable to
Envoyé de mon SM-G928F en utilisant Tapatalk
You're probably not looking for a specific algorithm, but rather for some technical guidance? How far along are you? Did you get the Bluetooth connection between the two to work? Are you building your own app?
cookiey89 said:
Hello everyone,
I have a quick question.
Can someone help me with an algorithm that will:
1. Sort incoming data from Arduino transfered via Bluetooth to the Android App.
2. Sort for example, if i have 1000 data but i only want the important ones that I use to compare with my file.
Thank you guys in advance,
Cookie
Click to expand...
Click to collapse
Assuming your data is simply some numbers, you can put them in ArrayList and then sort them using Collections.sort() function. For example if you want to get 3 greatest numbers , you can do something like that:
Code:
List<Integer> data = new ArrayList<>();
data.add(5);
data.add(10);
data.add(3);
data.add(20);
data.add(1);
data.add(6);
Collections.sort(data, Comparator.reverseOrder());
List<Integer> topNumbers = data.subList(0, 3);
System.out.println("Top 3 numbers: " + topNumbers);
If you need something more complex, please provide some more information about your data and what you mean by "important"
Hi Everyone,
thank you for the fast responses.
This is my initial plan:
I want to gather data from Arduino via bluetooth to the android app.
From there, I want to "sort" the data in such a way to minimize and specify the data I want to compare to a library.
The data will be analog values from various sensors on the Arduino.
Thanks
Cookie
cookiey89 said:
Hello everyone,
I have a quick question.
Can someone help me with an algorithm that will:
1. Sort incoming data from Arduino transfered via Bluetooth to the Android App.
2. Sort for example, if i have 1000 data but i only want the important ones that I use to compare with my file.
Thank you guys in advance,
Cookie
Click to expand...
Click to collapse
i think , to make that solutions works, you need to insert the datas to database first..
cmiiw
It's Java code of main activity:
package com.example.bluetooth1;
import java.io.IOException;
import java.iutputStream;
import java.lang.reflect.Method;
import java.util.UUID;
import com.example.bluetooth1.R;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends Activity {
private static final String TAG = "bluetooth1";
Button btnOn, btnOff;
private BluetoothAdapter btAdapter = null;
private BluetoothSocket btSocket = null;
private OutputStream outStream = null;
// SPP UUID service
private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
// MAC-address of Bluetooth module (you must edit this line)
private static String address = "00:15:FF:F2:19:5F";
/** Called when the activity is first created. */
@override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnOn = (Button) findViewById(R.id.btnOn);
btnOff = (Button) findViewById(R.id.btnOff);
btAdapter = BluetoothAdapter.getDefaultAdapter();
checkBTState();
btnOn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
sendData("1");
Toast.makeText(getBaseContext(), "Turn on LED", Toast.LENGTH_SHORT).show();
}
});
btnOff.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
sendData("0");
Toast.makeText(getBaseContext(), "Turn off LED", Toast.LENGTH_SHORT).show();
}
});
}
private BluetoothSocket createBluetoothSocket(BluetoothDevice device) throws IOException {
if(Build.VERSION.SDK_INT >= 10){
try {
final Method m = device.getClass().getMethod("createInsecureRfcommSocketToServiceRecord", new Class[] { UUID.class });
return (BluetoothSocket) m.invoke(device, MY_UUID);
} catch (Exception e) {
Log.e(TAG, "Could not create Insecure RFComm Connection",e);
}
}
return device.createRfcommSocketToServiceRecord(MY_UUID);
}
@override
public void onResume() {
super.onResume();
Log.d(TAG, "...onResume - try connect...");
// Set up a pointer to the remote node using it's address.
BluetoothDevice device = btAdapter.getRemoteDevice(address);
// Two things are needed to make a connection:
// A MAC address, which we got above.
// A Service ID or UUID. In this case we are using the
// UUID for SPP.
try {
btSocket = createBluetoothSocket(device);
} catch (IOException e1) {
errorExit("Fatal Error", "In onResume() and socket create failed: " + e1.getMessage() + ".");
}
// Discovery is resource intensive. Make sure it isn't going on
// when you attempt to connect and pass your message.
btAdapter.cancelDiscovery();
// Establish the connection. This will block until it connects.
Log.d(TAG, "...Connecting...");
try {
btSocket.connect();
Log.d(TAG, "...Connection ok...");
} catch (IOException e) {
try {
btSocket.close();
} catch (IOException e2) {
errorExit("Fatal Error", "In onResume() and unable to close socket during connection failure" + e2.getMessage() + ".");
}
}
// Create a data stream so we can talk to server.
Log.d(TAG, "...Create Socket...");
try {
outStream = btSocket.getOutputStream();
} catch (IOException e) {
errorExit("Fatal Error", "In onResume() and output stream creation failed:" + e.getMessage() + ".");
}
}
@override
public void onPause() {
super.onPause();
Log.d(TAG, "...In onPause()...");
if (outStream != null) {
try {
outStream.flush();
} catch (IOException e) {
errorExit("Fatal Error", "In onPause() and failed to flush output stream: " + e.getMessage() + ".");
}
}
try {
btSocket.close();
} catch (IOException e2) {
errorExit("Fatal Error", "In onPause() and failed to close socket." + e2.getMessage() + ".");
}
}
private void checkBTState() {
// Check for Bluetooth support and then check to make sure it is turned on
// Emulator doesn't support Bluetooth and will return null
if(btAdapter==null) {
errorExit("Fatal Error", "Bluetooth not support");
} else {
if (btAdapter.isEnabled()) {
Log.d(TAG, "...Bluetooth ON...");
} else {
//Prompt user to turn on Bluetooth
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, 1);
}
}
}
private void errorExit(String title, String message){
Toast.makeText(getBaseContext(), title + " - " + message, Toast.LENGTH_LONG).show();
finish();
}
private void sendData(String message) {
byte[] msgBuffer = message.getBytes();
Log.d(TAG, "...Send data: " + message + "...");
try {
outStream.write(msgBuffer);
} catch (IOException e) {
String msg = "In onResume() and an exception occurred during write: " + e.getMessage();
if (address.equals("00:00:00:00:00:00"))
msg = msg + ".\n\nUpdate your server address from 00:00:00:00:00:00 to the correct address on line 35 in the java code";
msg = msg + ".\n\nCheck that the SPP UUID: " + MY_UUID.toString() + " exists on server.\n\n";
errorExit("Fatal Error", msg);
}
}
}
MihaelYank said:
It's Java code of main activity:
package com.example.bluetooth1;
import java.io.IOException;
import java.iutputStream;
import java.lang.reflect.Method;
import java.util.UUID;
import com.example.bluetooth1.R;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends Activity {
private static final String TAG = "bluetooth1";
Button btnOn, btnOff;
private BluetoothAdapter btAdapter = null;
private BluetoothSocket btSocket = null;
private OutputStream outStream = null;
// SPP UUID service
private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
// MAC-address of Bluetooth module (you must edit this line)
private static String address = "00:15:FF:F2:19:5F";
/** Called when the activity is first created. */
@override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnOn = (Button) findViewById(R.id.btnOn);
btnOff = (Button) findViewById(R.id.btnOff);
btAdapter = BluetoothAdapter.getDefaultAdapter();
checkBTState();
btnOn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
sendData("1");
Toast.makeText(getBaseContext(), "Turn on LED", Toast.LENGTH_SHORT).show();
}
});
btnOff.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
sendData("0");
Toast.makeText(getBaseContext(), "Turn off LED", Toast.LENGTH_SHORT).show();
}
});
}
private BluetoothSocket createBluetoothSocket(BluetoothDevice device) throws IOException {
if(Build.VERSION.SDK_INT >= 10){
try {
final Method m = device.getClass().getMethod("createInsecureRfcommSocketToServiceRecord", new Class[] { UUID.class });
return (BluetoothSocket) m.invoke(device, MY_UUID);
} catch (Exception e) {
Log.e(TAG, "Could not create Insecure RFComm Connection",e);
}
}
return device.createRfcommSocketToServiceRecord(MY_UUID);
}
@override
public void onResume() {
super.onResume();
Log.d(TAG, "...onResume - try connect...");
// Set up a pointer to the remote node using it's address.
BluetoothDevice device = btAdapter.getRemoteDevice(address);
// Two things are needed to make a connection:
// A MAC address, which we got above.
// A Service ID or UUID. In this case we are using the
// UUID for SPP.
try {
btSocket = createBluetoothSocket(device);
} catch (IOException e1) {
errorExit("Fatal Error", "In onResume() and socket create failed: " + e1.getMessage() + ".");
}
// Discovery is resource intensive. Make sure it isn't going on
// when you attempt to connect and pass your message.
btAdapter.cancelDiscovery();
// Establish the connection. This will block until it connects.
Log.d(TAG, "...Connecting...");
try {
btSocket.connect();
Log.d(TAG, "...Connection ok...");
} catch (IOException e) {
try {
btSocket.close();
} catch (IOException e2) {
errorExit("Fatal Error", "In onResume() and unable to close socket during connection failure" + e2.getMessage() + ".");
}
}
// Create a data stream so we can talk to server.
Log.d(TAG, "...Create Socket...");
try {
outStream = btSocket.getOutputStream();
} catch (IOException e) {
errorExit("Fatal Error", "In onResume() and output stream creation failed:" + e.getMessage() + ".");
}
}
@override
public void onPause() {
super.onPause();
Log.d(TAG, "...In onPause()...");
if (outStream != null) {
try {
outStream.flush();
} catch (IOException e) {
errorExit("Fatal Error", "In onPause() and failed to flush output stream: " + e.getMessage() + ".");
}
}
try {
btSocket.close();
} catch (IOException e2) {
errorExit("Fatal Error", "In onPause() and failed to close socket." + e2.getMessage() + ".");
}
}
private void checkBTState() {
// Check for Bluetooth support and then check to make sure it is turned on
// Emulator doesn't support Bluetooth and will return null
if(btAdapter==null) {
errorExit("Fatal Error", "Bluetooth not support");
} else {
if (btAdapter.isEnabled()) {
Log.d(TAG, "...Bluetooth ON...");
} else {
//Prompt user to turn on Bluetooth
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, 1);
}
}
}
private void errorExit(String title, String message){
Toast.makeText(getBaseContext(), title + " - " + message, Toast.LENGTH_LONG).show();
finish();
}
private void sendData(String message) {
byte[] msgBuffer = message.getBytes();
Log.d(TAG, "...Send data: " + message + "...");
try {
outStream.write(msgBuffer);
} catch (IOException e) {
String msg = "In onResume() and an exception occurred during write: " + e.getMessage();
if (address.equals("00:00:00:00:00:00"))
msg = msg + ".\n\nUpdate your server address from 00:00:00:00:00:00 to the correct address on line 35 in the java code";
msg = msg + ".\n\nCheck that the SPP UUID: " + MY_UUID.toString() + " exists on server.\n\n";
errorExit("Fatal Error", msg);
}
}
}
Click to expand...
Click to collapse
Thank you, I will try it out
andihong said:
i think , to make that solutions works, you need to insert the datas to database first..
cmiiw
Click to expand...
Click to collapse
Can I place the incoming data values into an array? I will referesh the array everytime the array finishes with the code
maddoc42 said:
You're probably not looking for a specific algorithm, but rather for some technical guidance? How far along are you? Did you get the Bluetooth connection between the two to work? Are you building your own app?
Click to expand...
Click to collapse
Hi,
Yes i'm building my own app. We have split the work. Im responsible for the app development side.
{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
I've drafted a state diagram of how I want my app to function.
Can anyone give me a hand on starting to implement this? I am fairly new to coding-just self learning.
Thanks,
Cookie :fingers-crossed:

Need help android studio authentication

I am not able to authenticate using the following username and password.Plz help me figure out guys what i am doing wrong.
I am using version 2.23.Even if i enter the correct username and password it gives me Username and pass is incorrect.
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.*;
import android.*;
public class MainActivity extends AppCompatActivity {
private static Button button;
private static EditText etext; //Username
private static EditText etext2; //Password
private static TextView text; //Text infornt of Attempt
int counter = 5;
@override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
onButton();
}
public void onButton() {
button = (Button)findViewById(R.id.button);
etext =(EditText)findViewById(R.id.editText);
etext =(EditText)findViewById(R.id.editText2);
text =(TextView)findViewById(R.id.textView3);
text.setText(Integer.toString(counter));
button.setOnClickListener(
new View.OnClickListener() {
@override
public void onClick(View view) {
if(etext.getText().toString()==("user") && (etext2.getText().toString()==("pass")) ) {
Toast.makeText(MainActivity.this, "Username and Password is correct", Toast.LENGTH_LONG).show();
Intent intent = new Intent("com.wahid.logan.SecondActivity");
startActivity(intent);
}
else {
Toast.makeText(MainActivity.this,"Username and Password is incorrect",Toast.LENGTH_LONG).show();
counter--;
text.setText(Integer.toString(counter));
if(counter ==0) {
button.setEnabled(false);
}
}
}
}
);
}
}
frankruss2013 said:
if(etext.getText().toString()==("user") && (etext2.getText().toString()==("pass")) )
Click to expand...
Click to collapse
Have you double checked this logic ? The brackets look a little off to me. Try just setting the test condition to true for debugging. Or try using variables for each conditional test and monitor the variable values in the debugger.

Using Intent(send mail) in Navigation drawer

I want to send mail from Navigation Drawer using the intent. First, my MainActivity.
Code:
else if(id==R.id.nav_mail) {
fragment = new MailFragment();
}
and MailFragment.
Code:
public class MailFragment extends Fragment {
public MailFragment() {
Intent email = new Intent(Intent.ACTION_SEND);
email.setType("plain/text");
String[] address = {"********@gmail.com"};
email.putExtra(Intent.EXTRA_EMAIL, address);
email.putExtra(Intent.EXTRA_SUBJECT, "Subject___****");
email.putExtra(Intent.EXTRA_TEXT, "Text___****.\n\n");
startActivity(email);
}
// @Override
// public View onCreateView(LayoutInflater inflater, ViewGroup container,
// Bundle savedInstanceState) {
// TextView textView = new TextView(getActivity());
// textView.setText(R.string.hello_blank_fragment);
// return textView;
// }
}
Run to create crash. The reason why I used to use fragment is because I made the simple screen change function fragment.
If you need more code, comment plz.
I didn't get what you are trying to do. If you are trying to invoke the "Select your mail app" screen and then send a message thru the Intent all of this when the user clicks on a row on the drawer then you should just copy the code to
Code:
else if(id==R.id.nav_mail) {
// here
}
without switching any fragment.
By the way, as far as I know, the fragment's public constructor must be empty.
You cannot do it from Fragment's constructor. Move your code to onActivityCreated() method.
qlife1146 said:
I want to send mail from Navigation Drawer using the intent. First, my MainActivity.
Code:
else if(id==R.id.nav_mail) {
fragment = new MailFragment();
}
and MailFragment.
Code:
public class MailFragment extends Fragment {
public MailFragment() {
Intent email = new Intent(Intent.ACTION_SEND);
email.setType("plain/text");
String[] address = {"********@gmail.com"};
email.putExtra(Intent.EXTRA_EMAIL, address);
email.putExtra(Intent.EXTRA_SUBJECT, "Subject___****");
email.putExtra(Intent.EXTRA_TEXT, "Text___****.\n\n");
startActivity(email);
}
// @Override
// public View onCreateView(LayoutInflater inflater, ViewGroup container,
// Bundle savedInstanceState) {
// TextView textView = new TextView(getActivity());
// textView.setText(R.string.hello_blank_fragment);
// return textView;
// }
}
Run to create crash. The reason why I used to use fragment is because I made the simple screen change function fragment.
If you need more code, comment plz.
Click to expand...
Click to collapse
Creating a new Intent in the constructor is a really bad idea. An example from the android's developer guide
Code:
public class MainActivity extends AppCompatActivity {
public static final String EXTRA_MESSAGE = "com.example.myfirstapp.MESSAGE";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
/** Called when the user taps the Send button */
public void sendMessage(View view) {
Intent intent = new Intent(this, DisplayMessageActivity.class);
EditText editText = (EditText) findViewById(R.id.editText);
String message = editText.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message);
startActivity(intent);
}
}

Categories

Resources