android ui hangs while writting to a bluetooth device from an activity - java

I am new to android + bluetooth. I am trying to write a simple rfcomm client app which talks to a rfcomm server running on a embedded platfrom. When my application starts it show a listview of paired devices and on clicking one of thoes devices it jumps to a second activity. In this activity I opens a bluetooth socket and connects to it. As soon as I jump to a new activity my UI sort of hangs. This new activity has two buttons. Onclick of these buttons I send data to bluetooth server. But my UI kind of hangs in this activity, once I click a button it takes ages to respond and it generates a error message.
My codes looks like this:
package com.example.bluetoothapp2;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Set;
import java.util.UUID;
import android.app.Activity;
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.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
// Return Intent extra
public static String EXTRA_DEVICE_ADDRESS = "device_address";
public int REQUEST_ENABLE_BT = 1;// Just defining a flag
//Define a local bluetooth adapter variable to get id of default Adapter
public BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
//Adapter for LIST ITEMS FOR PAIRED DEVICES
public ArrayAdapter<String> mPairedDevicesArrayAdapter;
//Array to store list data for paired device
ArrayList<String> itemPairedArray = new ArrayList<String> ();
//Adapter for LIST ITEMS FOR NEW DEVICES
public ArrayAdapter<String> mNewDevicesArrayAdapter;
//Array to store list data for paired device
ArrayList<String> itemNewDvcArray = new ArrayList<String> ();
//RECORDING HOW MUCH TIMES BUTTON WAS CLICKED
int clickCounter=0;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
}
private void init()
{
//GetListId from Layout
ListView pairedListView = (ListView) findViewById(R.id.listPairedDvc);
ListView newListView = (ListView) findViewById(R.id.listAvailableDvc);
//Bind the list with listview in layout
mPairedDevicesArrayAdapter= new ArrayAdapter<String>(this,android.R.layout.simple_expandable_list_item_1,itemPairedArray);
mNewDevicesArrayAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_expandable_list_item_1,itemNewDvcArray);
//Set the adapter to list view (bind a adapter to listview in layout)
pairedListView.setAdapter(mPairedDevicesArrayAdapter);
newListView.setAdapter(mNewDevicesArrayAdapter);
pairedListView.setOnItemClickListener(mDeviceClickListener);
// Register the BroadcastReceiver
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mReceiver, filter); // Don't forget to unregister during onDestroy
// Register for broadcasts when discovery has finished
filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
this.registerReceiver(mReceiver, filter);
// Register for broadcasts when discovery has finished
filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
this.registerReceiver(mReceiver, filter);
// Get a set of currently paired devices
Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
// If there are paired devices, add each one to the ArrayAdapter
if (pairedDevices.size() > 0)
{
/*findViewById(R.id.title_paired_devices).setVisibility(View.VISIBLE);*/
for (BluetoothDevice device : pairedDevices)
{
itemPairedArray.add(device.getName() + " => "+ device.getAddress());
}
}
else
{
itemPairedArray.add("noDevices");
}
//Check if device has bluetooth
if(mBluetoothAdapter == null)
{
Toast.makeText(this, "Bluetooth is not available", Toast.LENGTH_LONG).show();
finish();
return;
}
//Check if it is enabled or not
if(!mBluetoothAdapter.isEnabled())
{
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
}
//METHOD WHICH WILL HANDLE DYNAMIC INSERTION
public void addItems(View v)
{
//itemPairedArray.add("Clicked : "+clickCounter++); //Just for debugging
//itemNewDvcArray.add("Clicked : "+clickCounter++); //Just for debugging
//itemNewDvcArray.add("NoDevice");
startDiscovery() ;
//mPairedDevicesArrayAdapter.notifyDataSetChanged();
mNewDevicesArrayAdapter.notifyDataSetChanged();
}
//method to start discovery
private void startDiscovery()
{
// TODO Auto-generated method stub
// If we're already discovering, stop it
if (mBluetoothAdapter.isDiscovering())
{
mBluetoothAdapter.cancelDiscovery();
}
// Request discover from BluetoothAdapter
mBluetoothAdapter.startDiscovery();
}
protected void onDestroy()
{
super.onDestroy();
// Make sure we're not doing discovery anymore
if (mBluetoothAdapter != null)
{
mBluetoothAdapter.cancelDiscovery();
}
// Unregister broadcast listeners
this.unregisterReceiver(mReceiver);
}
// The BroadcastReceiver that listens for discovered devices and
// changes the title when discovery is finished
private final BroadcastReceiver mReceiver = new BroadcastReceiver()
{
public void onReceive(Context context, Intent intent)
{
String action = intent.getAction();
// When discovery finds a device
if (BluetoothDevice.ACTION_FOUND.equals(action))
{
// Get the BluetoothDevice object from the Intent
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
// If it's already paired, skip it, because it's been listed already
if (device.getBondState() != BluetoothDevice.BOND_BONDED)
{
// Add the name and address to an array adapter to show in a ListView
itemNewDvcArray.add(device.getName() +" => "+ device.getAddress());
}
}
}
};
// The on-click listener for all devices in the ListViews
private OnItemClickListener mDeviceClickListener = new OnItemClickListener()
{
public void onItemClick(AdapterView<?> av, View v, int arg2, long arg3)
{
// Get the device MAC address, which is the last 17 chars in the View
String info = ((TextView) v).getText().toString();
String address = info.substring(info.length() - 17);
//Toast.makeText(getApplicationContext(), address, 0).show();
// Create the result Intent and include the MAC address
Intent intent = new Intent(MainActivity.this,ConnectActivity.class);
intent.putExtra(EXTRA_DEVICE_ADDRESS, address);
startActivity(intent);
}
};
}
package com.example.bluetoothapp2;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.UUID;
import android.app.Activity;
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.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class ConnectActivity extends Activity {
// Unique UUID for this application
public static final UUID MY_UUID_INSECURE = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
String address;
protected static final int SUCCESS_CONNECT = 0;
protected static final int MESSAGE_READ = 1;
public BluetoothSocket mmSocket;
public InputStream mmInStream;
public OutputStream mmOutStream;
String tag = "debugging";
private BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
Handler mHandler = new Handler(){
#Override
public void handleMessage(Message msg)
{
// TODO Auto-generated method stub
Log.i(tag, "in handler");
super.handleMessage(msg);
switch(msg.what){
case SUCCESS_CONNECT:
// DO something
ConnectedThread connectedThread = new ConnectedThread((BluetoothSocket)msg.obj);
//Toast.makeText(getApplicationContext(), "CONNECT", 0).show();
String s = "successfully connected";
connectedThread.write(s.getBytes());
Log.i(tag, "connected");
break;
case MESSAGE_READ:
byte[] readBuf = (byte[])msg.obj;
String string = new String(readBuf);
//Toast.makeText(getApplicationContext(), string, 0).show();
break;
}
}
};
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_connect);
// Get the message from the intent
Intent intent = getIntent();
address = intent.getStringExtra(MainActivity.EXTRA_DEVICE_ADDRESS);
// Create the text view
TextView textView = (TextView)findViewById(R.id.addrs);
//textView.setTextSize(40);
textView.setText(address);
connect();
}
//method to start discovery
public void connect()
{
// Get the BluetoothDevice object
BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
//Toast.makeText(getApplicationContext(),"connecting", 0).show();
ConnectThread connect = new ConnectThread(device) ;
connect.start();
}
//Thread for establising a connection
private class ConnectThread extends Thread
{
private final BluetoothSocket mmSocket;
private final BluetoothDevice mmDevice;
public ConnectThread(BluetoothDevice device)
{
// Use a temporary object that is later assigned to mmSocket,
// because mmSocket is final
BluetoothSocket tmp = null;
mmDevice = device;
// Get a BluetoothSocket to connect with the given BluetoothDevice
try {
// MY_UUID is the app's UUID string, also used by the server code
tmp = device.createRfcommSocketToServiceRecord(MY_UUID_INSECURE);
} catch (IOException e) { }
mmSocket = tmp;
}
public void run()
{
// Cancel discovery because it will slow down the connection
mBluetoothAdapter.cancelDiscovery();
try {
// Connect the device through the socket. This will block
// until it succeeds or throws an exception
mmSocket.connect();
} catch (IOException connectException) {
// Unable to connect; close the socket and get out
try {
mmSocket.close();
} catch (IOException closeException) { }
return;
}
// Do work to manage the connection (in a separate thread)
//manageConnectedSocket(mmSocket);
mHandler.obtainMessage(SUCCESS_CONNECT, mmSocket).sendToTarget();
}
/** Will cancel an in-progress connection, and close the socket */
public void cancel()
{
try
{
mmSocket.close();
} catch (IOException e) { }
}
}
private class ConnectedThread extends Thread
{
public ConnectedThread(BluetoothSocket socket) {
mmSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;
// Get the input and output streams, using temp objects because
// member streams are final
try {
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) { }
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
public void run() {
byte[] buffer ; // buffer store for the stream
int bytes; // bytes returned from read()
// Keep listening to the InputStream until an exception occurs
while (true) {
try {
// Read from the InputStream
buffer = new byte[1024];
bytes = mmInStream.read(buffer);
// Send the obtained bytes to the UI activity
mHandler.obtainMessage(MESSAGE_READ, bytes, -1, buffer).sendToTarget();
} catch (IOException e) {
break;
}
}
}
/* Call this from the main activity to send data to the remote device */
public void write(byte[] bytes) {
try {
//a delay of 20ms occurs after each flush...
mmOutStream.write(bytes);
mmOutStream.flush();
} catch (IOException e) { }
}
/* Call this from the main activity to shutdown the connection */
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) { }
}
}
//method to start discovery
public void ledOn(View v ) throws IOException
{
//Toast.makeText(getApplicationContext(),"LED ON", 0).show();
mmOutStream.write('o');
}
//method to start discovery
public void ledOff(View v ) throws IOException
{
//Toast.makeText(getApplicationContext(),"LED OFF", 0).show();
mmOutStream.write('f');
}
public void disconnectCntn(View v ) throws IOException
{
String msg = "Disconnect";
mmOutStream.write(msg.getBytes());
// close the connection
mmOutStream.close();
mmInStream.close();
// close the connection
if (mmSocket != null)
try {
mmSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return;
}
}
I get following error messages
08-19 13:09:55.833: D/AndroidRuntime(5221): Shutting down VM
08-19 13:09:55.834: W/dalvikvm(5221): threadid=1: thread exiting with uncaught exception (group=0x41cc29a8)
08-19 13:09:55.847: E/AndroidRuntime(5221): FATAL EXCEPTION: main
08-19 13:09:55.847: E/AndroidRuntime(5221): java.lang.IllegalStateException: Could not execute method of the activity
08-19 13:09:55.847: E/AndroidRuntime(5221): at android.view.View$1.onClick(View.java:3606)
08-19 13:09:55.847: E/AndroidRuntime(5221): at android.view.View.performClick(View.java:4211)
08-19 13:09:55.847: E/AndroidRuntime(5221): at android.view.View$PerformClick.run(View.java:17446)
08-19 13:09:55.847: E/AndroidRuntime(5221): at android.os.Handler.handleCallback(Handler.java:725)
08-19 13:09:55.847: E/AndroidRuntime(5221): at android.os.Handler.dispatchMessage(Handler.java:92)
08-19 13:09:55.847: E/AndroidRuntime(5221): at android.os.Looper.loop(Looper.java:153)
08-19 13:09:55.847: E/AndroidRuntime(5221): at android.app.ActivityThread.main(ActivityThread.java:5299)
08-19 13:09:55.847: E/AndroidRuntime(5221): at java.lang.reflect.Method.invokeNative(Native Method)
08-19 13:09:55.847: E/AndroidRuntime(5221): at java.lang.reflect.Method.invoke(Method.java:511)
08-19 13:09:55.847: E/AndroidRuntime(5221): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833)
08-19 13:09:55.847: E/AndroidRuntime(5221): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
08-19 13:09:55.847: E/AndroidRuntime(5221): at dalvik.system.NativeStart.main(Native Method)
08-19 13:09:55.847: E/AndroidRuntime(5221): Caused by: java.lang.reflect.InvocationTargetException
08-19 13:09:55.847: E/AndroidRuntime(5221): at java.lang.reflect.Method.invokeNative(Native Method)
08-19 13:09:55.847: E/AndroidRuntime(5221): at java.lang.reflect.Method.invoke(Method.java:511)
08-19 13:09:55.847: E/AndroidRuntime(5221): at android.view.View$1.onClick(View.java:3601)
08-19 13:09:55.847: E/AndroidRuntime(5221): ... 11 more
08-19 13:09:55.847: E/AndroidRuntime(5221): Caused by: java.io.IOException: [JSR82] write: write() failed.
08-19 13:09:55.847: E/AndroidRuntime(5221): at android.bluetooth.BluetoothSocket.write(BluetoothSocket.java:702)
08-19 13:09:55.847: E/AndroidRuntime(5221): at android.bluetooth.BluetoothOutputStream.write(BluetoothOutputStream.java:56)
08-19 13:09:55.847: E/AndroidRuntime(5221): at com.example.bluetoothapp2.ConnectActivity.ledOn(ConnectActivity.java:213)
08-19 13:09:55.847: E/AndroidRuntime(5221): ... 14 more
Sorry for such a long post. Any idea why is the UI hangs and what could be causing the error.
Thanks
Tama

