• After 15+ years, we've made a big change: Android Forums is now Early Bird Club. Learn more here.

How to extend 2 classes when using fragment in app

Lemon_Foam

Newbie
Sep 30, 2017
20
0
I'm building an app by using fragment with layout shown below. When i adding java class to tab 1 and tab 2, my app work as normal which allow me to slide between tab 1 and 2. When i try to add my third class into tab 3, there is an error appear which state that it cannot extend 2 class at once. Can anybody help me to solve this problem?

The first picture is code use for tab 1
The second picture is code use for tab 2
The third picture is code use for tab 3
The last picture is layout of my app


Picture 1

tab2.PNG






Picture 2


tab1.PNG







Picture 3


tab3.PNG







Last Picture


layout of app.PNG
 
Upvote 0
If it's no a humor, I'm really sorry. I just can't understand what is the problem with the lack of multiple inheritance.
I have looked at first post more closely.
MainActivity never should extend Fragment. It always must extend AppCompatActivity.
All the tabs should extends Fragment.
MainActivity should start and open first tab based on Fragment by default.

Again if I've violated some hidden rules, please forgive me. I promise never to offer to rewrite project.
Thank you.
 
Upvote 0
If it's no a humor, I'm really sorry. I just can't understand what is the problem with the lack of multiple inheritance.
I have looked at first post more closely.
MainActivity never should extend Fragment. It always must extend AppCompatActivity.
All the tabs should extends Fragment.
MainActivity should start and open first tab based on Fragment by default.

Again if I've violated some hidden rules, please forgive me. I promise never to offer to rewrite project.
Thank you.
Let me made a clearer explanation. First of all, i have create 3 activities in my android studio, which is MainActivities, FoodtrackerActivities and StepcounterActivities. I can move from one activities to other by using button. But the layout is not so beautiful. So i decide to put all of my 3 activities into fragment, so that i can swipe between them with a more beautiful layout.
As we know, to put activities into fragment, we need to extend these activities with fragment. For the FoodtrackerActivities and StepcounterActivities, it is work when i try to extend it with fregment. Below is how it look like in my app.
Screenshot_20180418-221658 (1).jpg Screenshot_20180418-221706.jpg
So, now what i want is to put the third activitiy (MainActivity) into fragment, But when i try to extend MainActivities with fragment, it show an error.
So my problem now is how i can solve this problem found in MainActivities
 
Upvote 0
This is my MainActivity code with problem which cannot extend fragment



Java:
public class MainActivity  extends BlunoLibrary, Fragment {
    private Button buttonScan;
    private Button buttonSerialSend;
    private EditText serialSendText;
    private TextView serialReceivedText;
   
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        onCreateProcess();                                                        //onCreate Process by BlunoLibrary


        serialBegin(115200);                                                    //set the Uart Baudrate on BLE chip to 115200

        serialReceivedText=(TextView) findViewById(R.id.serialReveicedText);    //initial the EditText of the received data
        serialSendText=(EditText) findViewById(R.id.serialSendText);            //initial the EditText of the sending data

        buttonSerialSend = (Button) findViewById(R.id.buttonSerialSend);        //initial the button for sending the data
        buttonSerialSend.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub

                serialSend(serialSendText.getText().toString());                //send the data to the BLUNO
            }
        });

        buttonScan = (Button) findViewById(R.id.buttonScan);                    //initial the button for scanning the BLE device
        buttonScan.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub

                buttonScanOnClickProcess();                                        //Alert Dialog for selecting the BLE device
            }
        });
    }

    protected void onResume(){
        super.onResume();
        System.out.println("BlUNOActivity onResume");
        onResumeProcess();                                                        //onResume Process by BlunoLibrary
    }
   
   
   
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        onActivityResultProcess(requestCode, resultCode, data);                    //onActivityResult Process by BlunoLibrary
        super.onActivityResult(requestCode, resultCode, data);
    }
   
    @Override
    protected void onPause() {
        super.onPause();
        onPauseProcess();                                                        //onPause Process by BlunoLibrary
    }
   
    protected void onStop() {
        super.onStop();
        onStopProcess();                                                        //onStop Process by BlunoLibrary
    }
   
    @Override
    protected void onDestroy() {
        super.onDestroy();   
        onDestroyProcess();                                                        //onDestroy Process by BlunoLibrary
    }

    @Override
    public void onConectionStateChange(connectionStateEnum theConnectionState) {//Once connection state changes, this function will be called
        switch (theConnectionState) {                                            //Four connection state
        case isConnected:
            buttonScan.setText("Connected");
            break;
        case isConnecting:
            buttonScan.setText("Connecting");
            break;
        case isToScan:
            buttonScan.setText("Scan");
            break;
        case isScanning:
            buttonScan.setText("Scanning");
            break;
        case isDisconnecting:
            buttonScan.setText("isDisconnecting");
            break;
        default:
            break;
        }
    }

    @Override
    public void onSerialReceived(String theString) {                            //Once connection data received, this function will be called
        // TODO Auto-generated method stub
        serialReceivedText.append(theString);                            //append the text into the EditText
        //The Serial data from the BLUNO may be sub-packaged, so using a buffer to hold the String is a good choice.
        ((ScrollView)serialReceivedText.getParent()).fullScroll(View.FOCUS_DOWN);
    }

}
 
