Hot questions for Using Transmission Control Protocol in android recyclerview

Question:

About my App

In my app there is a TCP Client at the start it ask the server for a number, and for now it's working properly but the problem is when i have to open the connection again and ask number times that the server sent before for other data. I mean i'm trying to make a for cycle that will ask X times the server for data and will put them in RecyclerView.Adapter but for now the For Cycle goes in a infinity loop without stoping after X times .

Example

So if i'm starting my app and it reveice number 5 from the server i will ask the server for 1st number details after i got it i will ask for 2nd number details and co.

Here is my AsyncTask from MainActivity code where i get the X number from the server at the start :
   public static class ConnectTask extends AsyncTask<String, String, Client> {

    @Override
    protected Client doInBackground(String... message) {


        client = new Client(new Client.OnMessageReceived() {
            @Override

            public void messageReceived(String message) {

                publishProgress(message);

            }
    });
        client.run();

        return null;
    }

    @Override
    protected void onProgressUpdate(String... values) {
        super.onProgressUpdate(values);

        if(MainActivity.active){
            msgServer.setTextColor(Color.parseColor("#00FF00"));
            msgServer.setText("ONLINE");

            SelfNumber = values[0];
        }
        if(help.active){
            for(int i=0; i< Integer.valueOf(SelfNumber); i++){


            StringTokenizer stringTokenizer = new StringTokenizer(String.valueOf(values[0]),"#");
            status = stringTokenizer.nextToken();
            receipt = stringTokenizer.nextToken();
            eur = stringTokenizer.nextToken();

                help.adapter = new SelfAdapter(("CASSA SELF N°" + Integer.toString(i+1)),"EUR: " + eur,"SC: " + receipt,help.img);
                help.selfList.add(help.adapter);
                help.adapterView.notifyDataSetChanged();

                startConnection.removeCallbacks(runnableConnection);
                startConnection.postDelayed(runnableConnection,100);

                startCashMessage.removeCallbacks(runnableCashMessage);
                startCashMessage.postDelayed(runnableCashMessage,250);


            }

        }

    }
}
Handlers :
static Handler startConnection = new Handler();
static Runnable runnableConnection = new Runnable() {
    @Override
    public void run() {

        new ConnectTask().execute("");
    }
};

    static Handler startCashMessage = new Handler();
static Runnable runnableCashMessage = new Runnable() {
    @Override
    public void run() {
        if (help.active) {
            final Cursor cursor = myDB.fetchData();
            if (cursor.moveToFirst()) {
                do {
                    Client.SERVER_IP = cursor.getString(1);
                } while (cursor.moveToNext());
            }
            if (client != null) {
                    client.sendMessage("RICEVO DATI CASSA 1");
                }
            }
        }
};

Answer:

I think you will benefit from learning to use RxJava / RxAndroid.

I believe that this presentation (and a video link) will help you with a solution, he was presenting a solution to a similar problem.

If you never used RxJava before perhaps you should start with his first presentation and video.

Good Luck!

Question:

I've made an app that is receiving some data from a TCP Client to my TCP Server that store the data in SQlite DB, and actually i've made a recyclerView where to visualize all that data but now my issue is what i'm trying like 2 weeks to refresh the recyclerView in real Time, i mean if a TCP Client will send a new package to my TCP Server and if i'm in the activity with the recyclerView the data have to be added dynamically. I will also accept any type of tips and suggestions on how to improve my app. Actually it's my 1st app i've ever created in Android.

HERE you can find my Server(TCPServer),RecyclerViewAdapter,Adapter(constructor),allert.java(class where i invoke the RecyclerViewAdapter.

Hope someone will be able to help me and ill be very grateful.


Answer:

Try sending broadcast method. Here are the steps :

  1. Make a inner class that extends BroadcastReceiver in your activity.

    private class ExampleBroadcastReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        //do stuffs here, e.g. getting extras from intent
    }
    
  2. Declare a instance of the class outside any methods.

    public class MainActivity extends AppCompatActivity {
    
        private ExampleBroadcastReceiver exampleBroadcastReceiver;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            //stuffs
        }
    
    }
    
  3. Override onResume method. Initialize the instance you just made in this method. Then, register it with a intent-filter. This will make sure that your broadcast receiver ready when user open the activity.

    @Override
    protected void onResume() {
        super.onResume();
        IntentFilter filter = new IntentFilter();
        filter.addAction("com.example.MainActivity");   
        exampleBroadcastReceiver = new ExampleBroadcastReceiver();
        LocalBroadcastManager.getInstance(this).registerReceiver(exampleBroadcastReceiver, filter);
    }
    
  4. Override onPause method and unregister your receiver.

     @Override
     protected void onPause() {
         super.onPause();
         try {
             LocalBroadcastManager.getInstance(this).unregisterReceiver(exampleBroadcastReceiver);
         } catch (IllegalArgumentException e) {
        if (!e.getMessage().contains("Receiver not registered")) {
            // unexpected, re-throw
            throw e;
    
     }
    
  5. Make sure you use ArrayList for dynamic data.

  6. Whenever you receive data from server, after you store them in your database, send a broadcast with extras contains data you want to display in your activity.

EDITED

I registered the receiver using an instance of LocalBroadcastManager.

Question:

I'm receiving a String with a number from a TCP Server to my TCP Client, that String specific the number of cash registers online and for every cash register i have to create a cardView, i created a cardViewand the recyclerViewAdapter but for now the one who set the amount of cash registers is me by adding string in the ArrayList. The String send by TCP Server is yet set as static in MainActivity but now i don't know how can i use it for create the desired amount.

Here is the code where i evoke the recyclerViewAdapter:

public class help extends AppCompatActivity {

private ArrayList selfList;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_help);
    Utils.darkenStatusBar(this, R.color.colorAccent);
    ImageButton home = (ImageButton) findViewById(R.id.casa);

    initViews();

    home.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
         finish();
        }
    });
}

private void initViews(){
    RecyclerView recyclerView = 
(RecyclerView)findViewById(R.id.recyclerviewSelfMachine);
    recyclerView.setHasFixedSize(true);
    RecyclerView.LayoutManager layoutManager = 
new LinearLayoutManager(getApplicationContext());
    recyclerView.setLayoutManager(layoutManager);

    selfList = new ArrayList<>();
    selfList.add("CASSA SELF N°1");
    selfList.add("CASSA SELF N°2");
    selfList.add("CASSA SELF N°3");
    selfList.add("CASSA SELF N°4");
    RecyclerView.Adapter adapter = new RecyclerViewSelf(selfList);
    recyclerView.setAdapter(adapter);
    }
}

Answer:

// after you receives the string from your server

String num = serverValue;

int limit = Integer.valueof(num);

selfList = new ArrayList<>();

for(int i=0; i<limit; i++)
{
    selfList.add("" + i);    // add "" with i if you want list with string type
}

// call your init method here
initViews();


// your init method
private void initViews(){
    RecyclerView recyclerView = 
    (RecyclerView)findViewById(R.id.recyclerviewSelfMachine);
    recyclerView.setHasFixedSize(true);
    RecyclerView.LayoutManager layoutManager = 
    new LinearLayoutManager(getApplicationContext());
    recyclerView.setLayoutManager(layoutManager);

    RecyclerView.Adapter adapter = new RecyclerViewSelf(selfList);
    recyclerView.setAdapter(adapter);
    }
}