ConnectedThread is instantiated, however we have skipped the part which starts the thread, fancy calling start() on it? connectedThread.start() which will keep it listening on a socket for any data written.
ConnectedThread connectedThread = new ConnectedThread((BluetoothSocket)msg.obj);
//add this line
connectedThread.start()
//Toast.makeText(getApplicationContext(), "CONNECT", 0).show();
String s = "successfully connected";
connectedThread.write(s.getBytes());

Related

Connect Bluetooth Android Client to Bluetooth Java Server

I've been following these two posts SPP Server and Client and this stackoverflow post. I have the server running on a Linux VM and the Android app running on a Samsung Galaxy S6. When I run the server code in Intellij, it says:
"Server Started. Waiting for clients to connect".
When I run the Android app, I get the following Alert box saying:
"Fatal Error. In OnResume()and an exception occurred during write: socket closed.
Check that the SPP UUID: 00001101-0000-1000-8000-00805F9B34FB exists on server. Press OK to exit.
Why is this happening and how can I resolve it so the server will connect and receive a string from the Android app?
SPP Server Code:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import javax.bluetooth.*;
import javax.microedition.io.*;
public class SampleSPPServer {
//start server
private void startServer() throws IOException{
//Create a UUID for SPP
UUID uuid = new UUID("0000110100001000800000805F9B34FB", false);
//Create the servicve url
String connectionString = “btspp://localhost:” + uuid +”;name=Sample
SPP Server”;
//open server url
StreamConnectionNotifier streamConnNotifier =
(StreamConnectionNotifier)Connector.open( connectionString );
//Wait for client connection
System.out.println(“\nServer Started. Waiting for clients to connect…”);
StreamConnection connection=streamConnNotifier.acceptAndOpen();
RemoteDevice dev = RemoteDevice.getRemoteDevice(connection);
System.out.println(“Remote device address: “+dev.getBluetoothAddress());
System.out.println(“Remote device name: “+dev.getFriendlyName(true));
//read string from spp client
InputStream inStream=connection.openInputStream();
BufferedReader bReader=new BufferedReader(new
InputStreamReader(inStream));
String lineRead=bReader.readLine();
System.out.println(lineRead);
//send response to spp client
OutputStream outStream=connection.openOutputStream();
PrintWriter pWriter=new PrintWriter(new OutputStreamWriter(outStream));
pWriter.write(“Response String from SPP Server\r\n”);
pWriter.flush();
pWriter.close();
streamConnNotifier.close();
}
public static void main(String[] args) throws IOException {
//display local device address and name
LocalDevice localDevice = LocalDevice.getLocalDevice();
System.out.println(“Address: “+localDevice.getBluetoothAddress());
System.out.println(“Name: “+localDevice.getFriendlyName());
SampleSPPServer sampleSPPServer=new SampleSPPServer();
sampleSPPServer.startServer();
}
}
Android Client Code:
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.UUID;
public class BluetoothClient extends AppCompatActivity {
TextView out;
private static final int REQUEST_ENABLE_BT = 1;
private BluetoothAdapter btAdapter = null;
private BluetoothSocket btSocket = null;
private OutputStream outStream = null;
// Well known SPP UUID
private static final UUID MY_UUID =
UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
// Insert your server's MAC address
private static String address = "00:10:60:AA:B9:B2";
/** Called when the activity is first created. */
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bluetooth_client);
out = (TextView) findViewById(R.id.out);
out.append("\n...In onCreate()...");
btAdapter = BluetoothAdapter.getDefaultAdapter();
CheckBTState();
}
public void onStart() {
super.onStart();
out.append("\n...In onStart()...");
}
public void onResume() {
super.onResume();
out.append("\n...In onResume...\n...Attempting client 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 = device.createRfcommSocketToServiceRecord(MY_UUID);
} catch (IOException e) {
AlertBox("Fatal Error", "In onResume() and socket create failed: " + e.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.
try {
btSocket.connect();
out.append("\n...Connection established and data link opened...");
} catch (IOException e) {
try {
btSocket.close();
} catch (IOException e2) {
AlertBox("Fatal Error", "In onResume() and unable to close socket during connection failure" + e2.getMessage() + ".");
}
}
// Create a data stream so we can talk to server.
out.append("\n...Sending message to server...");
String message = "Hello from Android.\n";
out.append("\n\n...The message that we will send to the server is: "+message);
try {
outStream = btSocket.getOutputStream();
} catch (IOException e) {
AlertBox("Fatal Error", "In onResume() and output stream creation failed:" + e.getMessage() + ".");
}
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 37 in the java code";
msg = msg + ".\n\nCheck that the SPP UUID: " + MY_UUID.toString() + " exists on server.\n\n";
AlertBox("Fatal Error", msg);
}
}
public void onPause() {
super.onPause();
//out.append("\n...Hello\n");
InputStream inStream;
try {
inStream = btSocket.getInputStream();
BufferedReader bReader=new BufferedReader(new InputStreamReader(inStream));
String lineRead=bReader.readLine();
out.append("\n..."+lineRead+"\n");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
out.append("\n...In onPause()...");
if (outStream != null) {
try {
outStream.flush();
} catch (IOException e) {
AlertBox("Fatal Error", "In onPause() and failed to flush output stream: " + e.getMessage() + ".");
}
}
try {
btSocket.close();
} catch (IOException e2) {
AlertBox("Fatal Error", "In onPause() and failed to close socket." + e2.getMessage() + ".");
}
}
public void onStop() {
super.onStop();
out.append("\n...In onStop()...");
}
public void onDestroy() {
super.onDestroy();
out.append("\n...In onDestroy()...");
}
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) {
AlertBox("Fatal Error", "Bluetooth Not supported. Aborting.");
} else {
if (btAdapter.isEnabled()) {
out.append("\n...Bluetooth is enabled...");
} else {
//Prompt user to turn on Bluetooth
Intent enableBtIntent = new Intent(btAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
}
}
public void AlertBox( String title, String message ){
new AlertDialog.Builder(this)
.setTitle( title )
.setMessage( message + " Press OK to exit." )
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
finish();
}
}).show();
}
}
Android Studio Logcat:
android.view.WindowLeaked: Activity com.example.toby.btclientapp.BluetoothClient has leaked window com.android.internal.policy.PhoneWindow$DecorView{b73d40d V.E...... R.....I. 0,0-1368,1249} that was originally added here
at android.view.ViewRootImpl.<init>(ViewRootImpl.java:569)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:326)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:91)
at android.app.Dialog.show(Dialog.java:350)
at android.support.v7.app.AlertDialog$Builder.show(AlertDialog.java:955)
at com.example.toby.btclientapp.BluetoothClient.AlertBox(BluetoothClient.java:181)
at com.example.toby.btclientapp.BluetoothClient.onResume(BluetoothClient.java:107)
at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1286)
at android.app.Activity.performResume(Activity.java:6987)
at android.app.ActivityThread.performResumeActivity(ActivityThread.java:4145)
at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:4250)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3361)
at android.app.ActivityThread.access$1100(ActivityThread.java:222)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1795)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:158)
at android.app.ActivityThread.main(ActivityThread.java:7229)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
07-26 13:09:21.574 3857-3857/? E/WindowManager: android.view.WindowLeaked: Activity com.example.toby.btclientapp.BluetoothClient has leaked window com.android.internal.policy.PhoneWindow$DecorView{9723488 V.E...... R....... 0,0-1368,1249} that was originally added here
at android.view.ViewRootImpl.<init>(ViewRootImpl.java:569)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:326)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:91)
at android.app.Dialog.show(Dialog.java:350)
at android.support.v7.app.AlertDialog$Builder.show(AlertDialog.java:955)
at com.example.toby.btclientapp.BluetoothClient.AlertBox(BluetoothClient.java:181)
at com.example.toby.btclientapp.BluetoothClient.onResume(BluetoothClient.java:107)
at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1286)
at android.app.Activity.performResume(Activity.java:6987)
at android.app.ActivityThread.performResumeActivity(ActivityThread.java:4145)
at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:4250)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1839)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:158)
at android.app.ActivityThread.main(ActivityThread.java:7229)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
07-26 13:09:21.574 3857-3857/? E/WindowManager: android.view.WindowLeaked: Activity com.example.toby.btclientapp.BluetoothClient has leaked window com.android.internal.policy.PhoneWindow$DecorView{cea821b V.E...... R....... 0,0-1368,799} that was originally added here
at android.view.ViewRootImpl.<init>(ViewRootImpl.java:569)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:326)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:91)
at android.app.Dialog.show(Dialog.java:350)
at android.support.v7.app.AlertDialog$Builder.show(AlertDialog.java:955)
at com.example.toby.btclientapp.BluetoothClient.AlertBox(BluetoothClient.java:181)
at com.example.toby.btclientapp.BluetoothClient.onPause(BluetoothClient.java:135)
at android.app.Activity.performPause(Activity.java:7033)
at android.app.Instrumentation.callActivityOnPause(Instrumentation.java:1339)
at android.app.ActivityThread.performPauseActivity(ActivityThread.java:4577)
at android.app.ActivityThread.performPauseActivity(ActivityThread.java:4550)
at android.app.ActivityThread.handlePauseActivity(ActivityThread.java:4525)
at android.app.ActivityThread.access$1300(ActivityThread.java:222)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1813)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:158)
at android.app.ActivityThread.main(ActivityThread.java:7229)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
I needed to change the MAC address of the Bluetooth adapter. It works now.

