Android app crashes on Bluetooth connect? - android

I'm trying to connect to other Android devices using Bluetooth via my app. The app works fine while discovering nearby Bluetooth devices. However, upon connecting, the app crashes.
I have two JAVA files other than MainActivity.java that are responsible for discovering & connecting to other Bluetooth devices. Their codes are posted below:
SearchBTDevice.java (for discovering nearby devices)
package vertex2016.mvjce.edu.bluealert;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGattDescriptor;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.bluetooth.BluetoothAdapter;
import android.provider.Settings;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import java.util.Set;
public class SearchBTDevice extends AppCompatActivity {
public BluetoothAdapter BlueAdapter = BluetoothAdapter.getDefaultAdapter();
public ArrayAdapter PairedArrayAdapter;
public ArrayAdapter BTArrayAdapter;
BluetoothDevice btd;
public ListView devicesFound;
private final BroadcastReceiver BTReceiver= new BroadcastReceiver(){
public void onReceive(Context context, Intent intent)
{
String action = intent.getAction();
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
btd = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
BTArrayAdapter.add(btd.getName() + "\t" + btd.getAddress() + "\n");
}
}
};
IntentFilter filter1 = new IntentFilter(BluetoothDevice.ACTION_FOUND);
#Override
protected void onResume() {
super.onResume();
this.registerReceiver(BTReceiver,filter1);
}
#Override
protected void onPause() {
super.onPause();
BlueAdapter.cancelDiscovery();
this.unregisterReceiver(BTReceiver);
Toast.makeText(SearchBTDevice.this, "Discovery Stopped!!", Toast.LENGTH_SHORT).show();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search_btdevice);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LOCKED);
searchBTDevices();
}
public void searchBTDevices()
{
if(!BlueAdapter.startDiscovery())
Toast.makeText(SearchBTDevice.this, "Failed to Start Discovery", Toast.LENGTH_SHORT).show();
else
Toast.makeText(SearchBTDevice.this, "Discovery Startred", Toast.LENGTH_SHORT).show();
BTArrayAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1);
devicesFound = (ListView)findViewById(R.id.searchpagelistView);
devicesFound.setAdapter(BTArrayAdapter);
devicesFound.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent connectedBTintent = new Intent(SearchBTDevice.this, ConnectedBTDevice.class);
connectedBTintent.putExtra("BluetoothDevice", btd);
startActivity(connectedBTintent);
}
});
}
}
This is updated ConnectedBTDevice.java, responsible for connecting devices
package vertex2016.mvjce.edu.bluealert;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import java.io.IOException;
import java.util.UUID;
public class ConnectedBTDevice extends AppCompatActivity {
public BluetoothDevice btd;
public BluetoothSocket btSocket, tempSocket;
private UUID myUUID;
ArrayAdapter arr;
ListView lv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_connected_btdevice);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LOCKED);
arr = new ArrayAdapter(this, android.R.layout.simple_list_item_2);
btd = getIntent().getParcelableExtra("BluetoothDevice");
connectBT();
displayStuff();
}
public void connectBT() {
Thread myThread = new Thread() {
public void run() {
tempSocket = null;
try {
tempSocket = btd.createRfcommSocketToServiceRecord(myUUID);
} catch (IOException e) {
e.printStackTrace();
}
BluetoothAdapter.getDefaultAdapter().cancelDiscovery();
try {
tempSocket.connect();
arr.add("CONNECTED TO-->" + btd.getName());
} catch (IOException e) {
e.printStackTrace();
try {
tempSocket.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
};
myThread.start();
}
public void displayStuff()
{
lv = (ListView)findViewById(R.id.connectedBTlistView);
lv.setAdapter(arr);
}
}
This is activity_connected_btdevice.xml for ConnectedBTDevice.java activity
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context="vertex2016.mvjce.edu.bluealert.SearchBTDevice">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.NoActionBar.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.NoActionBar.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<include layout="#layout/content_connected_btdevice" />
</android.support.design.widget.CoordinatorLayout>
This is content_connected_btdevice.xml for ConnectedBTDevice.java
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="vertex2016.mvjce.edu.bluealert.ConnectedBTDevice"
tools:showIn="#layout/activity_connected_btdevice">
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/connectedBTimageView"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:src="#drawable/bluealert_bg"
android:scaleType="centerCrop"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Connected Bluetooth Device"
android:id="#+id/connectedBTtextextView"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="105dp"
android:textSize="25dp"
android:textAlignment="center"/>
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/connectedBTlistView"
android:layout_below="#+id/connectedBTtextextView"
android:layout_centerHorizontal="true"
android:layout_marginTop="65dp" />
</RelativeLayout>
This is AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="vertex2016.mvjce.edu.bluealert">
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<application
android:allowBackup="true"
android:icon="#mipmap/bluealerticon"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme.NoActionBar">
<activity
android:name=".SplashScreen"
android:label="#string/app_name"
android:theme="#style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".MainActivity" />
<activity
android:name=".SearchBTDevice"
android:label="#string/title_activity_search_btdevice"
android:parentActivityName=".MainActivity"
android:theme="#style/AppTheme.NoActionBar">
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="vertex2016.mvjce.edu.bluealert.MainActivity" />
</activity>
<activity
android:name=".ConnectedBTDevice"
android:label="#string/title_activity_connected_btdevice"
android:parentActivityName=".SearchBTDevice"
android:theme="#style/AppTheme.NoActionBar">
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="vertex2016.mvjce.edu.bluealert.SearchBTDevice" />
</activity>
</application>
</manifest>
Here's the exception that my updated logcat shows
03-24 00:19:40.541 7205-9703/vertex2016.mvjce.edu.bluealert E/AndroidRuntime: FATAL EXCEPTION: Thread-35890
Process: vertex2016.mvjce.edu.bluealert, PID: 7205
java.lang.NullPointerException: Attempt to invoke virtual method 'long java.util.UUID.getMostSignificantBits()' on a null object reference
at android.os.ParcelUuid.writeToParcel(ParcelUuid.java:129)
at android.bluetooth.IBluetooth$Stub$Proxy.connectSocket(IBluetooth.java:1767)
at android.bluetooth.BluetoothSocket.connect(BluetoothSocket.java:309)
at vertex2016.mvjce.edu.bluealert.ConnectedBTDevice$1.run(ConnectedBTDevice.java:63)
I don't understand what the problem is. I have tried several online tutorials, but nothing seemed to work. I know the problem is in my ConnectedBTDevice.java, but can't figure out the point at which it's throwing the exception.
Thank you for your time.

You are assigning BluetoothSocket to tempSocket, and then you try to invoke connect() method on btSocket which is null.

Related

Not able to read notifications from other apps

I want to read notifications from other apps in android , but I am not able to do so. These are my implementations to achieve same.
This is my MainActivity.java
package com.example.demoapp;
import androidx.appcompat.app.AppCompatActivity;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Html;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
TableLayout tab;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tab = (TableLayout)findViewById(R.id.tab);
LocalBroadcastManager.getInstance(this).registerReceiver(onNotice, new IntentFilter("Msg"));
}
private BroadcastReceiver onNotice= new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String pack = intent.getStringExtra("package");
String title = intent.getStringExtra("title");
String text = intent.getStringExtra("text");
TableRow tr = new TableRow(getApplicationContext());
tr.setLayoutParams(new TableRow.LayoutParams( TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.WRAP_CONTENT));
TextView textview = new TextView(getApplicationContext());
textview.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT, TableRow.LayoutParams.WRAP_CONTENT,1.0f));
textview.setTextSize(20);
textview.setTextColor(Color.parseColor("#0B0719"));
textview.setText(Html.fromHtml(pack +"<br><b>" + title + " : </b>" + text));
tr.addView(textview);
tab.addView(tr);
}
};
}
This is my NotificationService class
package com.example.demoapp;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.service.notification.NotificationListenerService;
import android.service.notification.StatusBarNotification;
import android.util.Log;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
public class NotificationService extends NotificationListenerService {
Context context;
#Override
public void onCreate() {
super.onCreate();
context = getApplicationContext();
}
#Override
public void onNotificationPosted(StatusBarNotification sbn) {
String pack = sbn.getPackageName();
String ticker = sbn.getNotification().tickerText.toString();
Bundle extras = sbn.getNotification().extras;
String title = extras.getString("android.title");
String text = extras.getCharSequence("android.text").toString();
Log.i("Package",pack);
Log.i("Ticker",ticker);
Log.i("Title",title);
Log.i("Text",text);
Intent msgrcv = new Intent("Msg");
msgrcv.putExtra("package", pack);
msgrcv.putExtra("ticker", ticker);
msgrcv.putExtra("title", title);
msgrcv.putExtra("text", text);
LocalBroadcastManager.getInstance(context).sendBroadcast(msgrcv);
}
#Override
public void onNotificationRemoved(StatusBarNotification sbn) {
Log.i("Msg","Notification Removed");
}
}
This is my AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:dist="http://schemas.android.com/apk/distribution"
package="com.example.demoapp">
<dist:module dist:instant="true" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name="com.example.demoapp.NotificationService"
android:label="#string/app_name"
android:permission="android.permission.BIND_NOTIFICATION_LISTENER_SERVICE">
<intent-filter>
<action android:name="android.service.notification.NotificationListenerService" />
</intent-filter>
</service>
</application>
</manifest>
This is my activity.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<TableLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/tab" />
</ScrollView>
</LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
I have tested app in Android 5 and above, it is not getting any notification details. I gave permission to the app for reading permissions in android while testing on Android 6 and above versions.
Suggest me where I am getting wrong.
I have created a small demo for you its working fine in Android API-18 and above devices.
Even you can
Read all incoming SMS
Read all incoming calls
Battery Low and other notifications too
This is screenshot for display notification of other application Picture1 Picture2
NotificationService.java
import android.app.Notification;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.service.notification.NotificationListenerService;
import android.service.notification.StatusBarNotification;
import android.util.Log;
import android.support.v4.content.LocalBroadcastManager;
import java.io.ByteArrayOutputStream;
public class NotificationService extends NotificationListenerService {
Context context;
#Override
public void onCreate() {
super.onCreate();
context = getApplicationContext();
}
#Override
public void onNotificationPosted(StatusBarNotification sbn) {
String pack = sbn.getPackageName();
String ticker ="";
if(sbn.getNotification().tickerText !=null) {
ticker = sbn.getNotification().tickerText.toString();
}
Bundle extras = sbn.getNotification().extras;
String title = extras.getString("android.title");
String text = extras.getCharSequence("android.text").toString();
int id1 = extras.getInt(Notification.EXTRA_SMALL_ICON);
Bitmap id = sbn.getNotification().largeIcon;
Log.i("Package",pack);
Log.i("Ticker",ticker);
Log.i("Title",title);
Log.i("Text",text);
Intent msgrcv = new Intent("Msg");
msgrcv.putExtra("package", pack);
msgrcv.putExtra("ticker", ticker);
msgrcv.putExtra("title", title);
msgrcv.putExtra("text", text);
if(id != null) {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
id.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
msgrcv.putExtra("icon",byteArray);
}
LocalBroadcastManager.getInstance(context).sendBroadcast(msgrcv);
}
#Override
public void onNotificationRemoved(StatusBarNotification sbn) {
Log.i("Msg","Notification Removed");
}
}
MainActivity.java
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ListView;
import java.util.ArrayList;
public class MainActivity extends Activity {
ListView list;
CustomListAdapter adapter;
ArrayList<Model> modelList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
modelList = new ArrayList<Model>();
adapter = new CustomListAdapter(getApplicationContext(), modelList);
list=(ListView)findViewById(R.id.list);
list.setAdapter(adapter);
LocalBroadcastManager.getInstance(this).registerReceiver(onNotice, new IntentFilter("Msg"));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);//Menu Resource, Menu
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_settings:
Intent intent = new Intent(
"android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS");
startActivity(intent);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private BroadcastReceiver onNotice= new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// String pack = intent.getStringExtra("package");
String title = intent.getStringExtra("title");
String text = intent.getStringExtra("text");
//int id = intent.getIntExtra("icon",0);
Context remotePackageContext = null;
try {
byte[] byteArray =intent.getByteArrayExtra("icon");
Bitmap bmp = null;
if(byteArray !=null) {
bmp = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
}
Model model = new Model();
model.setName(title +" " +text);
model.setImage(bmp);
if(modelList !=null) {
modelList.add(model);
adapter.notifyDataSetChanged();
}else {
modelList = new ArrayList<Model>();
modelList.add(model);
adapter = new CustomListAdapter(getApplicationContext(), modelList);
list=(ListView)findViewById(R.id.list);
list.setAdapter(adapter);
}
} catch (Exception e) {
e.printStackTrace();
}
}
};
}
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="{relativePackage}.${activityClass}" >
<ListView
android:id="#+id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true" >
</ListView>
</RelativeLayout>
Androidmanifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.demoapp">
<uses-permission android:name="android.permission.RECEIVE_SMS"></uses-permission>
<uses-permission android:name="android.permission.READ_SMS" />
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme">
<activity
android:name="com.example.demoapp.MainActivity"
android:configChanges="keyboardHidden|orientation|screenSize"
android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name="com.example.demoapp.NotificationService"
android:label="#string/app_name"
android:permission="android.permission.BIND_NOTIFICATION_LISTENER_SERVICE">
<intent-filter>
<action android:name="android.service.notification.NotificationListenerService" />
</intent-filter>
</service>
</application>
</manifest>

