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.
Related
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>
I am starting the activity after clicking on menu item in the action bar menu.
I have added the activity in manifest file also . I cannot find why there is ActivityNotFoundException. I have used intent to start new Activity. FragmentActivity extends Activity.
MANIFEST FILE:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.android.myapplication">
<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/Theme.AppCompat.Light.NoActionBar">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name="com.example.android.myapplication.FragmentActivity"
android:label="#string/app_name"></activity>
</application>
</manifest>
MAIN ACTIVITY FILE:
package com.example.android.myapplication;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentActivity;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.app.AppCompatCallback;
import android.support.v7.app.AppCompatDelegate;
import android.support.v7.view.ActionMode;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity implements AppCompatCallback{
private SharedPreferences mSharedPreferences;
private SharedPreferences.Editor mEditor;
private EditText mEditTextName;
private EditText mEditTextEmail;
private EditText mEditTextPhone;
private Context context;
Toast mToast;
Intent mIntent;
// private String mPreferenceFileName = getString(R.string.preference_file_key);
// private String mNameKey = this.getString(R.string.name_key);
// private String mPhoneKey = this.getString(R.string.phone_key);
//private String mEmailKey = this.getString(R.string.email_key);
#Override
public void onSupportActionModeStarted(ActionMode mode) {}
#Override
public void onSupportActionModeFinished(ActionMode mode) {}
#Nullable
#Override
public ActionMode onWindowStartingSupportActionMode(ActionMode.Callback callback) {
return null;
}
private AppCompatDelegate delegate;
#Override
protected void onCreate(Bundle savedInstanceState) {
delegate = AppCompatDelegate.create(this, this);
delegate.installViewFactory();
super.onCreate(savedInstanceState);
delegate.onCreate(savedInstanceState);
delegate.setContentView(R.layout.activity_main);
Toolbar toolbar=(Toolbar) findViewById(R.id.app_bar);
delegate.setSupportActionBar(toolbar);
mSharedPreferences = this.getSharedPreferences("myFile" , Context.MODE_PRIVATE);
mEditor = mSharedPreferences.edit();
mEditTextName = (EditText)findViewById(R.id.name);
mEditTextPhone = (EditText)findViewById(R.id.phone);
mEditTextEmail= (EditText)findViewById(R.id.email);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()){
case R.id.save:
mEditor.putString( "mNameKey",mEditTextName.getText().toString());
mEditor.putString( "mEmailKey",mEditTextPhone.getText().toString());
mEditor.putString( "mPhoneKey",mEditTextEmail.getText().toString());
mEditor.apply();
mToast = Toast.makeText(this,"saved",Toast.LENGTH_LONG);
mToast.show();
break;
case R.id.Clear:
mEditTextName.setText("");
mEditTextEmail.setText("");
mEditTextPhone.setText("");
mToast = Toast.makeText(this,"Cleared",Toast.LENGTH_LONG);
mToast.show();
break;
case R.id.retrieve:
if(mSharedPreferences.contains("mNameKey")){
mEditTextName.setText(mSharedPreferences.getString("mNameKey",""));
}
if(mSharedPreferences.contains("mEmailKey")){
mEditTextEmail.setText(mSharedPreferences.getString("mEmailKey",""));
}
if(mSharedPreferences.contains("mPhoneKey")){
mEditTextPhone.setText(mSharedPreferences.getString("mPhoneKey",""));
}
mToast = Toast.makeText(this,"Retrieved",Toast.LENGTH_LONG);
mToast.show();
break;
case R.id.FragementActivity:
// HERE I CALL THE NEW ACTIVITY
try {
mIntent = new Intent(MainActivity.this, FragmentActivity.class);
this.startActivity(mIntent);
}catch(ActivityNotFoundException e){
e.printStackTrace();
Log.i("tag","exception");
}
}
return super.onOptionsItemSelected(item);
}
}
When i click on the FragmentActivity menu item I cannot start the new activity. Is it not possible to start new activity this way? Is there some alternative?
as #Mike M. already mentioned, you are trying to open FragmentActivity from the support package instead of your package, hence the issue
Solution :
You have to remove this import
import android.support.v4.app.FragmentActivity;
and import your activity carefully.
you can use setAction as
mIntent = new Intent();
intent.setAction("com.example.android.myapplication.FragmentActivity");
this.startActivity(mIntent);
Note : For second solution , To avoid the user to select app to complete the action, you need to add DEFAULT as category along with intent-filter for FragmentActivity
No need of changing the class name or no need of removing this :-
import android.support.v4.app.FragmentActivity;
Instead write your full qualified class ( yourPackagename.FragmentActivity )name like
(MainActivity.this,com.example.android.myapplication.FragmentActivity.class );
in the explicit intent call !!
I am trying to read some information via NFC and created the intent-filter to do so, together with the xml that contains the required technologies. The intent-filter should start my ReadActivity, but it doesn't do so, when I put the card near my phone. NFC is activated, so this shouldn't be the problem. I really don't see the problem with my code, so it would be great if someone could take a look at it and maybe give me a hint in the right direction. Here is the code:
AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.johan.nfcreaderforunicard">
<uses-permission android:name="android.permission.NFC" />
<uses-feature android:name="android.hardware.nfc" android:required="true"/>
<uses-sdk android:minSdkVersion="10"/>
<application
android:allowBackup="true"
android:icon="#mipmap/apple"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/Theme.AppCompat.Light.NoActionBar">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".ReadActivity">
<intent-filter>
<action android:name="android.nfc.action.TECH_DISCOVERED"/>
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
<meta-data android:name="android.nfc.action.TECH_DISCOVERED"
android:resource="#xml/tech"/>
</activity>
</manifest>
ReadActivity:
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.tech.IsoDep;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.TextView;
import android.content.Intent;
import android.os.Bundle;
import java.io.IOException;
public class ReadActivity extends AppCompatActivity {
private final byte[] selectAid = {(byte)90, (byte)95, (byte)-124, (byte)21};
private final byte[] creditPayload = {(byte)108, (byte)1};
private byte[] resultOk;
private byte[] creditBytes;
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.read_view);
Toolbar myToolbar = (Toolbar) findViewById(R.id.my_toolbar);
setSupportActionBar(myToolbar);
if(NfcAdapter.ACTION_TECH_DISCOVERED.equals(getIntent().getAction())){
IsoDep isodep = IsoDep.get((Tag)getIntent().getParcelableExtra(NfcAdapter.EXTRA_TAG));
if(isodep != null){
try{
isodep.connect();
resultOk = isodep.transceive(selectAid);
if(resultOk[0] == 0){
creditBytes = isodep.transceive(creditPayload);
}
}catch (IOException e){
}
}
}
float credit = (float)formatCredit(creditBytes);
TextView label = (TextView)findViewById(R.id.read_text);
label.setText("Dein Guthaben: "+String.valueOf(credit)+"€");
}
private double formatCredit(byte[] array) {
double credit = (double)(((0xff & array[4]) << 24) + ((0xff & array[3]) << 16) + ((0xff & array[2]) << 8) + (0xff & array[1])) / 1000D;
return credit;
}
#Override
public boolean onCreateOptionsMenu(Menu menu){
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem menuItem){
switch(menuItem.getItemId()){
case(R.id.action_settings):
Intent startSettings = new Intent(ReadActivity.this, SettingsActivity.class);
startActivity(startSettings);
return true;
case(R.id.about):
Intent startAbout = new Intent(ReadActivity.this, AboutActivity.class);
startActivity(startAbout);
return true;
default:
return super.onOptionsItemSelected(menuItem);
}
}
#Override
public void onBackPressed(){
Intent backToMain = new Intent(getApplicationContext(), MainActivity.class);
startActivity(backToMain);
finish();
}
}
MainActivity:
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar myToolbar = (Toolbar) findViewById(R.id.my_toolbar);
setSupportActionBar(myToolbar);
}
#Override
public boolean onCreateOptionsMenu(Menu menu){
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem menuItem){
switch(menuItem.getItemId()){
case(R.id.action_settings):
Intent startSettings = new Intent(MainActivity.this, SettingsActivity.class);
startActivity(startSettings);
return true;
case(R.id.about):
Intent startAbout = new Intent(MainActivity.this, AboutActivity.class);
startActivity(startAbout);
return true;
default:
return super.onOptionsItemSelected(menuItem);
}
}
#Override
public void onBackPressed(){
finish();
}
}
The AboutActivity and SettingsActivity don't contain anything yet, so I didn't include them in this post. I really don't know where the problem is though.
Restarting my phone and the NFC-setting solved the problem.
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.
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);
}
}
}