Upvote 0
Never mind, it was an attempt at humour, based on your willingness to provide comprehensive help, which is commendable.
Ok, understood.

As we know, to put activities into fragment, we need to extend these activities with fragment. For the FoodtrackerActivities and StepcounterActivities, it is work when i try to extend it with fregment. Below is how it look like in my app.
As I've already said MainActivity should be Activity, but Tabs Activities inside ViewPager should be Fragments.
Please find project here https://github.com/v777779/aad_20180418
Android Studio 3.1
Download, unzip, open and run.
 
Upvote 0
Ok, understood.


As I've already said MainActivity should be Activity, but Tabs Activities inside ViewPager should be Fragments.
Please find project here https://github.com/v777779/aad_20180418
Android Studio 3.1
Download, unzip, open and run.
Sir i have already download ur code and put my FoodtrackerActivities into ur FragmentUserActivity1 and put my StepcounterActivities into ur FragmentUserActivity2. Then i have change my MainActivity to DeviceActivity to avoid confusion. Then, how i can put my DeviceActivity into FragmentUserActivity3?

Java:
public class DeviceActivity  extends BlunoLibrary, Fragment {
    private Button buttonScan;
    private Button buttonSerialSend;
    private EditText serialSendText;
    private TextView serialReceivedText;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        onCreateProcess();                                                        //onCreate Process by BlunoLibrary
        serialBegin(115200);                                                    //set the Uart Baudrate on BLE chip to 115200
        serialReceivedText=(TextView) findViewById(R.id.serialReveicedText);    //initial the EditText of the received data
        serialSendText=(EditText) findViewById(R.id.serialSendText);            //initial the EditText of the sending data
        buttonSerialSend = (Button) findViewById(R.id.buttonSerialSend);        //initial the button for sending the data
        buttonSerialSend.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                serialSend(serialSendText.getText().toString());                //send the data to the BLUNO
            }
        });
        buttonScan = (Button) findViewById(R.id.buttonScan);                    //initial the button for scanning the BLE device
        buttonScan.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                buttonScanOnClickProcess();                                        //Alert Dialog for selecting the BLE device
            }
        });
    }
    protected void onResume(){
        super.onResume();
        System.out.println("BlUNOActivity onResume");
        onResumeProcess();                                                        //onResume Process by BlunoLibrary
    }
 
 
 
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        onActivityResultProcess(requestCode, resultCode, data);                    //onActivityResult Process by BlunoLibrary
        super.onActivityResult(requestCode, resultCode, data);
    }
 
    @Override
    protected void onPause() {
        super.onPause();
        onPauseProcess();                                                        //onPause Process by BlunoLibrary
    }
 
    protected void onStop() {
        super.onStop();
        onStopProcess();                                                        //onStop Process by BlunoLibrary
    }
 
    @Override
    protected void onDestroy() {
        super.onDestroy();
        onDestroyProcess();                                                        //onDestroy Process by BlunoLibrary
    }
    @Override
    public void onConectionStateChange(connectionStateEnum theConnectionState) {//Once connection state changes, this function will be called
        switch (theConnectionState) {                                            //Four connection state
        case isConnected:
            buttonScan.setText("Connected");
            break;
        case isConnecting:
            buttonScan.setText("Connecting");
            break;
        case isToScan:
            buttonScan.setText("Scan");
            break;
        case isScanning:
            buttonScan.setText("Scanning");
            break;
        case isDisconnecting:
            buttonScan.setText("isDisconnecting");
            break;
        default:
            break;
        }
    }
    @Override
    public void onSerialReceived(String theString) {                            //Once connection data received, this function will be called
        // TODO Auto-generated method stub
        serialReceivedText.append(theString);                            //append the text into the EditText
        //The Serial data from the BLUNO may be sub-packaged, so using a buffer to hold the String is a good choice.
        ((ScrollView)serialReceivedText.getParent()).fullScroll(View.FOCUS_DOWN);
    }
}
 