Android AIDL iBinder NullPointerException

Purpose: use AIDL to communicate two app (one is called service ,one is called client)
Condition: IDE: Android Studio ,In service ,I define a IPerson.aidl (in this file I define a interface called queryPerson )which AS will generate the IPerson.java in GENERATED dir . I also add IntentFilter(action ,category) AndroidMainfest.xml in main And I create a AIDLService to extends the IPerson.Stub and implement the interface queryPerson . After that I make another app called client to communicate with service But got NOPOINTER Exception
here are code in service:
IPerson.aidl:
// IPerson.aidl
package com.example.jason.aidldemo;
// Declare any non-default types here with import statements
interface IPerson {
/**
* Demonstrates some basic types that you can use as parameters
* and return values in AIDL.
*/
String queryPerson(int num);
}
AIDLService.java:
package com.example.jason.aidldemo;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.RemoteException;
public class AIDLService extends Service {
private IBinder iBinder=new PersonQueryBinder();
private String [] names={"Apple","Banana","peach"};
private String query(int num)
{
if(num>0 && num<4)
{
return names[num-1];
}
return null;
}
public AIDLService() {
}
private final class PersonQueryBinder extends IPerson.Stub
{
#Override
public String queryPerson(int num) throws RemoteException {
return query(num);
}
}
#Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
return null;
}
}
AndroidMainfest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.jason.aidldemo" >
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name=".AIDLService"
android:enabled="true"
android:exported="true" >
<intent-filter>
<action android:name="android.intent.action.AIDLService"/>
<category android:name="android.intent.category.DEFAULT"/>
</intent-filter>
</service>
</application>
</manifest>
In client:
activity-main.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/hello_world"
android:id="#+id/textView" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/edit_num"
android:layout_below="#+id/textView"
android:layout_alignParentStart="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Query"
android:id="#+id/btn_query"
android:layout_below="#+id/edit_num"
android:layout_alignParentStart="true"
android:layout_marginTop="26dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/tx_name"
android:layout_marginTop="20dp"
android:layout_below="#+id/btn_query" />
</RelativeLayout>
MainActivity.java:
package com.example.jason.aidlclient;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.os.RemoteException;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import com.example.jason.aidldemo.IPerson;
public class MainActivity extends Activity implements View.OnClickListener {
private IPerson iPerson;
private Button btn_query;
private TextView tx_name;
private EditText edit_name;
private PersonConnection pconn=new PersonConnection();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bindView();
//bind remoted service
Intent service=new Intent("android.intent.action.AIDLService");
service.setPackage("com.example.jason.aidldemo");
bindService(service,pconn,BIND_AUTO_CREATE);
}
private void bindView()
{
edit_name= (EditText) findViewById(R.id.edit_num);
btn_query= (Button) findViewById(R.id.btn_query);
tx_name= (TextView) findViewById(R.id.tx_name);
btn_query.setOnClickListener(this);
}
/**
* Called when a view has been clicked.
*
* #param v The view that was clicked.
*/
#Override
public void onClick(View v) {
switch (v.getId())
{
case R.id.btn_query:
String number=edit_name.getText().toString();
int num=Integer.valueOf(number);
try{
String temp=iPerson.queryPerson(num);
tx_name.setText(temp);
} catch (RemoteException e) {
e.printStackTrace();
}
edit_name.setText("");
break;
}
}
private final class PersonConnection implements ServiceConnection{
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
iPerson= (IPerson.Stub) IPerson.Stub.asInterface(service);
}
#Override
public void onServiceDisconnected(ComponentName name) {
iPerson=null;
}
}
}
And I want Demo to run like this :
enter image description here
But got problem NOPOINTER
Hope someone teach ME!! THANKS!!
Your service is returning a null binder. You have to return the AIDL interface stub like this:
#Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
return new IPerson.Stub(){
#Override
public String queryPerson(int num) throws RemoteException {
return query(num);
}
}
}

