I have 2 classes.

Activity Class 1 and normal class 2.

In the first class, there is a SimpleAdapter, and in the second class there is a network request.

Question: how can I transfer the data to the adapter from the second class, first?

Here is the interface itself

public interface ResponseCallback { void response(ArrayList<ResponseMsgArray> response); } 

Here is the activation class:

 public class FriendMsgActivity extends AppCompatActivity implements ResponseCallback { private ListView listView; String LOG_TAG = "FriendLOG"; ArrayList data; EditText editText; Handler mHandler; ChatMsgAdapter sAdapter; protected String LV_KEY = Auth.key; protected int LV_USID = Integer.parseInt(Auth.id); protected int GET_ID = Integer.parseInt(FriendActivity.get_id); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_friend_msg); setTitle(get_login); listView = (ListView) findViewById(R.id.lvFriendMsg); editText = (EditText) findViewById(R.id.form_input); } @Override public void response(ArrayList<ResponseMsgArray> response) { sAdapter = new ChatMsgAdapter(this, response); if(sAdapter == null) { listView.setAdapter(sAdapter); } else { sAdapter.notifyDataSetChanged(); } } class RefreshActivity extends Thread { @Override public void run() { runOnUiThread(new Runnable() { @Override public void run() { mHandler.postDelayed(this, 5000); new UpdateMsg(FriendMsgActivity.this).execute(); Log.d(LOG_TAG, "get handler"); } }); } } @Override protected void onStart() { super.onStart(); mHandler = new Handler(); mHandler.post(new RefreshActivity()); getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN); Log.d(LOG_TAG, "MainActivity: onStart()"); } } 

Here is the Json parser:

 public class ResponseMsgJson { String LOG_TAG = "FriendLOG"; public ArrayList<ResponseMsgArray> parseData(String response) { ArrayList<ResponseMsgArray> data = new ArrayList<>(); JSONObject dataJsonObj = null; try { dataJsonObj = new JSONObject(response); JSONArray chat = dataJsonObj.getJSONArray("data"); for (int i = 0; i < chat.length(); i++) { ResponseMsgArray rms = new ResponseMsgArray(); JSONObject msgList = chat.getJSONObject(i); String error = msgList.getString("error"); if (!error.equals("0")) { if (error.equals("1")) { Log.d(LOG_TAG, "Ошибка 1!.."); } if (error.equals("2")) { Log.d(LOG_TAG, "Ошибка 2!.."); } } else { String msg = msgList.getString("msg"); String msg_id = msgList.getString("msg_id"); String msg_time = msgList.getString("msg_time"); String msg_id_us = msgList.getString("msg_id_user"); rms.setMsg(msg); rms.setMsg_id(msg_id); rms.setMsg_time(msg_time); rms.setMsg_id_us(msg_id_us); data.add(rms); } } } catch (JSONException e) { e.printStackTrace(); } return data; } } 

AsynckTasc:

 public class UpdateMsg extends AsyncTask<ArrayList<ResponseMsgArray>, Void, ArrayList<ResponseMsgArray>> { String LOG_TAG = "FriendLOG"; protected String LV_KEY = Auth.key; protected int LV_USID = Integer.parseInt(Auth.id); protected int GET_ID = Integer.parseInt(FriendActivity.get_id); private ResponseCallback callback; public UpdateMsg(ResponseCallback callback) { this.callback = callback; } @Override protected void onPreExecute() { super.onPreExecute(); } @Override protected ArrayList<ResponseMsgArray> doInBackground(ArrayList<ResponseMsgArray>... params) { StringBuilder content = new StringBuilder(); byte[] data = null; String parammetrs = "FriendMsgLoad=true&get_id=" + GET_ID + "&us_id=" + LV_USID + "&key=" + LV_KEY; Log.d(LOG_TAG, parammetrs); HttpURLConnection urlConnection = null; BufferedReader reader = null; try { URL url = new URL("http://сайтточкаруиндСкс.php"); urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setConnectTimeout(5000); urlConnection.setReadTimeout(5000); urlConnection.setRequestMethod("POST"); urlConnection.setDoOutput(true); urlConnection.setDoInput(true); urlConnection.setRequestProperty("Content-Length", "" + Integer.toString(parammetrs.getBytes().length)); OutputStream os = urlConnection.getOutputStream(); data = parammetrs.getBytes("UTF-8"); os.write(data); urlConnection.connect(); InputStream inputStream = urlConnection.getInputStream(); reader = new BufferedReader(new InputStreamReader(inputStream)); String line; while ((line = reader.readLine()) != null) { content.append(line + "\n"); } if (content.length() == 0) { return null; } return new ResponseMsgJson().parseData(content.toString()); } catch (IOException e) { Log.d("PlaceholderFragment", "Error ", e); return null; } finally { if (urlConnection != null) { urlConnection.disconnect(); } } } protected void onPostExecute(ArrayList<ResponseMsgArray> result) { callback.response(result); } } 

