0

I have a task where I get information about service using NsdServiceInfo class such as name of service, host, port,IP address and displaying some of in the custom array adapter, however the information which I get from NsdServiceInfo it is not enough, I need to display model type of device which I am connecting to and the status, for that I am using personal protocol to connect with http server.

So far I only displaying service name and IP address on the screen because I only can access this information using NsdServiceInfo class. For the model type and status I thought to create separate class and store all the information from NsdServiceInfo to that custom class, but I am not sure how to do that or if it is correct approach. Till now I have created custom class and modified custom adapter to it, but when it comes to changing main activity I am lost.

If you have any ideas please share with me :)

PrinterNew.java custom class

package com.example.app;


public class PrinterNew {
String printerName;
String printerModel;
int printerState;


public PrinterNew() {

}


public String getPrinterName() {
    return printerName;
}

public void setPrinterName(String printerName) {
    this.printerName = printerName;
}

public String getPrinterModel() {
    return printerModel;
}

public void setPrinterModel(String printerModel) {
    this.printerName = printerModel;
}

public int getPrinterState() {
    return this.printerState;
}

public void setPrinterState(int printerState) {
    this.printerState = printerState;
}


}

NsdServiceInfoAdapter.java my custom array adapter (sorry for not clear name I was just playing around with code, did not wanted to rename classes just yet)

public class NsdServiceInfoAdapter extends ArrayAdapter<PrinterNew> {
private Context mContext;
private List<PrinterNew> services;
private InetAddress hostAddress;


//Creating new constructor with parameters such as this class(context), layout id (list item layout Id) and data model.

public NsdServiceInfoAdapter(@NonNull Context context, int layoutId, List<PrinterNew> list) {
    super(context, layoutId, list);
    mContext = context;
    services = list;
}

@NonNull
@Override

// Creating method get(), which is called when listItem needs to be populated with data.
//Get a View that displays the data at the specified position in the data set.
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
    View listItem = convertView;

    //Checking if view is empty then we inflate our list  layout.
    if (listItem == null)
        listItem = LayoutInflater.from(mContext).inflate(R.layout.list_item, parent, false);

    //Getting data's position in the data set.
    PrinterNew currentService = services.get(position);


    //We asign the the view to the item layout as a TextView
    TextView t = listItem.findViewById(R.id.TextView_serviceName);
    TextView r = listItem.findViewById(R.id.TextView_serviceIP);
    //hostAddress = currentService.getHost();
    r.setText("IP: " + currentService.getPrinterModel());
    t.setText("name: " + currentService.getPrinterName());


    Log.d("tag", "model" + currentService.getPrinterModel());
    Log.d("hello2", String.valueOf(currentService.getPrinterName()));


    return listItem;
}

}

MainActivity.java

public class MainActivity extends AppCompatActivity {

private String SERVICE_TYPE = "_lala._tcp."; // change to normal



private InetAddress hostAddress;
private int hostPort;
private NsdManager mNsdManager;
ArrayList<PrinterNew> services;
private NsdServiceInfoAdapter mAdapter;


@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);


    //Getting toolbar by id
    Toolbar toolbar = findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);


    services = new ArrayList<>();
    mAdapter = new NsdServiceInfoAdapter(this, R.id.TextView_serviceName, services);
    ListView listView = findViewById(R.id.ListViewServices);
    listView.setAdapter(mAdapter); // we add custom adapter to the listview to display data from adapter.


    //disabling default title text
    getSupportActionBar().setDisplayShowTitleEnabled(false);


    //NSD stuff

    mNsdManager = (NsdManager) getSystemService(Context.NSD_SERVICE);
    mNsdManager.discoverServices(SERVICE_TYPE, NsdManager.PROTOCOL_DNS_SD, mDiscoveryListener);

    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
            Object serviceObj = adapterView.getItemAtPosition(i);
            //NsdServiceInfo selectedService = (NsdServiceInfo) serviceObj;
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Intent intent = new Intent(MainActivity.this, WebViewActivity.class);
                    startActivity(intent);
                }
            });

            //mNsdManager.stopServiceDiscovery(mDiscoveryListener);
            //mNsdManager.resolveService(selectedService, mResolveListener);

        }
    });


    RequestQueue queue = Volley.newRequestQueue(this);
    String url = "http://10.0.0.100/SettingGetPrinterName";

    StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            Log.d("Model", "Printer mode" + response.toString());
            String temp = response.toString().substring(2, response.length() - 3);
            byte array[] = temp.getBytes();
            Log.d("Model", "Printer mode" + temp);

            //Assigning printer model to the PrinterNew class , printer model attribute.
            PrinterNew myPrinterDetails = new PrinterNew();
            myPrinterDetails.printerModel = temp;
            Log.d("Model", "zdrv77 " + myPrinterDetails.printerModel);

        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Log.d("Model", "Nope ");
        }
    });
    queue.add(stringRequest);
}

public NsdManager.ResolveListener initializeResolveListener() {
    return new NsdManager.ResolveListener() {
        @Override
        public void onResolveFailed(NsdServiceInfo nsdServiceInfo, int errorCode) {
            Log.e("TAG", "Resolved failed " + errorCode);
            Log.e("TAG", "Service = " + nsdServiceInfo);
            mNsdManager.resolveService(nsdServiceInfo, initializeResolveListener());
        }

        @Override
        public void onServiceResolved(final NsdServiceInfo nsdServiceInfo) {
            final PrinterNew myPrinterDetails = new PrinterNew();
            myPrinterDetails.printerName = nsdServiceInfo.getServiceName();
            myPrinterDetails.printerModel = myPrinterDetails.getPrinterModel();

            Log.d("TAG", "Resolve Succeeded " + nsdServiceInfo);
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    services.add(myPrinterDetails);

                    mAdapter.notifyDataSetChanged();
                }
            });
        }
    };
}

NsdManager.DiscoveryListener mDiscoveryListener = new NsdManager.DiscoveryListener() {
    @Override
    public void onStartDiscoveryFailed(String serviceType, int errorCode) {
        Log.e("TAG", "DiscoveryFailed: Error code: " + errorCode);
        mNsdManager.stopServiceDiscovery(this);
    }

    @Override
    public void onStopDiscoveryFailed(String serviceType, int errorCode) {
        Log.e("TAG", "Discovery failed : Error code: " + errorCode);
    }

    @Override
    public void onDiscoveryStarted(String regType) {
        Log.d("TAG", "Service discovery started");

    }

    @Override
    public void onDiscoveryStopped(String serviceType) {
        Log.i("TAG", "Discovery stopped: " + serviceType);

    }

    @Override
    public void onServiceFound(final NsdServiceInfo serviceInfo) {


        Log.d("TAG", "Service discovery success : " + serviceInfo);
        Log.d("TAG", "Host = " + serviceInfo.getServiceName());
        Log.d("TAG", "Port = " + serviceInfo.getPort());
        if (!services.contains(serviceInfo)) {
            if (serviceInfo.getServiceType().equals(SERVICE_TYPE)) {
                mNsdManager.resolveService(serviceInfo, initializeResolveListener());
            }
        }
    }

    @Override
    public void onServiceLost(NsdServiceInfo nsdServiceInfo) {
        Log.d("TAG", "Service lost " + nsdServiceInfo);
        PrinterNew serviceToRemove = new PrinterNew();
        for (PrinterNew currentService : services) {
            if (currentService.getPrinterName() == currentService.getPrinterName() && currentService.getPrinterModel() == currentService.getPrinterModel()) {
                serviceToRemove = currentService;
            }
        }
        final PrinterNew finalServiceToRemove = serviceToRemove;
        if (serviceToRemove != null) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    services.remove(finalServiceToRemove);
                    mAdapter.notifyDataSetChanged();
                }
            });
        }
        Log.d("TAG", "Xd" + services);
    }

};



/*

NsdManager.ResolveListener mResolveListener = new NsdManager.ResolveListener() {


    @Override
    public void onResolveFailed(NsdServiceInfo nsdServiceInfo, int errorCode) {
        Log.e("TAG", "Resolved failed " + errorCode);
        Log.e("TAG", "Service = " + nsdServiceInfo);
    }

    @Override
    public void onServiceResolved(NsdServiceInfo nsdServiceInfo) {


        Log.d("TAG", "bbz" + nsdServiceInfo);
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Intent intent = new Intent(MainActivity.this, WebViewActivity.class);
                startActivity(intent);
           }
        });



        Log.d("TAG", "Resolve Succeeded " + nsdServiceInfo);

        if (nsdServiceInfo.getServiceType().equals(SERVICE_TYPE)) {
            Log.d("TAG", "Same IP");
            return;
        }



        hostPort = nsdServiceInfo.getPort();
        hostAddress = nsdServiceInfo.getHost();


    }
};



// NsdHelper's tearDown method
public void tearDown() {

    mNsdManager.stopServiceDiscovery(mDiscoveryListener);

}
*/


}
Grace
  • 11
  • 4
  • why bothering with getters and setters if you're going to write code like this? PrinterNew myPrinterDetails = new PrinterNew(); myPrinterDetails.printerModel = temp; Log.d("Model", "zdrv77 " + myPrinterDetails.printerModel); – Stultuske Sep 03 '19 at 13:07
  • @Stultuske Because when the code becomes more complicated and is worked on by multiple people, you don't want to expose details like that. For example it may later be decided not to keep the data as separate variables but to keep a reference to the NsdServiceInfo. Making that change is trivial with getters, but a nightmare with direct access. It may not be necessary right now, but there's always value in keeping up good practices. – Gabe Sechan Sep 03 '19 at 13:59
  • @GabeSechan be that as it may, there is never value in having your variables accessible the way they are now, which was my point – Stultuske Sep 04 '19 at 06:08

0 Answers0