Android service error Attempt to invoke virtual method

I am making an app, where a server in java sends a Place Array and other stuff in other activities. so I create a service to connect to the server from different activities. I have not implement server connection yet but I am simulating the server response, which I pass as parameter to an adapter (the adapter is tested), that I create to show this places in a ListView. so I got my Place array in my activity and I set it to the return object from a method in the service, but when I run the app it crashes and I got this error message:
java.lang.NullPointerException: Attempt to invoke virtual method
'com.remedialguns.smartourist.Place[]
com.remedialguns.smartourist.ConnectionService.getPlaces()' on a null
object.
UPDATE now is te same error but in myAdapter class when name.setText...
so this is my service.
package com.remedialguns.smartourist;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;
import java.io.IOException;
import java.io.PrintStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.util.Locale;
public class ConnectionService extends Service {
Socket s;
PrintStream os;
private static final String TAG="com.remedialguns.smartourist";
private final IBinder myBinder = new LocalBinder();
#Override
public IBinder onBind(Intent intent) {
return myBinder;
}
public void sendProfileData(){
//send profile data to server
}
public Place[] getPlaces(){
Place[] PlacesToShow = new Place[10];
//F̶a̶k̶e̶ ̶d̶a̶t̶a̶ Test data
PlacesToShow[0]= new Place("MUSEO","Museo Nacional Agropecuario", 0.15, 0.4, 0.12);
PlacesToShow[1]= new Place("MUSEO","Museo Arqueológico Junín",0.10, 0.78, 0.44);
PlacesToShow[2]= new Place("MUSEO","Museo Botero", 0.2, 0.8, 0.08);
PlacesToShow[3]= new Place("MUSEO","Museo de Zea", 0.3, 0.65, 0.23);
PlacesToShow[4]= new Place("MUSEO","MUSEO DEL ORO", 0.13, 0.56, 0.12);
PlacesToShow[5]= new Place("MUSEO","MUSEO DE ARTE COLONIAL", 0.3, 0.67, 0.14);
PlacesToShow[6]= new Place("MUSEO","MUSEO HISTORICO DE LA POLICIA NACIONAL", 0.34, 0.3, 0.33);
PlacesToShow[8]= new Place("MUSEO","MUSEO DE LOS NIÑOS", 0.05, 0.65, 0.03);
PlacesToShow[7]= new Place("MUSEO","Museo Nacional", 0.15, 0.4, 0.12);
PlacesToShow[9]= new Place("MUSEO","MUSEO MILITAR", 0.07, 0.5, 0.6);
return PlacesToShow;
}
public class LocalBinder extends Binder {
ConnectionService getService(){
return ConnectionService.this;
}
}
}
this is my activity with my ListView and adapter.(UPDATE)
package com.remedialguns.smartourist;
import android.content.ComponentName;
import android.content.Context;
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.os.IBinder;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import com.remedialguns.smartourist.ConnectionService.LocalBinder;
import com.google.android.gms.location.places.Places;
public class ListActivity extends AppCompatActivity {
ConnectionService tcpService;
boolean isBound=false;
//Place[] PlacesToShow=tcpService.getPlaces();
Place[] PlacesToShow=new Place[10];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Intent i = new Intent(this, ConnectionService.class);
bindService(i, myConnection, Context.BIND_AUTO_CREATE);
// PlacesToShow=tcpService.getPlaces();
if (isBound) {
PlacesToShow = tcpService.getPlaces();
}
//Place[] PlacesToShow=tcpService.getPlaces();
ListAdapter MyAdapter = new MyAdapter(this, PlacesToShow);
ListView ListPlaces=(ListView) findViewById(R.id.MyList);
ListPlaces.setAdapter(MyAdapter);
ListPlaces.setOnItemClickListener(
new AdapterView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Context context = view.getContext();
TextView textViewItem = ((TextView)view.findViewById(R.id.name));
String name =textViewItem.getText().toString();
TextView textViewItem2 = (TextView)findViewById(R.id.description);
String descripcion=textViewItem2.getText().toString();
Toast.makeText(context,"lugar: "+name+", descripcion: "+descripcion,Toast.LENGTH_SHORT).show();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, 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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private ServiceConnection myConnection=new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
LocalBinder binder = (LocalBinder) service;
tcpService = binder.getService();
PlacesToShow = tcpService.getPlaces();
isBound = true;
}
#Override
public void onServiceDisconnected(ComponentName name) {
isBound=false;
}
};
}
this is my activity.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:showIn="#layout/activity_list"
tools:context="com.remedialguns.smartourist.ListActivity">
<!-- <TextView
android:id="#+id/answer"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="these are the places that our smart monkeys had find for you."/>
-->
<ListView
android:id="#+id/MyList"
android:layout_width="match_parent"
android:layout_height="match_parent">
</ListView>
</LinearLayout>
this is my manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.remedialguns.smartourist" >
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme" >
<activity
android:name=".LoginActivity"
android:label="#string/app_name"
android:theme="#style/AppTheme.NoActionBar" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.USE_CREDENTIALS" />
<activity
android:name=".MainActivity"
android:label="#string/app_name"
android:theme="#style/AppTheme.NoActionBar" >
</activity>
<activity
android:name=".RealMainActivity"
android:label="#string/app_name"
android:theme="#style/AppTheme.NoActionBar" >
</activity>
<activity
android:name=".ListActivity"
android:label="#string/app_name"
android:parentActivityName=".RealMainActivity"
android:theme="#style/AppTheme.NoActionBar" >
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.remedialguns.smartourist.RealMainActivity" />
</activity>
<service
android:name=".ConnectionService"
android:enabled="true"
android:exported="true" >
</service>
</application>
</manifest>
this is my adapter class
package com.remedialguns.smartourist;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class MyAdapter extends ArrayAdapter<Place> {
MyAdapter(Context context, Place[] places){
super(context, R.layout.visual_place, places);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater MyInflater = LayoutInflater.from(getContext());
View placeView = MyInflater.inflate(R.layout.visual_place, parent, false);
Place singlePlaceItem=getItem(position);
TextView name=(TextView) placeView.findViewById(R.id.name);
ImageView icon =(ImageView) placeView.findViewById(R.id.icon);
TextView description = (TextView) placeView.findViewById(R.id.description);
name.setText(singlePlaceItem.getName().toString());
icon.setImageResource(R.mipmap.ic_launcher);
description.setText("Cost "+singlePlaceItem.getCost()+", distance "+singlePlaceItem.getDistance()+", rate "+singlePlaceItem.getRate()+" *");
return placeView;
}
}
please help me.
Here:
bindService(i, myConnection, Context.BIND_AUTO_CREATE);
Place[] PlacesToShow=new Place[10];
PlacesToShow=tcpService.getPlaces();
tcpService is null probably using is to call getPlaces() method before onServiceConnected method is called.
Use isBound to check onServiceConnected is called or not before using tcpService object:
if(isBound){
//
PlacesToShow=tcpService.getPlaces();
}
and also use onServiceConnected method as:
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
LocalBinder binder = (LocalBinder) service;
tcpService = binder.getService();
PlacesToShow=tcpService.getPlaces();
isBound=true;
}
Also make sure added ConnectionService in AndroidManifest.xml as service.