Adapter itself:

 public class ChatMsgAdapter extends ArrayAdapter<ResponseMsgArray> { private Context context; private ArrayList<ResponseMsgArray> data; protected String LV_KEY = Auth.key; protected int LV_USID = Integer.parseInt(Auth.id); protected int GET_ID = Integer.parseInt(FriendActivity.get_id); String LOG_TAG = "FriendLOG"; public ChatMsgAdapter(Context context, ArrayList<ResponseMsgArray> values) { super(context,R.layout.activity_friend_msg, values); this.data = values; this.context = context; } @Override public View getView(int position, View convertView, ViewGroup parent) { LayoutInflater inflater = LayoutInflater.from(context); View v; int type = getItemViewType(position); if(type == LV_USID) { v = inflater.inflate(R.layout.activity_friend_msg_adapter, null); TextView user_text = (TextView) v.findViewById(R.id.msg); TextView user_date = (TextView) v.findViewById(R.id.msg_time); user_text.setText(data.get(position).getMsg()); user_date.setText(data.get(position).getMsg_time()); } else if (type == GET_ID) { v = inflater.inflate(R.layout.talker, null); TextView talker_text = (TextView) v.findViewById(R.id.msg); TextView talker_date = (TextView) v.findViewById(R.id.msg_time); talker_text.setText(data.get(position).getMsg()); talker_date.setText(data.get(position).getMsg_time()); } else { //Если Π½Π΅Ρ‚ Π½Π°ΠΏΡ€ΠΈΠΌΠ΅Ρ€ сообщСний v = inflater.inflate(R.layout.msg_null, null); } return v; } @Override public int getItemViewType(int position) { int newPosition = Integer.parseInt(data.get(position).getMsg_id_us()); return newPosition; } } 

Well, the ResponseMsgArray itself:

 public class ResponseMsgArray { private String msg; private String msg_id; private String msg_time; private String msg_id_us; //************************ getters ****************************************** public String getMsg() { return msg; } public String getMsg_id() { return msg_id; } public String getMsg_time() { return msg_time; } public String getMsg_id_us() { return msg_id_us; } //*************************** setters ***************************************** public void setMsg(String msg) { this.msg = msg; } public void setMsg_id(String msg) { this.msg_id = msg; } public void setMsg_time(String msg) { this.msg_time = msg; } public void setMsg_id_us(String msg) { this.msg_id_us = msg; } } 

Laid out in principle, the finished task. Can someone come in handy, use :)

  • you have exactly two classes - none of which are activations? - Silento
  • I am sorry .... class 1 is activation - sergei1094
  • Create an instance of the adapter in activite, probably? - Silento
  • @Asgard what exactly do you mean? In the very activation adapter I have initialized - sergei1094
  • give the code, that's what I mean. - Silento

2 answers 2

example callback: where we get the data:

 private OnMessageListener callback; public interface OnMessageListener { void onMessage(SomeType mess); } public void setOnMessageListener(OnMessageListener listener) { callback = listener; } 

where we want to update the data subscribe to onMessage (...) new onMessageListener {...}

Only this need not be done in the adapter. the data must be stored separately, and updated in the adapter by event.

  • Thank you, rebuilt your program using the CallBack interface. I found a very useful dajver.blogspot.com/2015/10/callback-android.html article that can be useful to anyone. Now I am back again in the old age. Now I have the data displayed, but when the Handler time expires, my ListView again resets the scroll position. Could you symbolically show an example of updating the adapter guided by this article? My current activation was updated in the question - sergei1094
  • @ sergei1094 is not clear what it is and how it does not work. in the specified example (article) everything is more than specifically explained. I do not understand your Handler from the word at all. therefore, all I can offer is to debug it myself. put a label on callback.response (result); - check what is returned there; then acc. on sAdapter = new ChatMsgAdapter (this, response); - whether came here, how many times, etc. - Alyk

You can try using the EventBus library (the easiest way), or you can make an interface (the so-called kalbek) and transfer its copy from the adapter to the second class, and pull it from there and transfer data to it.

  • Did, but what to do next? I'm confused - sergei1094