Upvote 0
The problem is you are going to extend Fragment and BlunoLibrary at the same time.
Why do you extend Bluno? Is it possible to create instance of BlunoLibrary Class and put it as a field inside of DeviceActivity class?
Is it possible to use interface of BlunoLibrary instead of class BlunoLibrary.
And could you please provide link on BlunoLibrary.
 
Upvote 0
The problem is you are going to extend Fragment and BlunoLibrary at the same time.
Why do you extend Bluno? Is it possible to create instance of BlunoLibrary Class and put it as a field inside of DeviceActivity class?
Is it possible to use interface of BlunoLibrary instead of class BlunoLibrary.
And could you please provide link on BlunoLibrary.
The DeviceActivity is used to collect data from my electronic device built, so it should extend BlunoLibrary (library use to connect my device known as bluno beetle with app build).
This is the code for BlunoLibrary:

Java:
public abstract  class BlunoLibrary  extends Activity{

    private Context mainContext=this;

   
//    public BlunoLibrary(Context theContext) {
//       
//        mainContext=theContext;
//    }

    public abstract void onConectionStateChange(connectionStateEnum theconnectionStateEnum);
    public abstract void onSerialReceived(String theString);
    public void serialSend(String theString){
        if (mConnectionState == connectionStateEnum.isConnected) {
            mSCharacteristic.setValue(theString);
            mBluetoothLeService.writeCharacteristic(mSCharacteristic);
        }
    }
   
    private int mBaudrate=115200;    //set the default baud rate to 115200
    private String mPassword="AT+PASSWOR=DFRobot\r\n";
   
   
    private String mBaudrateBuffer = "AT+CURRUART="+mBaudrate+"\r\n";
   
//    byte[] mBaudrateBuffer={0x32,0x00,(byte) (mBaudrate & 0xFF),(byte) ((mBaudrate>>8) & 0xFF),(byte) ((mBaudrate>>16) & 0xFF),0x00};;
   
   
    public void serialBegin(int baud){
        mBaudrate=baud;
        mBaudrateBuffer = "AT+CURRUART="+mBaudrate+"\r\n";
    }
   
   
    static class ViewHolder {
        TextView deviceName;
        TextView deviceAddress;
    }
    private static BluetoothGattCharacteristic mSCharacteristic, mModelNumberCharacteristic, mSerialPortCharacteristic, mCommandCharacteristic;
    BluetoothLeService mBluetoothLeService;
    private ArrayList<ArrayList<BluetoothGattCharacteristic>> mGattCharacteristics =
            new ArrayList<ArrayList<BluetoothGattCharacteristic>>();
    private LeDeviceListAdapter mLeDeviceListAdapter=null;
    private BluetoothAdapter mBluetoothAdapter;
    private boolean mScanning =false;
    AlertDialog mScanDeviceDialog;
    private String mDeviceName;
    private String mDeviceAddress;
    public enum connectionStateEnum{isNull, isScanning, isToScan, isConnecting , isConnected, isDisconnecting};
    public connectionStateEnum mConnectionState = connectionStateEnum.isNull;
    private static final int REQUEST_ENABLE_BT = 1;

    private Handler mHandler= new Handler();
   
    public boolean mConnected = false;

    private final static String TAG = BlunoLibrary.class.getSimpleName();

    private Runnable mConnectingOverTimeRunnable=new Runnable(){

        @Override
        public void run() {
            if(mConnectionState==connectionStateEnum.isConnecting)
            mConnectionState=connectionStateEnum.isToScan;
            onConectionStateChange(mConnectionState);
            mBluetoothLeService.close();
        }};
       
    private Runnable mDisonnectingOverTimeRunnable=new Runnable(){

        @Override
        public void run() {
            if(mConnectionState==connectionStateEnum.isDisconnecting)
            mConnectionState=connectionStateEnum.isToScan;
            onConectionStateChange(mConnectionState);
            mBluetoothLeService.close();
        }};
   