Unable to insert documents into mongodb database gives NetworkOnMainthread EXception

Im making an android app to fetch data from user and store it in a mongodb database
mongodb runs on localhost:27017 and im able to connect to it using 10.0.3.2:27017 on genymotion emulator
here is LoginActivity.java
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.TextView;
import com.facebook.AccessToken;
import com.facebook.AccessTokenTracker;
import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.FacebookSdk;
import com.facebook.GraphRequest;
import com.facebook.GraphResponse;
import com.facebook.Profile;
import com.facebook.ProfileTracker;
import com.facebook.login.LoginResult;
import com.facebook.login.widget.LoginButton;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
import org.json.JSONException;
import org.json.JSONObject;
public class LoginActivity extends AppCompatActivity {
static DB db;
static DBCollection locations;
public String name,middlename,surname,userid,profilelink,imageUrl,emailid,gender,birthday;
private CallbackManager callbackManager;
private AccessTokenTracker accessTokenTracker;
private ProfileTracker profileTracker;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getApplicationContext());
setContentView(R.layout.activity_login);
callbackManager = CallbackManager.Factory.create();
accessTokenTracker = new AccessTokenTracker() {
#Override
protected void onCurrentAccessTokenChanged(AccessToken oldToken, AccessToken newToken) {
}
};
profileTracker = new ProfileTracker() {
#Override
protected void onCurrentProfileChanged(Profile oldProfile, Profile newProfile) {
nextActivity(newProfile);
}
};
accessTokenTracker.startTracking();
profileTracker.startTracking();
LoginButton loginButton = (LoginButton)findViewById(R.id.login_button);
FacebookCallback<LoginResult> callback = new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
Profile profile = Profile.getCurrentProfile();
nextActivity(profile);
GraphRequest request = GraphRequest.newMeRequest(AccessToken.getCurrentAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object, GraphResponse response) {
Log.v("JSON",response.toString());
try {
emailid=object.getString("email");
gender=object.getString("gender");
birthday=object.getString("birthday");
TextView nameView6 = (TextView)findViewById(R.id.emailr);
nameView6.setText(emailid);
TextView nameView7 = (TextView)findViewById(R.id.genderr);
nameView7.setText(gender);
TextView nameView8 = (TextView)findViewById(R.id.birthdayr);
nameView8.setText(birthday);
String[] dset={emailid,gender,birthday};
yalla(dset);
} catch (JSONException e) {
e.printStackTrace();
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "email,gender,birthday");
request.setParameters(parameters);
request.executeAsync();
}
#Override
public void onCancel() {
}
#Override
public void onError(FacebookException e) {
}
};
loginButton.setReadPermissions("user_friends");
loginButton.setReadPermissions("public_profile");
loginButton.setReadPermissions("email");
loginButton.setReadPermissions("user_birthday");
loginButton.registerCallback(callbackManager, callback);
}
#Override
protected void onResume() {
super.onResume();
//Facebook login
Profile profile = Profile.getCurrentProfile();
nextActivity(profile);
}
#Override
protected void onPause() {
super.onPause();
}
protected void onStop() {
super.onStop();
accessTokenTracker.stopTracking();
profileTracker.stopTracking();
}
#Override
protected void onActivityResult(int requestCode, int responseCode, Intent intent) {
super.onActivityResult(requestCode, responseCode, intent);
callbackManager.onActivityResult(requestCode, responseCode, intent);
}
private void nextActivity(Profile profile){
if(profile != null){
Intent main = new Intent(LoginActivity.this, MainActivity.class);
main.putExtra("name", profile.getFirstName());
main.putExtra("middlename", profile.getMiddleName());
main.putExtra("surname", profile.getLastName());
main.putExtra("userid", profile.getId());
main.putExtra("profilelink", profile.getLinkUri());
main.putExtra("imageUrl", profile.getProfilePictureUri(200,200).toString());
startActivity(main);
}
}
public static void yalla(String[] args){
String[] dset;
dset=args;
//try {
String uri = "mongodb://10.0.3.2:27017";
Log.v("enterhere", dset[0]);
MongoClientURI mongoClientURI=new MongoClientURI(uri);
//MongoClient mongoClient = new MongoClient("mongodb://10.0.3.2:27017/test");
Log.v("connectedserver", dset[0]);
MongoClient mongoClient = new MongoClient(mongoClientURI);
MongoDatabase database = mongoClient.getDatabase("users");
Log.v("Connect to database successfully",database.getName());
MongoCollection mongoCollection = database.getCollection("assest");
Log.v("collection", dset[0]);
Document doc = new Document("emailid", dset[0])
.append("gender", dset[1])
.append("birthday", dset[2]);
Log.v("document update", dset[0]);
mongoCollection.insertOne(doc);
Log.v("doc insertion", dset[0]);
mongoClient.close();
//} catch (MongoException e)
//{
// e.getStackTrace();
//}
}
}
Error on android studio
V/document update: zissujith#gmail.com
I/cluster: No server chosen by PrimaryServerSelector from cluster description ClusterDescription{type=UNKNOWN, connectionMode=SINGLE, all=[ServerDescription{address=10.0.3.2:27017, type=UNKNOWN, state=CONNECTING}]}. Waiting for 30000 ms before timing out
I/connection: Opened connection [connectionId{localValue:1, serverValue:17}] to 10.0.3.2:27017
I/cluster: Monitor thread successfully connected to server with description ServerDescription{address=10.0.3.2:27017, type=STANDALONE, state=CONNECTED, ok=true, version=ServerVersion{versionList=[3, 0, 14]}, minWireVersion=0, maxWireVersion=3, electionId=null, maxDocumentSize=16777216, roundTripTimeNanos=9233253}
D/dalvikvm: GC_CONCURRENT freed 413K, 5% free 12382K/12935K, paused 11ms+1ms, total 17ms
I/connection: Closed connection [connectionId{localValue:2}] to 10.0.3.2:27017 because the underlying connection was closed.
D/AndroidRuntime: Shutting down VM
W/dalvikvm: threadid=1: thread exiting with uncaught exception (group=0xa62fe288)
E/AndroidRuntime: FATAL EXCEPTION: main
com.mongodb.MongoException: android.os.NetworkOnMainThreadException
at com.mongodb.connection.InternalStreamConnection.open(InternalStreamConnection.java:125)
at com.mongodb.connection.UsageTrackingInternalConnection.open(UsageTrackingInternalConnection.java:46)
at com.mongodb.connection.DefaultConnectionPool$PooledConnection.open(DefaultConnectionPool.java:366)
at com.mongodb.connection.DefaultConnectionPool.get(DefaultConnectionPool.java:94)
at com.mongodb.connection.DefaultConnectionPool.get(DefaultConnectionPool.java:80)
at com.mongodb.connection.DefaultServer.getConnection(DefaultServer.java:69)
at com.mongodb.binding.ClusterBinding$ClusterBindingConnectionSource.getConnection(ClusterBinding.java:86)
at com.mongodb.operation.OperationHelper.withConnectionSource(OperationHelper.java:184)
at com.mongodb.operation.OperationHelper.withConnection(OperationHelper.java:177)
at com.mongodb.operation.MixedBulkWriteOperation.execute(MixedBulkWriteOperation.java:141)
at com.mongodb.operation.MixedBulkWriteOperation.execute(MixedBulkWriteOperation.java:72)
at com.mongodb.Mongo.execute(Mongo.java:747)
at com.mongodb.Mongo$2.execute(Mongo.java:730)
at com.mongodb.MongoCollectionImpl.executeSingleWriteRequest(MongoCollectionImpl.java:482)
at com.mongodb.MongoCollectionImpl.insertOne(MongoCollectionImpl.java:277)
at com.sujithsizon.lzlogin3.LoginActivity.yalla(LoginActivity.java:224)
at com.sujithsizon.lzlogin3.LoginActivity$3$1.onCompleted(LoginActivity.java:99)
at com.facebook.GraphRequest$1.onCompleted(GraphRequest.java:304)
at com.facebook.GraphRequest$5.run(GraphRequest.java:1368)
at android.os.Handler.handleCallback(Handler.java:615)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4745)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
Caused by: android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1117)
at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:84)
at libcore.io.IoBridge.connectErrno(IoBridge.java:144)
at libcore.io.IoBridge.connect(IoBridge.java:112)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:459)
at java.net.Socket.connect(Socket.java:842)
at com.mongodb.connection.SocketStreamHelper.initialize(SocketStreamHelper.java:50)
at com.mongodb.connection.SocketStream.open(SocketStream.java:58)
at com.mongodb.connection.InternalStreamConnection.open(InternalStreamConnection.java:114)
at com.mongodb.connection.UsageTrackingInternalConnection.open(UsageTrackingInternalConnection.java:46) 
at com.mongodb.connection.DefaultConnectionPool$PooledConnection.open(DefaultConnectionPool.java:366) 
at com.mongodb.connection.DefaultConnectionPool.get(DefaultConnectionPool.java:94) 
at com.mongodb.connection.DefaultConnectionPool.get(DefaultConnectionPool.java:80) 
at com.mongodb.connection.DefaultServer.getConnection(DefaultServer.java:69) 
at com.mongodb.binding.ClusterBinding$ClusterBindingConnectionSource.getConnection(ClusterBinding.java:86) 
at com.mongodb.operation.OperationHelper.withConnectionSource(OperationHelper.java:184) 
at com.mongodb.operation.OperationHelper.withConnection(OperationHelper.java:177) 
at com.mongodb.operation.MixedBulkWriteOperation.execute(MixedBulkWriteOperation.java:141) 
at com.mongodb.operation.MixedBulkWriteOperation.execute(MixedBulkWriteOperation.java:72) 
at com.mongodb.Mongo.execute(Mongo.java:747) 
at com.mongodb.Mongo$2.execute(Mongo.java:730) 
at com.mongodb.MongoCollectionImpl.executeSingleWriteRequest(MongoCollectionImpl.java:482) 
at com.mongodb.MongoCollectionImpl.insertOne(MongoCollectionImpl.java:277) 
at com.sujithsizon.lzlogin3.LoginActivity.yalla(LoginActivity.java:224) 
at com.sujithsizon.lzlogin3.LoginActivity$3$1.onCompleted(LoginActivity.java:99) 
at com.facebook.GraphRequest$1.onCompleted(GraphRequest.java:304) 
at com.facebook.GraphRequest$5.run(GraphRequest.java:1368) 
at android.os.Handler.handleCallback(Handler.java:615) 
at android.os.Handler.dispatchMessage(Handler.java:92) 
at android.os.Looper.loop(Looper.java:137) 
at android.app.ActivityThread.main(ActivityThread.java:4745) 
at java.lang.reflect.Method.invokeNative(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:511) 
You can use Async Task for this. I don't know much about mongoDB, but assuming your yalla method has heavy network operation which includes mongoDB.
Try to add yalla method into new AyancTask.
private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
protected Long doInBackground(URL... urls) {
//Include your mongoDB accessing method here, in background thread.
}
}
And you can execute this method by the following line from your activity.
new DownloadFilesTask().execute(url1, url2, url3);
Hope this helps.
EDIT: Now you are including your method in AsyncTask, and passing URL as arguments, Just provide the links via execute() method. No need to use this String[] = args, which currently you are using in your methos.
For more details on AsyncTask, refer the official docs from this link :)
I am actually trying to do the same and found mongoclient won't work so I used the common class to connect to my server on mlab then I used an asynkTask inner class with HTTPUrlConnection to get the data I stored, check out this link for querying urls for mlab-> http://docs.mlab.com/data-api/
Also check this out-> https://m.youtube.com/watch?v=RSZ2pyhfR0I
public class Common {
private static String DB_NAME = "edmtdev";
private static String COLLECTION_NAME = "user";
public static String API_KEY = "YOUR API KEY";
public static String getAddressSingle(User user) {
String baseUrl = String.format("https://api.mlab.com/api/1/databases/%s/collections/%s", DB_NAME, COLLECTION_NAME);
StringBuilder stringBuilder = new StringBuilder(baseUrl);
stringBuilder.append("/"+user.get_id().getOid()+"?apiKey="+API_KEY);
return stringBuilder.toString():
}

I keep getting a nullpointer exception with my JSON Object Calls

For some reason I keep getting a nullpointer exception with my double parsing. AFter further inquiry there seems to be some issue with my JSON Objects but I have no clue what the issue is.I am pulling JSON data form openweathermap api. I scuessfully pulled and printed the data into the log.i, however when I try to access with the JSONObject I am getting an error. Please help.
Code:
package com.anuraagy.myweather;
import android.app.Activity;
import android.app.ActionBar;
import android.app.Fragment;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;
import android.content.*;
import android.os.Build;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
public class MyActivity extends Activity {
private String s;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.my, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
private JSONObject myObject,mainObject,nameObject;
private ImageView myImage;
private TextView titleText;
private String hello,weatherName,max_temp,min_temp;
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_my, container, false);
RequestTask task = new RequestTask();
task.execute(new String[]{"http://api.openweathermap.org/data/2.5/weather?q=Ashburn&APPID=970bf0e4978dae293b065f8f2830ba58"});
return rootView;
}
public class RequestTask extends AsyncTask<String, String, String> {
private TextView myView;
private String s;
#Override
protected String doInBackground(String... uri) {
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response;
String responseString = null;
try {
response = httpclient.execute(new HttpGet(uri[0]));
StatusLine statusLine = response.getStatusLine();
if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
responseString = out.toString();
} else {
//Closes the connection.
response.getEntity().getContent().close();
throw new IOException(statusLine.getReasonPhrase());
}
} catch (ClientProtocolException e) {
//TODO Handle problems..
} catch (IOException e) {
//TODO Handle problems..
}
Log.i("", responseString);
return responseString;
}
#Override
protected void onPostExecute(String result){
Log.i("","hello");
super.onPostExecute(result);
try {
myObject = new JSONObject(result);
nameObject = myObject.getJSONObject("weather");
weatherName = nameObject.getString("main");
mainObject = myObject.getJSONObject("main");
Log.i("Wather Name",weatherName);
Log.i("mainObject",mainObject.toString());
hello = mainObject.getString("temp");
max_temp = mainObject.getString("temp_max");
min_temp = mainObject.getString("temp_min");
} catch(JSONException jsonException){
}
double f = Double.parseDouble(hello);
double max = Double.parseDouble(max_temp);
double min = Double.parseDouble(min_temp);
double realMax = (max - 273)* 1.8 + 32;
double realMin = (min - 273)* 1.8 + 32;
double realTemp = (max - 273)* 1.8 + 32;
int myMax = (int)realMax;
int myMin = (int)realMin;
int myWeather = (int)realTemp;
titleText = (TextView)getActivity().findViewById(R.id.textView3);
String fe = titleText.getText().toString();
fe.replace("definetly",weatherName);
myView = (TextView)getActivity().findViewById(R.id.textView);
// if()
// {
//
// }
// else
// {
//
// }
myImage = (ImageView)getActivity().findViewById(R.id.imageView);
myImage.setImageResource(R.drawable.clearnight);
String weather = myWeather + "";
myView.setText(weather + (char) 0x00B0 +"F");
// //Do anything with response..
}
}
}
}
Error:
10-16 10:01:26.398 664-664/com.anuraagy.myweather E/Trace﹕ error opening trace file: No such file or directory (2)
10-16 10:01:35.058 664-668/com.anuraagy.myweather D/dalvikvm﹕ GC_CONCURRENT freed 75K, 2% free 11112K/11335K, paused 17ms+3ms, total 312ms
10-16 10:01:35.058 664-664/com.anuraagy.myweather D/dalvikvm﹕ WAIT_FOR_CONCURRENT_GC blocked 282ms
10-16 10:01:35.498 664-664/com.anuraagy.myweather D/gralloc_goldfish﹕ Emulator without GPU emulation detected.
10-16 10:01:38.388 664-680/com.anuraagy.myweather I/﹕ {"coord":{"lon":-77.49,"lat":39.04},"sys":{"type":1,"id":2856,"message":0.0194,"country":"US","sunrise":1413458470,"sunset":1413498574},"weather":[{"id":701,"main":"Mist","description":"mist","icon":"50d"},{"id":721,"main":"Haze","description":"haze","icon":"50d"},{"id":741,"main":"Fog","description":"fog","icon":"50d"}],"base":"cmc stations","main":{"temp":288.03,"pressure":1008,"humidity":100,"temp_min":286.15,"temp_max":290.15},"wind":{"speed":2.86,"deg":261.502},"clouds":{"all":90},"dt":1413468071,"id":4744870,"name":"Ashburn","cod":200}
10-16 10:01:38.398 664-664/com.anuraagy.myweather I/﹕ hello
10-16 10:01:38.438 664-664/com.anuraagy.myweather D/AndroidRuntime﹕ Shutting down VM
10-16 10:01:38.438 664-664/com.anuraagy.myweather W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x40a13300)
10-16 10:01:38.448 664-664/com.anuraagy.myweather E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.NullPointerException
at java.lang.StringToReal.parseDouble(StringToReal.java:244)
at java.lang.Double.parseDouble(Double.java:295)
at com.anuraagy.myweather.MyActivity$PlaceholderFragment$RequestTask.onPostExecute(MyActivity.java:141)
at com.anuraagy.myweather.MyActivity$PlaceholderFragment$RequestTask.onPostExecute(MyActivity.java:91)
at android.os.AsyncTask.finish(AsyncTask.java:631)
at android.os.AsyncTask.access$600(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4745)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
Be careful - "weather" is a JSONArray, not a JSONObject. The NullPointerException is likely due to that.
Try instead using myObject.getJSONArray("weather"), and from there iterate through the JSONObjects inside.
See here for more information on that last part: Accessing members of items in a JSONArray with Java
It looks like myObject doesn't have item named "temp", so:
- on line 133 you set hello to null
- on line 141 you pass that null to Double.parseDouble()
- get your exception because class Double can't digest null
That's it!
Check it in the debugger, but I'm almost sure - according to your stack trace