I need alarm to start after specified time interval but alarm is executing at the start and repeats after certain interval

I have attached my code here for reference.
I need alarm to be executed after certain interval but its starting at the beginning and repeating. Can i get a solution for this.
AlarmManagerExample.java
package com.example.alarmmanagerexample;
import android.os.Bundle;
import android.os.SystemClock;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Intent;
public class AlarmManagerExample extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_alarm_manager_example);
try {
//Create a new PendingIntent and add it to the AlarmManager
Intent intent = new Intent(this, RingAlarm.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this,
12345, intent, PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager am =
(AlarmManager)getSystemService(Activity.ALARM_SERVICE);
am.setRepeating(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime(),
2*60*60,pendingIntent);
} catch (Exception e) {}
}
}
activity_alarm_manager_example.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".AlarmManagerExample" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="#string/hello_world" />
</RelativeLayout>
RingAlarm.java
package com.example.alarmmanagerexample;
import android.app.Activity;
import android.content.Context;
import android.media.MediaPlayer;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
public class RingAlarm extends Activity {
MediaPlayer mp=null ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.alarm);
Button stopAlarm = (Button) findViewById(R.id.stopAlarm);
mp = MediaPlayer.create(getBaseContext(),R.raw.audio);
stopAlarm.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View arg0, MotionEvent arg1) {
// TODO Auto-generated method stub
mp.stop();
finish();
return false;
}
});
playSound(this, getAlarmUri());
}
private void playSound(final Context context, Uri alert) {
Thread background = new Thread(new Runnable() {
public void run() {
try {
mp.start();
} catch (Throwable t) {
Log.i("Animation", "Thread exception "+t);
}
}
});
background.start();
}
#Override
protected void onDestroy() {
super.onDestroy();
mp.stop();
} //Get an alarm sound. Try for an alarm. If none set, try notification,
//Otherwise, ringtone.
private Uri getAlarmUri() {
Uri alert = RingtoneManager
.getDefaultUri(RingtoneManager.TYPE_ALARM);
if (alert == null) {
alert = RingtoneManager
.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
if (alert == null) {
alert = RingtoneManager
.getDefaultUri(RingtoneManager.TYPE_RINGTONE);
}
}
return alert;
}
}
Alarm.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent">
<Button android:text="Stop Alarm" android:id="#+id/stopAlarm"
android:layout_width="wrap_content" android:layout_height="wrap_content" />
</LinearLayout>
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.alarmmanagerexample"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.alarmmanagerexample.AlarmManagerExample"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".RingAlarm"
android:label="#string/app_name" />
</application>
</manifest>