    public static final String SerialPortUUID="0000dfb1-0000-1000-8000-00805f9b34fb";
    public static final String CommandUUID="0000dfb2-0000-1000-8000-00805f9b34fb";
    public static final String ModelNumberStringUUID="00002a24-0000-1000-8000-00805f9b34fb";
   
    public void onCreateProcess()
    {
        if(!initiate())
        {
            Toast.makeText(mainContext, R.string.error_bluetooth_not_supported,
                    Toast.LENGTH_SHORT).show();
            ((Activity) mainContext).finish();
        }


        Intent gattServiceIntent = new Intent(this, BluetoothLeService.class);
        bindService(gattServiceIntent, mServiceConnection, Context.BIND_AUTO_CREATE);
       
        // Initializes list view adapter.
        mLeDeviceListAdapter = new LeDeviceListAdapter();
        // Initializes and show the scan Device Dialog
        mScanDeviceDialog = new AlertDialog.Builder(mainContext)
        .setTitle("BLE Device Scan...").setAdapter(mLeDeviceListAdapter, new DialogInterface.OnClickListener() {
           
            @Override
            public void onClick(DialogInterface dialog, int which)
            {
                final BluetoothDevice device = mLeDeviceListAdapter.getDevice(which);
                if (device == null)
                    return;
                scanLeDevice(false);

                if(device.getName()==null || device.getAddress()==null)
                {
                    mConnectionState=connectionStateEnum.isToScan;
                    onConectionStateChange(mConnectionState);
                }
                else{

                    System.out.println("onListItemClick " + device.getName().toString());

                    System.out.println("Device Name:"+device.getName() + "   " + "Device Name:" + device.getAddress());

                    mDeviceName=device.getName().toString();
                    mDeviceAddress=device.getAddress().toString();

                    if (mBluetoothLeService.connect(mDeviceAddress)) {
                        Log.d(TAG, "Connect request success");
                        mConnectionState=connectionStateEnum.isConnecting;
                        onConectionStateChange(mConnectionState);
                        mHandler.postDelayed(mConnectingOverTimeRunnable, 10000);
                    }
                    else {
                        Log.d(TAG, "Connect request fail");
                        mConnectionState=connectionStateEnum.isToScan;
                        onConectionStateChange(mConnectionState);
                    }
                }
            }
        })
        .setOnCancelListener(new DialogInterface.OnCancelListener() {

            @Override
            public void onCancel(DialogInterface arg0) {
                System.out.println("mBluetoothAdapter.stopLeScan");

                mConnectionState = connectionStateEnum.isToScan;
                onConectionStateChange(mConnectionState);
                mScanDeviceDialog.dismiss();

                scanLeDevice(false);
            }
        }).create();
       
    }
   
   
   
    public void onResumeProcess() {
        System.out.println("BlUNOActivity onResume");
        // Ensures Bluetooth is enabled on the device. If Bluetooth is not
        // currently enabled,
        // fire an intent to display a dialog asking the user to grant
        // permission to enable it.
        if (!mBluetoothAdapter.isEnabled()) {
            if (!mBluetoothAdapter.isEnabled()) {
                Intent enableBtIntent = new Intent(
                        BluetoothAdapter.ACTION_REQUEST_ENABLE);
                ((Activity) mainContext).startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
            }
        }
       
       
        mainContext.registerReceiver(mGattUpdateReceiver, makeGattUpdateIntentFilter());

    }
   

    public void onPauseProcess() {
        System.out.println("BLUNOActivity onPause");
        scanLeDevice(false);
        mainContext.unregisterReceiver(mGattUpdateReceiver);
        mLeDeviceListAdapter.clear();
        mConnectionState=connectionStateEnum.isToScan;
        onConectionStateChange(mConnectionState);
        mScanDeviceDialog.dismiss();
        if(mBluetoothLeService!=null)
        {
            mBluetoothLeService.disconnect();
            mHandler.postDelayed(mDisonnectingOverTimeRunnable, 10000);

//            mBluetoothLeService.close();
        }
        mSCharacteristic=null;

    }

   
    public void onStopProcess() {
        System.out.println("MiUnoActivity onStop");
        if(mBluetoothLeService!=null)
        {
//            mBluetoothLeService.disconnect();
//            mHandler.postDelayed(mDisonnectingOverTimeRunnable, 10000);
            mHandler.removeCallbacks(mDisonnectingOverTimeRunnable);
            mBluetoothLeService.close();
        }
        mSCharacteristic=null;
    }

    public void onDestroyProcess() {
        mainContext.unbindService(mServiceConnection);
        mBluetoothLeService = null;
    }
   
    public void onActivityResultProcess(int requestCode, int resultCode, Intent data) {
        // User chose not to enable Bluetooth.
        if (requestCode == REQUEST_ENABLE_BT
                && resultCode == Activity.RESULT_CANCELED) {
            ((Activity) mainContext).finish();
            return;
        }
    }

    boolean initiate()
    {
        // Use this check to determine whether BLE is supported on the device.
        // Then you can
        // selectively disable BLE-related features.
        if (!mainContext.getPackageManager().hasSystemFeature(
                PackageManager.FEATURE_BLUETOOTH_LE)) {
            return false;
        }
       
        // Initializes a Bluetooth adapter. For API level 18 and above, get a
        // reference to
        // BluetoothAdapter through BluetoothManager.
        final BluetoothManager bluetoothManager = (BluetoothManager) mainContext.getSystemService(Context.BLUETOOTH_SERVICE);
        mBluetoothAdapter = bluetoothManager.getAdapter();
   
        // Checks if Bluetooth is supported on the device.
        if (mBluetoothAdapter == null) {
            return false;
        }
        return true;
    }
   
     // Handles various events fired by the Service.
    // ACTION_GATT_CONNECTED: connected to a GATT server.
    // ACTION_GATT_DISCONNECTED: disconnected from a GATT server.
    // ACTION_GATT_SERVICES_DISCOVERED: discovered GATT services.
    // ACTION_DATA_AVAILABLE: received data from the device.  This can be a result of read
    //                        or notification operations.
    private final BroadcastReceiver mGattUpdateReceiver = new BroadcastReceiver() {
        @SuppressLint("DefaultLocale")
        @Override
        public void onReceive(Context context, Intent intent) {
            final String action = intent.getAction();
            System.out.println("mGattUpdateReceiver->onReceive->action="+action);
            if (BluetoothLeService.ACTION_GATT_CONNECTED.equals(action)) {
                mConnected = true;
                mHandler.removeCallbacks(mConnectingOverTimeRunnable);

            } else if (BluetoothLeService.ACTION_GATT_DISCONNECTED.equals(action)) {
                mConnected = false;
                mConnectionState = connectionStateEnum.isToScan;
                onConectionStateChange(mConnectionState);
                mHandler.removeCallbacks(mDisonnectingOverTimeRunnable);
                mBluetoothLeService.close();
            } else if (BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED.equals(action)) {
                // Show all the supported services and characteristics on the user interface.
                for (BluetoothGattService gattService : mBluetoothLeService.getSupportedGattServices()) {
                    System.out.println("ACTION_GATT_SERVICES_DISCOVERED  "+
                            gattService.getUuid().toString());
                }
                getGattServices(mBluetoothLeService.getSupportedGattServices());
            } else if (BluetoothLeService.ACTION_DATA_AVAILABLE.equals(action)) {
                if(mSCharacteristic==mModelNumberCharacteristic)
                {
                    if (intent.getStringExtra(BluetoothLeService.EXTRA_DATA).toUpperCase().startsWith("DF BLUNO")) {
                        mBluetoothLeService.setCharacteristicNotification(mSCharacteristic, false);
                        mSCharacteristic=mCommandCharacteristic;
                        mSCharacteristic.setValue(mPassword);
                        mBluetoothLeService.writeCharacteristic(mSCharacteristic);
                        mSCharacteristic.setValue(mBaudrateBuffer);
                        mBluetoothLeService.writeCharacteristic(mSCharacteristic);
                        mSCharacteristic=mSerialPortCharacteristic;
                        mBluetoothLeService.setCharacteristicNotification(mSCharacteristic, true);
                        mConnectionState = connectionStateEnum.isConnected;
                        onConectionStateChange(mConnectionState);
                       
                    }
                    else {
                        Toast.makeText(mainContext, "Please select DFRobot devices",Toast.LENGTH_SHORT).show();
                        mConnectionState = connectionStateEnum.isToScan;
                        onConectionStateChange(mConnectionState);
                    }
                }
                else if (mSCharacteristic==mSerialPortCharacteristic) {
                    onSerialReceived(intent.getStringExtra(BluetoothLeService.EXTRA_DATA));
                }
               
           
                System.out.println("displayData "+intent.getStringExtra(BluetoothLeService.EXTRA_DATA));
               
//                mPlainProtocol.mReceivedframe.append(intent.getStringExtra(BluetoothLeService.EXTRA_DATA)) ;
//                System.out.print("mPlainProtocol.mReceivedframe:");
//                System.out.println(mPlainProtocol.mReceivedframe.toString());

               
            }
        }
    };
   
    void buttonScanOnClickProcess()
    {
        switch (mConnectionState) {
        case isNull:
            mConnectionState=connectionStateEnum.isScanning;
            onConectionStateChange(mConnectionState);
            scanLeDevice(true);
            mScanDeviceDialog.show();
            break;
        case isToScan:
            mConnectionState=connectionStateEnum.isScanning;
            onConectionStateChange(mConnectionState);
            scanLeDevice(true);
            mScanDeviceDialog.show();
            break;
        case isScanning:
           
            break;

        case isConnecting:
           
            break;
        case isConnected:
            mBluetoothLeService.disconnect();
            mHandler.postDelayed(mDisonnectingOverTimeRunnable, 10000);

//            mBluetoothLeService.close();
            mConnectionState=connectionStateEnum.isDisconnecting;
            onConectionStateChange(mConnectionState);
            break;
        case isDisconnecting:
           
            break;

        default:
            break;
        }
       
       
    }
   
    void scanLeDevice(final boolean enable) {
        if (enable) {
            // Stops scanning after a pre-defined scan period.

            System.out.println("mBluetoothAdapter.startLeScan");
           
            if(mLeDeviceListAdapter != null)
            {
                mLeDeviceListAdapter.clear();
                mLeDeviceListAdapter.notifyDataSetChanged();
            }
           
            if(!mScanning)
            {
                mScanning = true;
                mBluetoothAdapter.startLeScan(mLeScanCallback);
            }
        } else {
            if(mScanning)
            {
                mScanning = false;
                mBluetoothAdapter.stopLeScan(mLeScanCallback);
            }
        }
    }
   
    // Code to manage Service lifecycle.
        ServiceConnection mServiceConnection = new ServiceConnection() {

        @Override
        public void onServiceConnected(ComponentName componentName, IBinder service) {
            System.out.println("mServiceConnection onServiceConnected");
            mBluetoothLeService = ((BluetoothLeService.LocalBinder) service).getService();
            if (!mBluetoothLeService.initialize()) {
                Log.e(TAG, "Unable to initialize Bluetooth");
                ((Activity) mainContext).finish();
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            System.out.println("mServiceConnection onServiceDisconnected");
            mBluetoothLeService = null;
        }
    };

    // Device scan callback.
    private BluetoothAdapter.LeScanCallback mLeScanCallback = new BluetoothAdapter.LeScanCallback() {

        @Override
        public void onLeScan(final BluetoothDevice device, int rssi,
                byte[] scanRecord) {
            ((Activity) mainContext).runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    System.out.println("mLeScanCallback onLeScan run ");
                    mLeDeviceListAdapter.addDevice(device);
                    mLeDeviceListAdapter.notifyDataSetChanged();
                }
            });
        }
    };
   
    private void getGattServices(List<BluetoothGattService> gattServices) {
        if (gattServices == null) return;
        String uuid = null;
        mModelNumberCharacteristic=null;
        mSerialPortCharacteristic=null;
        mCommandCharacteristic=null;
        mGattCharacteristics = new ArrayList<ArrayList<BluetoothGattCharacteristic>>();

        // Loops through available GATT Services.
        for (BluetoothGattService gattService : gattServices) {
            uuid = gattService.getUuid().toString();
            System.out.println("displayGattServices + uuid="+uuid);
           
            List<BluetoothGattCharacteristic> gattCharacteristics =
                    gattService.getCharacteristics();
            ArrayList<BluetoothGattCharacteristic> charas =
                    new ArrayList<BluetoothGattCharacteristic>();

            // Loops through available Characteristics.
            for (BluetoothGattCharacteristic gattCharacteristic : gattCharacteristics) {
                charas.add(gattCharacteristic);
                uuid = gattCharacteristic.getUuid().toString();
                if(uuid.equals(ModelNumberStringUUID)){
                    mModelNumberCharacteristic=gattCharacteristic;
                    System.out.println("mModelNumberCharacteristic  "+mModelNumberCharacteristic.getUuid().toString());
                }
                else if(uuid.equals(SerialPortUUID)){
                    mSerialPortCharacteristic = gattCharacteristic;
                    System.out.println("mSerialPortCharacteristic  "+mSerialPortCharacteristic.getUuid().toString());
//                    updateConnectionState(R.string.comm_establish);
                }
                else if(uuid.equals(CommandUUID)){
                    mCommandCharacteristic = gattCharacteristic;
                    System.out.println("mSerialPortCharacteristic  "+mSerialPortCharacteristic.getUuid().toString());
//                    updateConnectionState(R.string.comm_establish);
                }
            }
            mGattCharacteristics.add(charas);
        }
       
        if (mModelNumberCharacteristic==null || mSerialPortCharacteristic==null || mCommandCharacteristic==null) {
            Toast.makeText(mainContext, "Please select DFRobot devices",Toast.LENGTH_SHORT).show();
            mConnectionState = connectionStateEnum.isToScan;
            onConectionStateChange(mConnectionState);
        }
        else {
            mSCharacteristic=mModelNumberCharacteristic;
            mBluetoothLeService.setCharacteristicNotification(mSCharacteristic, true);
            mBluetoothLeService.readCharacteristic(mSCharacteristic);
        }
       
    }
   
    private static IntentFilter makeGattUpdateIntentFilter() {
        final IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(BluetoothLeService.ACTION_GATT_CONNECTED);
        intentFilter.addAction(BluetoothLeService.ACTION_GATT_DISCONNECTED);
        intentFilter.addAction(BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED);
        intentFilter.addAction(BluetoothLeService.ACTION_DATA_AVAILABLE);
        return intentFilter;
    }
   
    private class LeDeviceListAdapter extends BaseAdapter {
        private ArrayList<BluetoothDevice> mLeDevices;
        private LayoutInflater mInflator;

        public LeDeviceListAdapter() {
            super();
            mLeDevices = new ArrayList<BluetoothDevice>();
            mInflator =  ((Activity) mainContext).getLayoutInflater();
        }

        public void addDevice(BluetoothDevice device) {
            if (!mLeDevices.contains(device)) {
                mLeDevices.add(device);
            }
        }

        public BluetoothDevice getDevice(int position) {
            return mLeDevices.get(position);
        }

        public void clear() {
            mLeDevices.clear();
        }

        @Override
        public int getCount() {
            return mLeDevices.size();
        }

        @Override
        public Object getItem(int i) {
            return mLeDevices.get(i);
        }

        @Override
        public long getItemId(int i) {
            return i;
        }

        @Override
        public View getView(int i, View view, ViewGroup viewGroup) {
            ViewHolder viewHolder;
            // General ListView optimization code.
            if (view == null) {
                view = mInflator.inflate(R.layout.listitem_device, null);
                viewHolder = new ViewHolder();
                viewHolder.deviceAddress = (TextView) view
                        .findViewById(R.id.device_address);
                viewHolder.deviceName = (TextView) view
                        .findViewById(R.id.device_name);
                System.out.println("mInflator.inflate  getView");
                view.setTag(viewHolder);
            } else {
                viewHolder = (ViewHolder) view.getTag();
            }

            BluetoothDevice device = mLeDevices.get(i);
            final String deviceName = device.getName();
            if (deviceName != null && deviceName.length() > 0)
                viewHolder.deviceName.setText(deviceName);
            else
                viewHolder.deviceName.setText(R.string.unknown_device);
            viewHolder.deviceAddress.setText(device.getAddress());

            return view;
        }
    }
}
 
Upvote 0
To solve you problem you should thrown one of classes which your DeviceActivity inherits.

I suspect you use this code for BlunoLibrary https://github.com/DFRobot/BlunoBasicDemo
As you can see BlunoLibrary Class extends Activity.

So you have three choices.
1. Extend BlunoLibrary Class from Fragment (instead of Activity) and replace Activity UI methods (onCreate, on Start...) with Fragment UI methods (onCreateView, onStart...)
You will get DeviceActivity extends BlunoLibrary, BlunoLibrary extends Fragment
So, your DeviceActivity will actually inherit both and Java rule will be not violated.
And yes, UI methods of BlunoLibrary will be redefined by UI methods of DeviceActivity and you
will need to cope with this.
May be better just extend BlunoLibrary Class from Fragment, replace methods and use it instead of DeviceActivity Class.
But if you are going to use BlunoLibrary multiple times you should use next variants 2 or 3.

