Last active
September 21, 2017 22:50
-
-
Save omayib/9e77be9c457c4192229474240f8c4b05 to your computer and use it in GitHub Desktop.
getting data directly from server
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Created by omayib on 18/09/17. | |
*/ | |
public class AlumnusListActivity extends Activity{ | |
private static final String TAG = "AlumnusListActivity"; | |
private RecyclerView mRecyclerView; | |
private LinearLayoutManager mLinearLayoutManager; | |
private RecyclerAdapter mAdapter; | |
private ArrayList<Person> alumnus; | |
@Override | |
protected void onCreate(@Nullable Bundle savedInstanceState) { | |
super.onCreate(savedInstanceState); | |
setContentView(R.layout.activity_alumni_list); | |
mRecyclerView = (RecyclerView) findViewById(R.id.recyclerViewAlumni); | |
mLinearLayoutManager = new LinearLayoutManager(this); | |
mRecyclerView.setLayoutManager(mLinearLayoutManager); | |
alumnus = new ArrayList<>(); | |
mAdapter = new RecyclerAdapter(alumnus); | |
mRecyclerView.setAdapter(mAdapter); | |
loadDataFromServer(); | |
} | |
private void loadDataFromServer() { | |
OkHttpClient client = new OkHttpClient(); | |
Request request = new Request.Builder().url("http://10.0.2.2:3000/alumnus").build(); | |
client.newCall(request).enqueue(new Callback() { | |
@Override | |
public void onFailure(Call call, IOException e) { | |
e.printStackTrace(); | |
} | |
@Override | |
public void onResponse(Call call, Response response) throws IOException { | |
try { | |
JSONArray data = new JSONArray(response.body().string()); | |
for (int i = 0; i < data.length(); i++) { | |
JSONObject obj = data.getJSONObject(i); | |
alumnus.add(new Person(obj.getString("id"),obj.getString("name"),obj.getString("email"),obj.getString("work"))); | |
} | |
runOnUiThread(new Runnable() { | |
@Override | |
public void run() { | |
mAdapter.notifyDataSetChanged(); | |
} | |
}); | |
} catch (JSONException e) { | |
e.printStackTrace(); | |
} | |
} | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment