data transfer from class to fragment android



  • There's a class that passes json line and keeps it in line in its classroom, and there's a fragment that needs to be transferred.

    The parsedata itself.class is caused from a fragment.

    public class ParseData extends AsyncTask<String, Void, String> {
        public static String LOG_TAG = "my_log";
        public static String sharedValue;
        public Socket client;
        public String resultJson = "";
        private String ip = "192.168.1.162";
        private int port = 7777;
    
    @Override
    protected String doInBackground(String... params) {
        try {
            client = new Socket(ip, port); // connect to the server
            PrintWriter out = new PrintWriter(client.getOutputStream(),true);
            out.println(params[0]);
            InputStream is = client.getInputStream();
            StringBuilder buffer = new StringBuilder();
            BufferedReader reader = new BufferedReader(new InputStreamReader(is));
            String line;
            while ((line = reader.readLine()) != null) {
                buffer.append(line);
            }
            resultJson = buffer.toString();
            client.close();
    
        } catch (Exception e) {
            e.printStackTrace();
        }
        return resultJson;
    }
    @Override
    protected void onPostExecute(String strJson) {
        super.onPostExecute(strJson);
        JSONObject dataJsonObj = null;
        String illumination = "";
        try {
            dataJsonObj = new JSONObject(strJson);
            JSONArray friends = dataJsonObj.getJSONArray("data");
    
            for (int i = 0; i &lt; friends.length(); i++) {
                JSONObject friend = friends.getJSONObject(i);
                JSONObject contacts = friend.getJSONObject("weather");
                String cel = contacts.getString("temperature");
                String humidity = contacts.getString("humidity");
    
                Log.d(LOG_TAG, "Температура: " + cel);
                Log.d(LOG_TAG, "Влажность: " + humidity);
    
                sharedValue = cel;
    
            }
    
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
    

    }

    And the fragment code that needs these lines:

    public class LoftFragment extends Fragment implements View.OnClickListener {
    Button button;
    TextView temp;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.loft_layout, container, false);
        temp = (TextView) view.findViewById(R.id.twmpt);
        button = (Button) view.findViewById(R.id.btn1);
        button.setOnClickListener(this);
        String s = ParseData.sharedValue;
        temp.setText(s); // отобразить полученную строку
        return view;
    }
    

    }

    How can data transmission be better implemented?



  • You need to create a separate class that will download the data from the server, but there's nothing to know about the flow. The approximate structure of this class will be such (psevdodhode):

    public class WeatherLoader {
    
    public Result loadData(String someParam){
        //код по загрузке данных, в котором нет явного указания в каком потоке работать
    }    
    

    }

    Result here is an arbitrary type, put what you want in his place.

    Then in your fragment you create AsyncTask and download the data:

    public class LoadData extends AsyncTask<String, Void, Result> {

    @Override
    protected String doInBackground(String... params) {
    
        WeatherLoader loader = new WeatherLoader();
        return loader.loadData(params[0]);
    }
    
    @Override
    protected void onPostExecute(Result result) {
        // делаем с результатом что хотим
    }
    

    }

    Well, call it. AsyncTask in its Activity/Fragment As usual.

    My advice to you after you've learned AsyncTask study other ways of interacting with the server, which are now very large, as well. AsyncTask It's not the best way to organize this interaction. Look at the library. https://github.com/stephanenicolas/robospice ♪ Connected http://square.github.io/retrofit/ They can make life easier.




Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2