2. Rewrite code of BlunoLibrary class and separate Activity methods (onCreate, onStart, OnResume) from Bluetooth processing methods and fields.
After that you will get User Class Bluno, that does not have superclass. You can insert Bluno object inside any Fragments as a field and use Bluno object and methods for connectivity to device.

3. Separate Activity methods (onCreate, onStart, OnResume) from Bluetooth processing methods and fields.Create Bluno Interface, which define methods for connectivity. Impements it in your Fragment and move code for Bluno inside the Fragment.

I think it's better but complicated to separate BlunoLibrary from UI and use it further. Author made mixed version for demo purposes.
This is an example where it has been done https://github.com/mibcxb/BlunoLibrary
Here Bluno interface used for User class BlunoBase. BlunoBase class does not have Activity as a superclass and used by BlunoManager like common user class.
 
Last edited:
Upvote 0
To solve you problem you should thrown one of classes which your DeviceActivity inherits.

I suspect you use this code for BlunoLibrary https://github.com/DFRobot/BlunoBasicDemo
As you can see BlunoLibrary Class extends Activity.

So you have three choices.
1. Extend BlunoLibrary Class from Fragment (instead of Activity) and replace Activity UI methods (onCreate, on Start...) with Fragment UI methods (onCreateView, onStart...)
You will get DeviceActivity extends BlunoLibrary, BlunoLibrary extends Fragment
So, your DeviceActivity will actually inherit both and Java rule will be not violated.
And yes, UI methods of BlunoLibrary will be redefined by UI methods of DeviceActivity and you
will need to cope with this.
May be better just extend BlunoLibrary Class from Fragment, replace methods and use it instead of DeviceActivity Class.
But if you are going to use BlunoLibrary multiple times you should use next variants 2 or 3.

2. Rewrite code of BlunoLibrary class and separate Activity methods (onCreate, onStart, OnResume) from Bluetooth processing methods and fields.
After that you will get User Class Bluno, that does not have superclass. You can insert Bluno object inside any Fragments as a field and use Bluno object and methods for connectivity to device.

3. Separate Activity methods (onCreate, onStart, OnResume) from Bluetooth processing methods and fields.Create Bluno Interface, which define methods for connectivity. Impements it in your Fragment and move code for Bluno inside the Fragment.

I think it's better but complicated to separate BlunoLibrary from UI and use it further. Author made mixed version for demo purposes.
This is an example where it has been done https://github.com/mibcxb/BlunoLibrary
Here Bluno interface used for User class BlunoBase. BlunoBase class does not have Activity as a superclass and used by BlunoManager like common user class.
Ya u r right sir, i taken the code from https://github.com/DFRobot/BlunoBasicDemo. But i still dont have any idea about what sir say. Sir u mean u prefer me to use third method by give away my BlunoLibrary class and replace it with BlunoBase class and BlunoManager class?
 
Last edited:
Upvote 0
If you extend BlunoLibrary from Fragment, you must use it in your Viewpager as a Tab Fragment Activity.
In this case DeviceActivity is removed from project and code from DeviceActivity merged with BlunoLibrary code.
BlunoLibrary will be used instead of DeviceActivity and DeviceActivity is removed from project at all.
I think this is the only way.
 
Upvote 0
If you extend BlunoLibrary from Fragment, you must use it in your Viewpager as a Tab Fragment Activity.
In this case DeviceActivity is removed from project and code from DeviceActivity merged with BlunoLibrary code.
BlunoLibrary will be used instead of DeviceActivity and DeviceActivity is removed from project at all.
I think this is the only way.
If you extend BlunoLibrary from Fragment, you must use it in your Viewpager as a Tab Fragment Activity.
In this case DeviceActivity is removed from project and code from DeviceActivity merged with BlunoLibrary code.
BlunoLibrary will be used instead of DeviceActivity and DeviceActivity is removed from project at all.
I think this is the only way.
I get what u say sir, but it is really complicated, i need some time for that
 
Upvote 0

BEST TECH IN 2023

We've been tracking upcoming products and ranking the best tech since 2007. Thanks for trusting our opinion: we get rewarded through affiliate links that earn us a commission and we invite you to learn more about us.

Smartphones