单击标签时停止刷新标签

时间:2017-02-26 15:18:28

标签: android android-tablayout

我正在创建这个有三个标签的应用程序。 Tab1用于处理蓝牙传入和传出连接。这里出现的主要问题是,一旦我点击连接按钮就会创建连接但是当我切换标签然后跳回到tab1时,一切都会丢失,因为标签已重新初始化。我想阻止这种情况发生。请在我的代码中建议我更正。

这是MainActivity.java文件

public class MainActivity extends AppCompatActivity implements TabLayout.OnTabSelectedListener{



    private TabLayout tabLayout;
    StringBuilder recDataString = new StringBuilder();
    int handlerState = 0;
    private ViewPager viewPager;
    int initialize = 0;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        //Initializing the tablayout
        tabLayout = (TabLayout)findViewById(R.id.tabLayout);
        tabLayout.addTab(tabLayout.newTab().setText("Manual"));
        tabLayout.setSelectedTabIndicatorColor(Color.BLACK);
        tabLayout.addTab(tabLayout.newTab().setText("Status"));
        tabLayout.addTab(tabLayout.newTab().setText("Database"));
        tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);

        viewPager = (ViewPager)findViewById(R.id.pager);
        Pager adapter = new Pager(getSupportFragmentManager(),tabLayout.getTabCount());
        viewPager.setAdapter(adapter);


        tabLayout.setOnTabSelectedListener(this);



        BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                String id = intent.getStringExtra("BS");
                Log.d("********", "ID = " + id);
                /*if (id.equalsIgnoreCase("F")) {
                    sendToConnectedThread(id);
                }*/
            }

        };


        IntentFilter filter = new IntentFilter();
        filter.addAction("com.example.nitesh.finaltab.DATA_BROADCAST");
        getApplicationContext().registerReceiver(broadcastReceiver,filter);


    }

    public int getInitialize(){
        return initialize;
    }

    public void setInitialize(int m){
         this.initialize = m;
    }

    @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 void onTabSelected(TabLayout.Tab tab) {
        viewPager.setCurrentItem(tab.getPosition());
    }

    @Override
    public void onTabUnselected(TabLayout.Tab tab) {

    }

    @Override
    public void onTabReselected(TabLayout.Tab tab) {
    }

    }

这是Pager.java文件

public class Pager extends FragmentStatePagerAdapter {

    int tabcount;
    public Pager(FragmentManager fm, int tabcount){
        super(fm);
        this.tabcount = tabcount;
    }

    @Override
    public Fragment getItem(int position){
        switch (position){

            case 0:
                Tab1 tab1 = new Tab1();
                return tab1;
            case 1:
                Tab2 tab2 = new Tab2();
                return tab2;
            case 2:
                Tab3 tab3 = new Tab3();
                return tab3;
            default:
                return null;
        }
    }

    @Override
    public int getCount(){return tabcount;}
}

这是Tab1.java文件

public class Tab1 extends Fragment  {


    SQLiteDatabase alexadb,activitydb;
    MainActivity mainActivity= new MainActivity();
    StringBuilder recDataString = new StringBuilder();
    String address = "98:D3:32:20:5A:57";
    static final UUID myUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
    int handlerState = 0;
    public   boolean isBtConnected = false;
    ProgressDialog progressDialog;
    int initialize = 0;
    Handler bluetoothIn;
    BluetoothAdapter myBluetooth;
    BluetoothSocket bluetoothSocket;
    ConnectedThread connectedThread ;
    Button connect,forward,reverse,left,right,stop;
    int speed;
    String datatoSend;
    private final long REPEAT_DELAY = 50;
    boolean autoIncreament,autoDecreament;
    View view;
    private Handler repeatUpdateHandler = new Handler();
    private Handler senddataUpdatehandler = new Handler();

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {


            createDatabase();
            view = inflater.inflate(R.layout.tab1, container, false);
            forward = (Button) view.findViewById(R.id.bforward);
            reverse = (Button) view.findViewById(R.id.breverse);
            left = (Button) view.findViewById(R.id.bleft);
            stop = (Button) view.findViewById(R.id.bstop);
            connect = (Button)view.findViewById(R.id.buttonConnect);
            right = (Button) view.findViewById(R.id.bright);
            Toast.makeText(getContext(), "Tab1 Initiated", Toast.LENGTH_SHORT).show();
            final AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(getContext());
            alertDialogBuilder.setMessage("Ready to connect?");
           handler();

            class RepetitiveUpdater implements Runnable {

                @Override
                public void run() {
                    if (autoIncreament) {
                        increment();
                        repeatUpdateHandler.postDelayed(new RepetitiveUpdater(), REPEAT_DELAY);
                    } else if (autoDecreament) {
                        decrement();
                        repeatUpdateHandler.postDelayed(new RepetitiveUpdater(), REPEAT_DELAY);
                    }
                }


            }


            connect.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    alertDialogBuilder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {

                            Toast.makeText(getContext(), "Process Initiated", Toast.LENGTH_SHORT).show();
                            new CheckBT().execute();

                        }
                    });

                    alertDialogBuilder.setNegativeButton("No", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {

                        }
                    });
                    AlertDialog alertDialog = alertDialogBuilder.create();
                    alertDialog.show();
                }
            });

            right.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //  bluetoothConnect.sendData("R");
                    Log.d("Right", "Button is clicked");
                    sendData("R");
                    insertIntoActivityDB("Right Button is clicked");
                }
            });

            left.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    sendData("L");
                    insertIntoActivityDB("Left Button is clicked");
                }
            });

            reverse.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    sendData("B");
                    insertIntoActivityDB("Reverse Button is clicked");
                }
            });
            stop.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    autoDecreament = false;
                    autoIncreament = false;
                    sendData("S");
                    insertIntoActivityDB("Stop Button is clicked");
                }
            });
            forward.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    increment();
                    sendData("F");
                    insertIntoActivityDB("Forward Button is clicked");
                }
            });

            forward.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View v) {

                    autoIncreament = true;
                    autoDecreament = false;


                    repeatUpdateHandler.post(new RepetitiveUpdater());

                    return false;
                }
            });
            forward.setOnTouchListener(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    if (event.getAction() == MotionEvent.ACTION_UP && autoIncreament) {

                        autoIncreament = false;
                        autoDecreament = true;
                        sendData("D");
                        repeatUpdateHandler.post(new RepetitiveUpdater());
                    }
                    return false;

                }
            });




    return view;
}



    public void handler() {
        bluetoothIn = new Handler() {
            public void handleMessage(android.os.Message msg) {
                if (msg.what == handlerState) {
                    String readMessage = (String) msg.obj;
                    recDataString.append(readMessage);
                    int endofLineIndex = recDataString.indexOf("~");

                    if (endofLineIndex > 0) {
                        //  String dataInPrint = recDataString.substring(0,endofLineIndex);
                        String data = recDataString.substring(1, endofLineIndex);
                        Log.d("Received Text", "" + data);

                        String first = recDataString.substring(0, 1);

                        Log.d("First letter ", "Hello" + first);

                        if (first.equalsIgnoreCase("P")) {

                            insertIntoAlexaDB(data);

                        }

                        if (first.equalsIgnoreCase("V")) {
                            insertIntoAlexaDB(data);
                        } else {


                        }
                        recDataString.delete(0, recDataString.length());
                        //  dataInPrint = " ";
                        data = "";
                        first = " ";


                    }

                }
            }
        };

    }

public void increment(){

        speed++;
        sendData("F");
        Log.d("Increasing Speed"," "+speed);
        }

public void decrement() {
    if (speed > 0) {
        speed--;
        sendData("D");
        Log.d("Decreasing Speed", " " + speed);
    }
}




    public class CheckBT extends AsyncTask<Void, Void, Void>//UI Thread
    {

        private boolean ConnectSuccess = true;

        @Override
        protected void onPreExecute() {
           progressDialog = ProgressDialog.show(getContext(), "Connecting you", "From Alexa");
            Toast.makeText(getContext(),"Conneting",Toast.LENGTH_SHORT).show();

        }

        @Override
        protected Void doInBackground(Void... params) {
            try {
                if (bluetoothSocket == null || !isBtConnected) {
                    myBluetooth = BluetoothAdapter.getDefaultAdapter();
                    BluetoothDevice device = myBluetooth.getRemoteDevice(address);
                    bluetoothSocket = device.createInsecureRfcommSocketToServiceRecord(myUUID); //Create RFCOMM connection
                    BluetoothAdapter.getDefaultAdapter().cancelDiscovery();
                    bluetoothSocket.connect();
                }
            } catch (IOException e) {
                ConnectSuccess = false;
                 Toast.makeText(getContext(), "HC-05 didn't respond", Toast.LENGTH_SHORT).show();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);
            if (!ConnectSuccess) {
                 Toast.makeText(getContext(), "Connection Failed. Try Again", Toast.LENGTH_SHORT).show();

            } else {
                 Toast.makeText(getContext(), "Connected", Toast.LENGTH_SHORT).show();
                isBtConnected = true;

                connectedThread = new ConnectedThread(bluetoothSocket);
                connectedThread.start();
            }
            progressDialog.dismiss();
        }
    }

    private class ConnectedThread extends Thread{


        private final InputStream mmInStream;
        private final OutputStream mmOutStream;


        //creation of the thread
        public ConnectedThread(BluetoothSocket bluetoothSocket){
            InputStream tmpIn = null;
            OutputStream tmpOut = null;
            try{
                //create I/O streams for connection
                tmpIn = bluetoothSocket.getInputStream();
                tmpOut = bluetoothSocket.getOutputStream();
            }catch (IOException
                    e){}
            mmInStream = tmpIn;
            mmOutStream = tmpOut;
        }

        public boolean getBluetoothStatus() {
            Toast.makeText(getContext(),"Bluetooth Status from thread"+isBtConnected,Toast.LENGTH_SHORT).show();
            return isBtConnected;
        }
        public void run(){

            byte[] buffer = new byte[256];
            int bytes;
            //keep looping ot listen for received messages
            while(true){
                try{
                    Log.d("Running"," Connected_Thread");

                    isBtConnected = true;
                    bytes = mmInStream.read(buffer); //read bytes from input buffer
                    String readMessage = new String(buffer,0,bytes);
                    //Send the obtained bytes to the UIActivity via handler
                   bluetoothIn.obtainMessage(handlerState,bytes,-1,readMessage).sendToTarget();

                }catch (IOException e){
                    break;
                }

            }


        }




    }

    public void sendData(String data)  {

        try {
            bluetoothSocket.getOutputStream().write(data.toString().getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }






    /**Creation of DATABASE**/

    public void createDatabase(){

        alexadb = getContext().openOrCreateDatabase("AlexaDB", Context.MODE_PRIVATE,null);
        activitydb= getContext().openOrCreateDatabase("ActivityDB",Context.MODE_PRIVATE,null);


        alexadb.execSQL("CREATE TABLE IF NOT EXISTS alexa(id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,data VARCHAR);");
        activitydb.execSQL("CREATE TABLE IF NOT EXISTS activity(id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,data VARCHAR);");
    }

    public boolean insertIntoAlexaDB( String data){

        if (data.equalsIgnoreCase(" ")) {
            return false;
        } else {
            String query = "INSERT INTO alexa(data)VALUES('" + data + "');";
            alexadb.execSQL(query);
            return true;
        }
    }

    public boolean insertIntoActivityDB(String data){
        if (data.equalsIgnoreCase(" ")) {
            return false;
        } else {
            String query = "INSERT INTO activity(data)VALUES('" + data + "');";
            activitydb.execSQL(query);
            return true;
        }
    }
}

1 个答案:

答案 0 :(得分:0)

仅当您选择最后一个标签时才会发生这种情况吗?看一下offscreen page limit parameter:基本上你可以设置滚动ViewPager时要保留在内存中的页数。在您的情况下,屏幕外页面限制为2应足以始终将所有页面保留在内存中。