ListView does not work

I'm trying to make a list view in a page that is liked form a button,
but when I debug the application it shows only a black page with the name.
I have 2 java
one xml to de main page
and one mainfest.xml
page 1:
package tm.andrioid.com;
import android.app.Activity;
import android.app.Dialog;
import android.app.ListActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.widget.Button;
import android.app.Activity;
import android.os.Bundle;
import android.content.Intent;
import android.widget.Button;
public class indexActivity extends Activity
{
public void onCreate(Bundle icicle)
{
super.onCreate(icicle);
setContentView(R.layout.main);
Button bprodukter = (Button) findViewById(R.id.bprodukter);
bprodukter.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
Intent i = new Intent(indexActivity.this, produkter.class);
startActivity(i);
}
});
}``
}
page 2 java:
tm.andrioid.com;
import android.app.Activity;
import android.app.Dialog;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.app.Activity;
import android.os.Bundle;
import android.widget.Button;
public class produkter extends ListActivity {
String classes[] = { "indexActivity", "Data", "Intim", "Hörlurar", "Prylar",
"Mat", "Sex", "Sju"};
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setListAdapter(new ArrayAdapter<String>(produkter.this,
android.R.layout.simple_list_item_1));
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
super.onListItemClick(l, v, position, id);
String saker = classes[position];
try{
Class ourClass = Class.forName("tm.android.com." + saker);
Intent ourIntent = new Intent(produkter.this, ourClass);
startActivity(ourIntent);
}catch(ClassNotFoundException e){
e.printStackTrace();
}
}
}
main xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="tm.andrioid.com"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="15" />
<application
android:icon="#drawable/tmm"
android:label="#string/app_name" >
<activity
android:name=".splash"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".indexActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="tm.android.com.INDEXACTIVITY" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity
android:name=".produkter"
android:label="#string/app_name" >
<intent-filter>
<action android:name="tm.android.com.PRODUKTER" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
</application>
</manifest>
Replace
setListAdapter(new ArrayAdapter<String>(produkter.this,
android.R.layout.simple_list_item_1));
with this:
setListAdapter(new ArrayAdapter<String>(produkter.this,
android.R.layout.simple_list_item_1, classes));
let me know if this works.

Categories

Resources