Hello world, today I am gonna share about get data from the JSON. In this case I will use volley library for make easy develop, when i get data from JSON. Actually this is test for myself, to remain me about android code. And this is my list :
1. A Activity have one button, two edit text.
2. When your click button will move to another activity, I call it Activity B, Activity B will show list data from JSON.
3. When you click your list, it will will be back to Activity B with fill two EditText.
4. Just it.
Hoya, in this tutorial i use JSON from androidhive. You can check here. He share about JSON too but in this post i will make it complete :D.
Now you follow my step by step :
1. Activity A
In this Activity A I just put One Button and with Two EditText this is my activity_main.xml file :
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" > <Button android:id="@+id/btnArrayRequest" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_marginTop="50dp" android:paddingLeft="15dp" android:paddingRight="15dp" android:text="Pick Doctor" /> <EditText android:id="@+id/ETCode" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_marginTop="50dp" android:paddingLeft="15dp" android:paddingRight="15dp" android:layout_below="@id/btnArrayRequest" /> <EditText android:id="@+id/ETName" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_marginTop="50dp" android:paddingLeft="15dp" android:paddingRight="15dp" android:layout_below="@id/ETCode" /> </RelativeLayout>
and this is my MainActivity.java file :
See on my first list, function button its for move to Activity B. You can see on this code :
public class MainActivity extends Activity { private static String TAG = MainActivity.class.getSimpleName(); private Button btnMakeArrayRequest; private EditText ETCOde; private EditText ETName; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); btnMakeArrayRequest = (Button) findViewById(R.id.btnArrayRequest); ETCOde = (EditText)findViewById(R.id.ETCode); ETCOde.setEnabled(false); ETName = (EditText)findViewById(R.id.ETName); ETName.setEnabled(false); btnMakeArrayRequest.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(MainActivity.this, MainActivityList.class); startActivity(intent); } }); if (getIntent() != null){ if (getIntent().hasExtra("Code")) { ETCOde.setText(getIntent().getStringExtra("Code"), TextView.BufferType.EDITABLE); } if (getIntent().hasExtra("Name")) { ETName.setText(getIntent().getStringExtra("Name"), TextView.BufferType.EDITABLE); } } } }
See on my first list, function button its for move to Activity B. You can see on this code :
btnMakeArrayRequest.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(MainActivity.this, MainActivityList.class); startActivity(intent); } });
And then as you can see in the third my list it must fill data from list Activity B. I just use this code:
if (getIntent() != null){ if (getIntent().hasExtra("Code")) { ETCOde.setText(getIntent().getStringExtra("Code"), TextView.BufferType.EDITABLE); } if (getIntent().hasExtra("Name")) { ETName.setText(getIntent().getStringExtra("Name"), TextView.BufferType.EDITABLE); } }
This condition for detection if this activity get intent for another activity.
2. Activity B
Remember in this activity it's our main point. We will show data from JSON and will be show on list activity. So this is my activity_main_list.xml and list_item.xml file.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" > <ListView android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/list" /> </RelativeLayout>
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <TextView android:layout_width="wrap_content" android:layout_height="50dp" android:id="@+id/name" android:layout_alignParentStart="true" android:gravity="center_vertical" android:paddingStart="10dp" /> <TextView android:layout_width="wrap_content" android:layout_height="50dp" android:id="@+id/code" android:gravity="center_vertical" android:layout_alignParentEnd="true" android:paddingEnd="10dp" /> </RelativeLayout>
In this xml file list we need to add item list for set list in xml file list. I mean element list have item list.
So this is my MainActivityList.java file in Activity B
public class MainActivityList extends Activity{ public ListView list; public ArrayList doc = new ArrayList(); public ListAdapter adapter; private String urlJsonArry = "http://192.168.88.10/api/medikav1/specialization"; private static String TAG = MainActivity.class.getSimpleName(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main_list); makeJsonArrayRequest(); list = (ListView) findViewById(R.id.list); adapter = new ListAdapter(this); list.setAdapter(adapter); list.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView parent, View view, int position, long id) { Intent intent = new Intent(MainActivityList.this, MainActivity.class); intent.putExtra("Code", doc.get(position).name); intent.putExtra("Name", doc.get(position).code); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); startActivity(intent); } }); } private void makeJsonArrayRequest() { JsonArrayRequest req = new JsonArrayRequest(urlJsonArry, new Response.Listener() { @Override public void onResponse(JSONArray response) { Log.d(TAG, response.toString()); try { for (int i = 0; i < response.length(); i++) { JSONObject person = (JSONObject) response.get(i); Model add=new Model(); add.name = person.getString("SpecializationID"); add.code = person.getString("SpecializationName"); doc.add(add); } } catch (JSONException e) { e.printStackTrace(); Toast.makeText(getApplicationContext(), "Error: " + e.getMessage(), Toast.LENGTH_LONG).show(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { VolleyLog.d(TAG, "Error: " + error.getMessage()); Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show(); } }); AppController.getInstance().addToRequestQueue(req); } }
The point of this activity is i create function for get data from Json. This is my function.
private void makeJsonArrayRequest() { JsonArrayRequest req = new JsonArrayRequest(urlJsonArry, new Response.Listener() { @Override public void onResponse(JSONArray response) { Log.d(TAG, response.toString()); try { for (int i = 0; i < response.length(); i++) { JSONObject person = (JSONObject) response.get(i); Model add=new Model(); add.name = person.getString("SpecializationID"); add.code = person.getString("SpecializationName"); doc.add(add); } } catch (JSONException e) { e.printStackTrace(); Toast.makeText(getApplicationContext(), "Error: " + e.getMessage(), Toast.LENGTH_LONG).show(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { VolleyLog.d(TAG, "Error: " + error.getMessage()); Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show(); } }); AppController.getInstance().addToRequestQueue(req); }
As you can see I use volley for get data Json with parameter urlJsonArry.
JsonArrayRequest req = new JsonArrayRequest(urlJsonArry, new Response.Listener() String urlJsonArry = "http://api.androidhive.info/volley/person_array.json"
.As i told you before, i use JSON data from android hive, you can check here. You can goto link JSON, If you want see, it would be like this.
[ { "name" : "Ravi Tamada", "email" : "ravi8x@gmail.com", "phone" : { "home" : "08947 000000", "mobile" : "9999999999" } }, { "name" : "Tommy", "email" : "tommy@gmail.com", "phone" : { "home" : "08946 000000", "mobile" : "0000000000" } } ]
You can see I am do looping and set data to my model class. And then I do add to array list with type data model. After that you can see when i set array list into list xml with this code. This is in my ListAdapter.java file.
public class ListAdapter extends BaseAdapter { MainActivityList main; ListAdapter(MainActivityList main) { this.main = main; } @Override public int getCount() { return main.doc.size(); } @Override public Object getItem(int position) { return null; } @Override public long getItemId(int position) { return 0; } static class ViewHolderItem { TextView name; TextView code; } @Override public View getView(int position, View convertView, ViewGroup parent){ ViewHolderItem holder = new ViewHolderItem(); if (convertView == null) { LayoutInflater inflater = (LayoutInflater) main.getSystemService(Context.LAYOUT_INFLATER_SERVICE); convertView = inflater.inflate(R.layout.list_item, null); holder.name = (TextView) convertView.findViewById(R.id.name); holder.code = (TextView) convertView.findViewById(R.id.code); convertView.setTag(holder); } else { holder = (ViewHolderItem) convertView.getTag(); } holder.name.setText(this.main.doc.get(position).name); holder.code.setText(this.main.doc.get(position).code); return convertView; } }
after adapter have value, this adapter will be add to list :
adapter = new ListAdapter(this); list.setAdapter(adapter);
And the last remember my third list. List will move back to activity A, with fill 2 EditText. I just use this code.
list.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView parent, View view, int position, long id) { Intent intent = new Intent(MainActivityList.this, MainActivity.class); intent.putExtra("Code", doc.get(position).name); intent.putExtra("Name", doc.get(position).code); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); startActivity(intent); } });
As you can see, I just use intent and bring data from array list with position. Then with the array list type data model I just add .name or .code it's a getter from model class. Uha
The conclusion is if you have text like this, you can make plan one by one. Like my plan is button click, get data Json, set data Json to list, and onclick list. Hoya you can also download to my GitHub repository with click link below.
GitHub
GitHub
Great blog! Thank you for sharing. Keep posting.
ReplyDeleteMobile app development company Gurgaon
hire mobile app developer
This comment has been removed by the author.
ReplyDeleteAwesome. Greatly portrayed your thoughts in your blog writing. Please keep continuing. Thanks for sharing.
ReplyDeleteNow, let's move on to Maven Technology, as the Best Mobile App Developers in India. We ensure the digital potential of your aesthetic mobile app integrations - Your Gateway to Unparalleled Success!
Try us now.
Great insights on extracting data from JSON for Android lists! For those interested in broader data solutions, partnering with an Odoo development company can streamline your projects.
ReplyDelete