Soy nuevo en la programando en android studio, estoy generando una interfaz para conectar una impresora Bluetooh con ayuda del SDK de ejemplo incluido pero al momento de llamar al metodo que realizara la conexion me genera el siguiente error, algun experto que me pudiera orientar.
E/AndroidRuntime: FATAL EXCEPTION: main
Process: mx.prodeco.printnew, PID: 4653
java.lang.NullPointerException: Attempt to invoke interface method 'void net.posprinter.posprinterface.IMyBinder.connectBtPort(java.lang.String, net.posprinter.posprinterface.UiExecute)' on a null object reference
at mx.prodeco.printnew.MainActivity.connetBle(MainActivity.java:213)
at mx.prodeco.printnew.MainActivity.onClick(MainActivity.java:124)
at android.view.View.performClick(View.java:5647)
at android.view.View$PerformClick.run(View.java:22462)
at android.os.Handler.handleCallback(Handler.java:754)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:163)
at android.app.ActivityThread.main(ActivityThread.java:6361)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:794)
este es el código:
public class MainActivity extends Activity implements OnClickListener {
public static String DISCONNECT="com.posconsend.net.disconnetct";
//IMyBinder interface,All methods that can be invoked to connect and send data are encapsulated within this interface
public static IMyBinder binder;
//bindService connection
ServiceConnection conn= new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
//Bind successfully
binder= (IMyBinder) iBinder;
Log.e("binder","connected");
}
@Override
public void onServiceDisconnected(ComponentName componentName) {
Log.e("disbinder","disconnected");
}
};
public static boolean ISCONNECT;
Button BTCon,//connection button
BTDisconnect,//disconnect button
BtposPrinter,
BtSb;// start posprint button
EditText showET;// show edittext
CoordinatorLayout container;
private View dialogView;
BluetoothAdapter bluetoothAdapter;
private ArrayAdapter<String> adapter1
,adapter2;
private ListView lv1,lv2;
private ArrayList<String> deviceList_bonded=new ArrayList<String>();//bonded list
private ArrayList<String> deviceList_found=new ArrayList<String>();//found list
private Button btn_scan; //scan button
private LinearLayout LLlayout;
AlertDialog dialog;
String mac;
int pos ;
private DeviceReceiver myDevice;
@Override
protected void onCreate(Bundle savedInstanceState) {
Log.i("bluetooth", "onCreate...");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//bind service,get ImyBinder object
Intent intent=new Intent(this,PosprinterService.class);
bindService(intent, conn, BIND_AUTO_CREATE);
//init view
initView();
//setlistener
setlistener();
}
private void initView(){
Log.i("bluetooth", "initView...");
BTCon= (Button) findViewById(R.id.buttonConnect);
BTDisconnect= (Button) findViewById(R.id.buttonDisconnect);
BtposPrinter= (Button) findViewById(R.id.buttonPosPrinter);
BtSb= (Button) findViewById(R.id.buttonSB);
showET= (EditText) findViewById(R.id.showET);
}
private void setlistener(){
Log.i("bluetooth", "setlistener...");
BTCon.setOnClickListener(this);
BTDisconnect.setOnClickListener(this);
BtSb.setOnClickListener(this);
//BTpos.setOnClickListener(this);
}
@Override
public void onClick(View view) {
Log.i("bluetooth", "onClick...");
switch (view.getId()){
case R.id.buttonConnect:{
//bluetooth connection
connetBle();
break;
}
case R.id.buttonSB:{
setBluetooth();
BTCon.setText(getString(R.string.connect));
break;
}
case R.id.buttonDisconnect:{
if (ISCONNECT){
binder.disconnectCurrentPort(new UiExecute() {
@Override
public void onsucess() {
showSnackbar(getString(R.string.toast_discon_success));
showET.setText("");
BTCon.setText(getString(R.string.connect));
}
@Override
public void onfailed() {
showSnackbar(getString(R.string.toast_discon_faile));
}
});
}else {
showSnackbar(getString(R.string.toast_present_con));
}
break;
}
default:
break;
}
}
private void connetBle(){
Log.i("bluetooth", "connetBle...");
String bleAdrress=showET.getText().toString();
Log.i("bluetooth", ""+bleAdrress+"...");
if (bleAdrress.equals(null)||bleAdrress.equals("")){
showSnackbar(getString(R.string.bleselect));
}else {
binder.connectBtPort(bleAdrress, new UiExecute() {
@Override
public void onsucess() {
ISCONNECT=true;
showSnackbar(getString(R.string.con_success));
BTCon.setText(getString(R.string.con_success));
binder.write(DataForSendToPrinterPos80.openOrCloseAutoReturnPrintState(0x1f), new UiExecute() {
@Override
public void onsucess() {
binder.acceptdatafromprinter(new UiExecute() {
@Override
public void onsucess() {
}
@Override
public void onfailed() {
ISCONNECT=false;
showSnackbar(getString(R.string.con_has_discon));
}
});
}
@Override
public void onfailed() {
}
});
}
@Override
public void onfailed() {
ISCONNECT=false;
showSnackbar(getString(R.string.con_failed));
}
});
}
}
public void setBluetooth(){
Log.i("bluetooth", "setBluetooth...");
bluetoothAdapter=BluetoothAdapter.getDefaultAdapter();
if (!bluetoothAdapter.isEnabled()){
//open bluetooth
Intent intent=new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(intent, Conts.ENABLE_BLUETOOTH);
}else {
showblueboothlist();
}
}
private void showblueboothlist() {
Log.i("bluetooth", "showbluetoothlist...");
if (!bluetoothAdapter.isDiscovering()) {
bluetoothAdapter.startDiscovery();
}
LayoutInflater inflater=LayoutInflater.from(this);
dialogView=inflater.inflate(R.layout.printer_list, null);
adapter1=new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, deviceList_bonded);
lv1=(ListView) dialogView.findViewById(R.id.listView1);
btn_scan=(Button) dialogView.findViewById(R.id.btn_scan);
LLlayout=(LinearLayout) dialogView.findViewById(R.id.ll1);
lv2=(ListView) dialogView.findViewById(R.id.listView2);
adapter2=new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, deviceList_found);
lv1.setAdapter(adapter1);
lv2.setAdapter(adapter2);
dialog=new AlertDialog.Builder(this).setTitle("BLE").setView(dialogView).create();
dialog.show();
myDevice=new DeviceReceiver(deviceList_found,adapter2,lv2);
//register the receiver
IntentFilter filterStart=new IntentFilter(BluetoothDevice.ACTION_FOUND);
IntentFilter filterEnd=new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
registerReceiver(myDevice, filterStart);
registerReceiver(myDevice, filterEnd);
setDlistener();
findAvalibleDevice();
}
private void setDlistener() {
Log.i("bluetooth", "setDlistener...");
// TODO Auto-generated method stub
btn_scan.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
LLlayout.setVisibility(View.VISIBLE);
//btn_scan.setVisibility(View.GONE);
}
});
//boned device connect
lv1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
try {
if(bluetoothAdapter!=null&&bluetoothAdapter.isDiscovering()){
bluetoothAdapter.cancelDiscovery();
}
String msg=deviceList_bonded.get(arg2);
mac=msg.substring(msg.length()-17);
String name=msg.substring(0, msg.length()-18);
//lv1.setSelection(arg2);
dialog.cancel();
showET.setText(mac);
//Log.i("TAG", "mac="+mac);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
//found device and connect device
lv2.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
try {
if(bluetoothAdapter!=null&&bluetoothAdapter.isDiscovering()){
bluetoothAdapter.cancelDiscovery();
}
String msg=deviceList_found.get(arg2);
mac=msg.substring(msg.length()-17);
String name=msg.substring(0, msg.length()-18);
//lv2.setSelection(arg2);
dialog.cancel();
showET.setText(mac);
Log.i("TAG", "mac="+mac);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
/*
find avaliable device
*/
private void findAvalibleDevice() {
Log.i("bluetooth", "findAvalibleDevice...");
// TODO Auto-generated method stub
Set<BluetoothDevice> device=bluetoothAdapter.getBondedDevices();
deviceList_bonded.clear();
if(bluetoothAdapter!=null&&bluetoothAdapter.isDiscovering()){
adapter1.notifyDataSetChanged();
}
if(device.size()>0){
//already
for(Iterator<BluetoothDevice> it = device.iterator(); it.hasNext();){
BluetoothDevice btd=it.next();
deviceList_bonded.add(btd.getName()+'\n'+btd.getAddress());
adapter1.notifyDataSetChanged();
}
}else{
deviceList_bonded.add("No can be matched to use bluetooth");
adapter1.notifyDataSetChanged();
}
}
/**
* show the massage
* @param showstring content
*/
private void showSnackbar(String showstring){
Snackbar.make(container, showstring,Snackbar.LENGTH_LONG)
.setActionTextColor(getResources().getColor(R.color.button_unable)).show();
}
@Override
protected void onDestroy() {
super.onDestroy();
binder.disconnectCurrentPort(new UiExecute() {
@Override
public void onsucess() {
}
@Override
public void onfailed() {
}
});
unbindService(conn);
}
}