how to stop jsonParser.makeHttpRequest in android

I crate app to check the database for login info by using jsonParser.makeHttpRequest
I try to make my app to stop after 10 second in case there is no internet connection or no response from the server. The code work however when the login button click for the second time the app crash
Could anyone please support why this happen
please see the below for the code
package com.example.pfms;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
public class MainActivity extends Activity {
private String id,pass,p,logincheck;
private EditText username,password;
private Button login;
private CheckLogin cl;
private ProgressDialog pDialog;
private SharedPreferences prefs;
JSONParser jsonParser = new JSONParser();
private static final String TAG_SUCCESS = "success";
private static final String TAG_PRODUCT = "product";
private static final String url = "http://192.168.1.11/pfm/get_id.php";
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
cl= new CheckLogin();
username=(EditText)findViewById(R.id.editText1);
password=(EditText)findViewById(R.id.editText2);
login=(Button)findViewById(R.id.button1);
prefs = this.getSharedPreferences("com.example.pfms", MODE_PRIVATE);
logincheck=prefs.getString("com.example.pfms.login", "0");
if(!logincheck.equals("0")){
Intent i=new Intent(MainActivity.this,TechOption.class);
Bundle info=new Bundle();
info.putString("techid",logincheck);
i.putExtras(info);
startActivity(i);
}
login.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
cl.execute();
}
});
}
class CheckLogin extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Checking Login info. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
p="0";
pass="0";
Log.d("test", "dialog");
}
/**
* Getting product details in background thread
* */
protected String doInBackground(String... params) {
// updating UI from Background Thread
// runOnUiThread(new Runnable() {
// public void run() {
// Check for success tag
int success;
try {
Log.d("test", "run");
// Building Parameters
List<NameValuePair> params2 = new ArrayList<NameValuePair>();
id=username.getText().toString();
pass=password.getText().toString();
params2.add(new BasicNameValuePair("id",id));
// getting product details by making HTTP request
// Note that product details url will use GET request
// HttpParams httpParameters = new BasicHttpParams();
// HttpConnectionParams.setConnectionTimeout(httpParameters, 30000);
// HttpConnectionParams.setSoTimeout(httpParameters, 30000);
// DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
messageHandler.sendEmptyMessageDelayed(0, 10000);
Log.d("test", "before");
JSONObject json = jsonParser.makeHttpRequest(
url, "GET", params2);
// check your log for json response
Log.d("Single Product Details", json.toString());
// json success tag
success = json.getInt(TAG_SUCCESS);
Log.d("test", "before success");
if (success == 1) {
// successfully received product details
JSONArray actiondetail = json
.getJSONArray(TAG_PRODUCT); // JSON Array
// get first product object from JSON Array
JSONObject c = actiondetail.getJSONObject(0);
// Storing each json item in variable
p="";
p = c.getString("pass");
Log.d("info", "p="+p);
Log.d("info", "pass="+pass);
}else{
Toast.makeText(getBaseContext(), "Wrong Username", Toast.LENGTH_LONG).show();
}
Log.d("test", "after success");
} catch (JSONException e) {
//pDialog.dismiss();
//Toast.makeText(getBaseContext(), "Please check internet connection", Toast.LENGTH_LONG).show();
e.printStackTrace();
}
// }
// });
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once got all details
pDialog.dismiss();
Log.d("test", "dismiss dailog");
if(p.contentEquals(pass)){
Intent i=new Intent(MainActivity.this,TechOption.class);
Bundle info=new Bundle();
info.putString("techid",id);
i.putExtras(info);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("com.example.pfms.login",id);
editor.commit();
startActivity(i);
}
else{
Toast.makeText(getBaseContext(), "Wrong Password", Toast.LENGTH_LONG).show();
}
}
}
private Handler messageHandler = new Handler() {
public void handleMessage(Message msg) {
super.handleMessage(msg);
pDialog.dismiss();
Toast.makeText(getBaseContext(), "Please check internet connection", Toast.LENGTH_LONG).show();
cl.cancel(true);
}
};
}
please see the below for Error :
11-05 09:37:09.053: D/AndroidRuntime(1398): Shutting down VM
11-05 09:37:09.053: W/dalvikvm(1398): threadid=1: thread exiting with uncaught exception (group=0x41465700)
11-05 09:37:09.123: E/AndroidRuntime(1398): FATAL EXCEPTION: main
11-05 09:37:09.123: E/AndroidRuntime(1398): java.lang.IllegalStateException: Cannot execute task: the task is already running.
11-05 09:37:09.123: E/AndroidRuntime(1398): at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:575)
11-05 09:37:09.123: E/AndroidRuntime(1398): at android.os.AsyncTask.execute(AsyncTask.java:534)
11-05 09:37:09.123: E/AndroidRuntime(1398): at com.example.pfms.MainActivity$2.onClick(MainActivity.java:79)
11-05 09:37:09.123: E/AndroidRuntime(1398): at android.view.View.performClick(View.java:4240)
11-05 09:37:09.123: E/AndroidRuntime(1398): at android.view.View$PerformClick.run(View.java:17721)
11-05 09:37:09.123: E/AndroidRuntime(1398): at android.os.Handler.handleCallback(Handler.java:730)
11-05 09:37:09.123: E/AndroidRuntime(1398): at android.os.Handler.dispatchMessage(Handler.java:92)
11-05 09:37:09.123: E/AndroidRuntime(1398): at android.os.Looper.loop(Looper.java:137)
11-05 09:37:09.123: E/AndroidRuntime(1398): at android.app.ActivityThread.main(ActivityThread.java:5103)
11-05 09:37:09.123: E/AndroidRuntime(1398): at java.lang.reflect.Method.invokeNative(Native Method)
11-05 09:37:09.123: E/AndroidRuntime(1398): at java.lang.reflect.Method.invoke(Method.java:525)
11-05 09:37:09.123: E/AndroidRuntime(1398): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
11-05 09:37:09.123: E/AndroidRuntime(1398): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
11-05 09:37:09.123: E/AndroidRuntime(1398): at dalvik.system.NativeStart.main(Native Method)
An object of an AsyncTask can be run only once. That is why you are getting the IllegalStateException.
Remove the object instantiation [cl= new CheckLogin()] from onCreate().
And instead,
login.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
new CheckLogin.execute(); // creating an anonymous object of the AsyncTask makes sure that you never use it again which prevents any IllegalStateExceptions
}
});

java.lang.RuntimeException: Unable to start service java.lang.NullPointerException

This is my first app using service. Getting java.lang.RuntimeException: Unable to start service java.lang.NullPointerException. My intention is to send sms when device is in suspend state.
SENDSMS.java
package com.qualcomm.sendsms;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
public class SENDSMS extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sendsms);
String phone_num = null;
String sms = null;
String sleep_time = null;
Bundle extras = getIntent().getExtras();
if (extras != null) {
phone_num = extras.getString("Phone_Number");
Log.e("????????????????SEND_SMS", "phno : "+phone_num);
sms = extras.getString("SMS_Body");
Log.e("????????????????SEND_SMS", "sms : "+sms);
sleep_time = extras.getString("Sleep_Time");
Log.e("????????????????Sleep_Time", "sleep_time : "+sleep_time);
Intent myIntent = new Intent(this, sendservicesms.class);
myIntent.putExtra("Phone_Number",phone_num);
myIntent.putExtra("SMS_Body",sms);
myIntent.putExtra("Sleep_Time",sleep_time);
startService(myIntent);
}
finish();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.sendsm, menu);
return true;
}
}
Service : sendservicesms.java
package com.qualcomm.sendsms;
import android.app.IntentService;
import android.content.Intent;
import android.os.Bundle;
import android.os.IBinder;
import android.telephony.SmsManager;
import android.util.Log;
import android.widget.Toast;
public class sendservicesms extends IntentService {
int mStartMode; // indicates how to behave if the service is killed
IBinder mBinder; // interface for clients that bind
boolean mAllowRebind; // indicates whether onRebind should be used
public sendservicesms() {
super("sendservicesms");
}
public void onCreate() {
// The service is being created
}
#Override
protected void onHandleIntent(Intent intent) {
// The service is starting, due to a call to startService()
if(intent!=null) {
Bundle param = intent.getExtras();
if (param != null) {
String phone_no = (String)param.get("Phone_Number");
String sms_body = (String)param.get("SMS_Body");
String sleeptime = (String)param.get("Sleep_Time");
Log.e("????????????????SEND_SMS", "phno : "+phone_no);
Log.e("????????????????SEND_SMS", "sms : "+sms_body);
Log.e("????????????????Sleep_Time", "sleep_time : "+sleeptime);
Long time = Long.parseLong(sleeptime);
Log.e("????????????????time long", "Long_time : "+time);
try {
if(sleeptime!=null && sleeptime.length() > 0){
Thread.sleep(Long.parseLong(sleeptime));
}
Log.e("????????????????Sleep happened well", "sleep_time : "+sleeptime);
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(phone_no, null, sms_body, null, null);
Toast.makeText(getApplicationContext(), "SMS Sent!",
Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(getApplicationContext(),
"SMS faild, please try again later!",
Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
}
}
#Override
public IBinder onBind(Intent intent) {
// A client is binding to the service with bindService()
return mBinder;
}
#Override
public boolean onUnbind(Intent intent) {
// All clients have unbound with unbindService()
return mAllowRebind;
}
#Override
public void onRebind(Intent intent) {
// A client is binding to the service with bindService(),
// after onUnbind() has already been called
}
#Override
public void onDestroy() {
// The service is no longer used and is being destroyed
}
}
LOGCAT:
E/AndroidRuntime(10276): FATAL EXCEPTION: main
E/AndroidRuntime(10276): java.lang.RuntimeException: Unable to start service com.qualcomm.sendsms.sendservicesms#418dd170 with Intent { cmp=com.qualcomm.sendsms/.sendservicesms (has extras) }: java.lang.NullPointerException
E/AndroidRuntime(10276): at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:2676)
E/AndroidRuntime(10276): at android.app.ActivityThread.access$1900(ActivityThread.java:144)
E/AndroidRuntime(10276): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1334)
E/AndroidRuntime(10276): at android.os.Handler.dispatchMessage(Handler.java:99)
E/AndroidRuntime(10276): at android.os.Looper.loop(Looper.java:137)
E/AndroidRuntime(10276): at android.app.ActivityThread.main(ActivityThread.java:5074)
E/AndroidRuntime(10276): at java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime(10276): at java.lang.reflect.Method.invoke(Method.java:511)
E/AndroidRuntime(10276): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
E/AndroidRuntime(10276): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
E/AndroidRuntime(10276): at dalvik.system.NativeStart.main(Native Method)
E/AndroidRuntime(10276): Caused by: java.lang.NullPointerException
E/AndroidRuntime(10276): at android.app.IntentService.onStart(IntentService.java:116)
E/AndroidRuntime(10276): at android.app.IntentService.onStartCommand(IntentService.java:130)
E/AndroidRuntime(10276): at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:2659)
You must call the super.onCreate() in the first line inside onCreate() if you override it, Cause system needs to be prepared before your own oncreate() implementation.....
Your program will be running fine if you do that
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Your rest of codes
}
When you remove onCreate() from your Activity, System will do that itself for you. :)
whenever there is a null pointer exception it is mostly due to xml... Some element may not be matching in your xml file.
to send sms u may try the following code:
Intent sendIntent = new Intent(Intent.ACTION_VIEW);
sendIntent.putExtra("sms_body", sms_text_string);
sendIntent.setType("vnd.android-dir/mms-sms");
startActivity(sendIntent);

Categories