I am trying to parse the user data using JSON. but my app keeps crashing .
This is the data that I display are
[Title, First Name, Last Name, location {street, city, state, and postcode} and email ]
this is the urls
"http://randomuser.me/api/?results=5&format=json"
This is my code
user class
public class User {
private String pic;
private String gender;
private String title;
private String first;
private String last ;
private String city;
private String street;
private String postcode;
private String email;}
MainActivity
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
private OkHttpClient httpClient;
private Request request;
TextView tv;
private String[] urls = {
"http://randomuser.me/api/?results=5&format=json"
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = findViewById(R.id.data_l);
httpClient = new OkHttpClient();
request = new Request.Builder()
.url(urls[0])
.build();
httpClient.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 {
if(response.isSuccessful())
{
final String dataa = response.body().string();
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
ArrayList<User> users = parseDataJSON(dataa) ;
tv.setText(dataa);
}
});
}
}
});
}
public ArrayList<User> parseDataJSON(String data) {
ArrayList<User> users = new ArrayList<>();
try {
JSONObject jsonObject = new JSONObject(data);
JSONArray usersArray = jsonObject.getJSONArray("results");
for (int i = 0; i < usersArray.length(); i++) {
User user = new User();
JSONObject userObject = usersArray.getJSONObject(i);
String gender = userObject.getString("gender");
user.setGender(gender);
JSONObject nameObject = userObject.getJSONObject("name");
user.setTitle(nameObject.getString("title"));
user.setFirst(nameObject.getString("first"));
user.setLast(nameObject.getString("last"));
JSONObject locationObject = userObject.getJSONObject("location");
user.setCity(locationObject.getString("city"));
user.setStreet(locationObject.getString("street"));
user.setStreet(locationObject.getString("state"));
String email = userObject.getString("email");
user.setEmail(email);
JSONObject pictureObject = userObject.getJSONObject("picture");
user.setPic(pictureObject.getString("large"));
users.add(user);
}
} catch (JSONException e) {
e.printStackTrace();
}
return users;
}
I already did the implementation.
As your Pojo has private properties (pic, gender, title, etc) then you need to include (in your POJO) public setters to set the data? (You'll also need getters too - in order to access the data)
e.g.
public void setPic(String pic) {
this.pic = pic;
}
Related
I have fetched JSON data from url using ION library, but I am facing problem in displaying it in a listView in android studio.
I debug it in this way:
JSONObject jsonObject = new JSONObject(String.valueOf(result));
JSONArray jsonArray = jsonObject.getJSONArray("contacts");
and here is the output for debug:
result = {JsonObject#5328} "{"id":2,"deptName":"PWD","logo":[],"contacts":[{"contactId":25,"empName":"Chill","designation":"Manager","mobile":"","landlineOffice":"23412388","landlineRes":"2334567","fax":"123445","email":"chunga#ymail.com"},{"contactId":27,"empName":"Cena","designation":"Wrestler","mobile":"98176253","landlineOffice":"2334531","landlineRes":"444568","fax":"","email":"cena#gmail.com"}]}"
result = {JsonObject#5328} "{"id":2,"deptName":"PWD","logo":[],"contacts":[{"contactId":25,"empName":"Chill","designation":"Manager","mobile":"","landlineOffice":"23412388","landlineRes":"2334567","fax":"123445","email":"chunga#ymail.com"},{"contactId":27,"empName":"Cena","designation":"Wrestler","mobile":"98176253","landlineOffice":"2334531","landlineRes":"444568","fax":"","email":"cena#gmail.com"}]}"
jsonObject = {JSONObject#5341} "{"id":2,"deptName":"PWD","logo":[],"contacts":[{"contactId":25,"empName":"Chill","designation":"Manager","mobile":"","landlineOffice":"23412388","landlineRes":"2334567","fax":"123445","email":"chunga#ymail.com"},{"contactId":27,"empName":"Cena","designation":"Wrestler","mobile":"98176253","landlineOffice":"2334531","landlineRes":"444568","fax":"","email":"cena#gmail.com"}]}"
id is an integer sent form first activity.The code for my activity is given below:
public class ContactsActivity extends AppCompatActivity {
ListView contactList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_contacts);
Intent intent = getIntent();
contactList = findViewById(R.id.contactList);
int dId = intent.getExtras().getInt("id");
String Sid = new String(String.valueOf(dId));
Context context = getApplicationContext();
Toast.makeText(context, "" + dId, Toast.LENGTH_SHORT).show();
try {
getContacts(Sid);
} catch (Exception e) {
e.printStackTrace();
}
}
public void getContacts(final String Sid) throws Exception {
class Contacts{
String empName;
String designation;
String mobile;
String landlineOffice;
String landlineRes;
String fax;
String email;
public Contacts(String designation, String mobile, String landlineOffice, String landlineRes, String fax, String email) {
this.designation = designation;
this.mobile = mobile;
this.landlineOffice = landlineOffice;
this.landlineRes = landlineRes;
this.fax = fax;
this.email = email;
}
}
Ion.with(this)
.load("http://10.180.243.19:8080/api/departments/" + Sid)
.asJsonObject()
.setCallback(new FutureCallback<JsonObject>() {
#Override
public void onCompleted(Exception e, JsonObject result) {
int id = Integer.parseInt(Sid);
try {
JSONObject jsonObject = new JSONObject(String.valueOf(result));
JSONArray jsonArray = jsonObject.getJSONArray("contacts");
} catch (JSONException e1) {
e1.printStackTrace();
}
}
});
}
}
I expect to display list of contact details of multiple employees in a listview.
I have Asp.net Api to get JSON response like this:
{\"UserID\":5,\"UserName\":\"asd\",\"Password\":\"asd\",\"Email\":\"ss#asd\",\"PhoneNumber\":\"1213\",\"Logtit\":0.0,\"Latitle\":0.0,\"OfGroup\":\"a \"}
How can I handle this JSON response in Android Studio Using Volley Lib?
This is my code:
public class MainActivity extends AppCompatActivity {
RequestQueue requestqueue;
Button start;
TextView textView;
EditText ee;
public String givenValue = ee.getText().toString();
public String URL = "http://localhost:61511:8010/api/Feedback/5" ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
requestqueue=Volley.newRequestQueue(this);
final Button start =(Button)findViewById(R.id.btnget);
final TextView textView =(TextView)findViewById(R.id.mTextView);
final EditText ee =(EditText)findViewById(R.id.idtxt) ;
start.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, URL, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("User");
for(int i= 0 ;i < jsonArray.length();i++){
JSONObject User = jsonArray.getJSONObject(i);
}
}catch (JSONException e ) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Volley", "ERROR");
}
}
);
requestqueue.add(jsonObjectRequest);}
});
}
Most probably you are getting a string respone. If its a string then firstly conver it to Json Object.. you can do this as following below.
JSONObject jsonObject=new JSONObject(response);
If it is JSONObject already then try to conver it to java object as following:
int userId=jsonObject.getInt("UserID");
String userName=jsonObject.getString("UserName");
String pass=jsonObject.getString("Password");
Put the code in your onResponse. and lastly seems like you are getting an array of object. Then create a POJO class like below:
public class UserData {
#Expose
#SerializedName("UserId")
private int userId;
#Expose
#SerializedName("UserName")
private String userName;
.
.
.
//add the extra attribute and create getter and setter
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
}
Then in declare in your code:
ArrayList<UserData>userDataList=new ArrayList();
Follow the below method to set data to arraylist with json data parsing
int userId=jsonObject.getInt("UserID");
String userName=jsonObject.getString("UserName");
String pass=jsonObject.getString("Password");
UserData userInfo=new UserData();
userInfo.setUserId(userId)
userIfo.setUserName(userName);
//add the other attribute similiarly
userDataList.add(userInfo);
You could parse it into a Map using GSON.
Please refer to this question and answer for more information.
I am trying to fetch data from the server and then display it into the app.
I have JSON data as,
{"COLUMNS":["TIMEID","BRANCHID","COMPANYID","MON_O","TUE_O","WED_O","THU_O","FRI_O","SAT_O","SUN_O","MON_C","TUE_C","WED_C","THU_C","FRI_C","SAT_C","SUN_C","CREATDATE"],"DATA":[[195,4,4,"09:00","09:00","09:00","09:00","09:00","Closed","Closed","16:30","16:30","16:30","16:30","16:30","Closed","Closed","May, 16 2017 08:16:12"]]}
When I access the url I get the complete JSON Data but when I am logging the same response from the server, I am not getting the DATA part of the JSON data.
My JAVA class implementation is as,
public static final String MON_O = "MON_O";
public static final String TUE_O = "TUE_O";
public static final String WED_O = "WED_O";
public static final String THU_O = "THU_O";
public static final String FRI_O = "FRI_O";
public static final String SAT_O = "SAT_O";
public static final String SUN_O = "SUN_O";
public static final String MON_C = "MON_C";
public static final String TUE_C = "TUE_C";
public static final String WED_C = "WED_C";
public static final String THU_C = "THU_C";
public static final String FRI_C = "FRI_C";
public static final String SAT_C = "SAT_C";
public static final String SUN_C = "SUN_C";
public static final String JSON_ARRAY = "COLUMNS";
private void getData() {
String url = context.getString(site_url)+"branch_time.cfc?method=branchtime&branchid=" +dBranchID;
StringRequest stringRequest = new StringRequest(url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
showJSON(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(context,error.getMessage().toString(),Toast.LENGTH_LONG).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(context);
requestQueue.add(stringRequest);
}
private void showJSON(String response) {
String name = "";
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray result = jsonObject.getJSONArray(JSON_ARRAY);
Log.d("TAG", result.toString());
name = result.getString(MON_O);
} catch (JSONException e) {
e.printStackTrace();
}
timeStatus.setText(name);
}
I am trying to log the result from the server and getting the below,
["TIMEID","BRANCHID","COMPANYID","MON_O","TUE_O","WED_O","THU_O","FRI_O","SAT_O","SUN_O","MON_C","TUE_C","WED_C","THU_C","FRI_C","SAT_C","SUN_C","CREATDATE"]
The DATA part of the response is null and I can get only the COLUMNS value.
I have no idea why this could happen. Please can anyone help in this?
Maybe it's null because you never did this to get that data correctly
JSONArray companyData = jsonObject.getJSONArray("DATA");
You only got the COLUMNS array, and the data is not within that array.
Also note that data array is an array within an array
Code use for COLUMNS will be:
JSONObject companyData = jsonObject.getJSONArray("COLUMNS");
Code use for DATA will be:
JSONObject companyData = jsonObject.getJSONArray("DATA ");
Please mark my answer useful, if you get you desired solution.
I have made a JSONParse class for parsing JSON response. I have to call 3 web services. But I want to use only that SINGLE class for parsing JSON response for all 3 web services. All 3 web services has different keys and values. What I have done is like below..
MainActivity.java
public class MainActivity extends AppCompatActivity implements AdapterView.OnItemClickListener {
// Anything Else Goes Here
private ArrayList<ModelCourse> ArrayListModelCourses;
// Variables
private String url = "stream.php";
private String career_path = "";
// Widgets
private ListView lv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
}
private void init() {
initialisation();
find_view_by_id();
clickListners();
fetchData();
}
private void initialisation() {
ArrayListModelCourses = new ArrayList<>();
}
private void find_view_by_id() {
lv = (ListView) findViewById(R.id.list_view);
}
private void clickListners() {
lv.setOnItemClickListener(this);
}
private void fetchData() {
StringRequest stringReq = new StringRequest(Request.Method.POST, Constants.base_url + url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jo = new JSONObject(response);
if (jo.has("success")) {
JsonParse jsonParse = new JsonParse(response);
ArrayListModelCourses = jsonParse.parseJson();
} else {
Toast.makeText(MainActivity.this, "Error msg from server!!", Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
CustomAdapter ca = new CustomAdapter(getApplicationContext(), ArrayListModelCourses);
lv.setAdapter(ca);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, "Error:" + error.getMessage(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("user_id", "51");
return params;
}
};
RequestQueue queue = Volley.newRequestQueue(this);
queue.add(stringReq);
}
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
String stream_name = ArrayListModelCourses.get(position).getmCourse_name();
String stream_id = ArrayListModelCourses.get(position).getmCourse_id();
career_path += stream_name + ", ";
fetchData();
}
}
JsonParse.java - The single class that I want to use for 3 web services.
public class JsonParse {
// Anything Else Goes Here
ArrayList<ModelCourse> modelCourses = new ArrayList<>();
// Variables
public static final String KEY_ARRAY = "stream_name";
public static final String KEY_ID = "stream_id";
public static final String KEY_NAME = "stream_name";
private String mJsonRes;
public JsonParse(String jsonRes) {
this.mJsonRes = jsonRes;
}
public ArrayList<ModelCourse> parseJson() throws JSONException {
JSONObject jo = new JSONObject(mJsonRes);
JSONArray ja = jo.getJSONArray(KEY_ARRAY);
for (int i = 0; i < ja.length(); i++) {
ModelCourse modelCourseObj = new ModelCourse();
JSONObject object = ja.getJSONObject(i);
modelCourseObj.mCourse_id = object.getString(KEY_ID);
modelCourseObj.mCourse_name = object.getString(KEY_NAME);
modelCourses.add(modelCourseObj);
}
return modelCourses;
}
}
Thanks in advance.
Use can use Gson for mapping json data to objects.
Create models classes for your json data. (use link http://www.jsonschema2pojo.org/)
Now in your MainActivity onResponse() method pass the string response to JsonParse class.
In JsonParse class parse your json data
Gson gson = new Gson();
gson.fromJson(jsonString, JsonModelRootClassName.class);
You can create one method to get "JsonModelRootClassName" based on your web services call.
I have created an Api which is used to add multiple invitations in the database called as sendMultipleInvites.
Now I want to implement this API in android. I am trying to create an AsyncTask to call the api. I have helper class to connect to http server.
I am testing this in postman: my input should be like this:
{
"invitations": [
{
"date" : "12/08/2016",
"invitee_no" : "196756456",
"status" : "1",
"user_name" : "user10"
},
{
"date" : "12/08/2016",
"invitee_no" : "13633469",
"status" : "1",
"user_id" : "user9"
}
]
}
My serverRequest class:
public class ServerRequest {
String api;
JSONObject jsonParams;
public ServerRequest(String api, JSONObject jsonParams) {
this.api = api;
this.jsonParams = jsonParams;
}
public JSONObject sendRequest() {
try {
URL url = new URL(api);
HttpURLConnection con = (HttpURLConnection)url.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type", "application/json");
con.setDoOutput(true);
con.setDoInput(true);
OutputStreamWriter writer = new OutputStreamWriter(con.getOutputStream());
writer.write(jsonParams.toString());
writer.close();
int responseCode = con.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
StringBuilder sb = new StringBuilder();
BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String line = "";
while ( (line = reader.readLine()) != null ){
sb.append(line);
}
reader.close();
Log.d("ServerResponse", new String(sb));
return new JSONObject(new String(sb));
} else {
throw new UnexpectedServerException("Unexpected server exception with status code : "+responseCode);
}
} catch (MalformedURLException me) {
me.printStackTrace();
return Excpetion2JSON.getJSON(me);
} catch(IOException ioe) {
ioe.printStackTrace();
return Excpetion2JSON.getJSON(ioe);
} catch(UnexpectedServerException ue) {
ue.printStackTrace();
return Excpetion2JSON.getJSON(ue);
} catch (JSONException je) {
je.printStackTrace();
return Excpetion2JSON.getJSON(je);
}
}
public ServerRequest(String api) {
this.api = api;
}
}
This is my asyncTask :
public class SendMultipleInvitesAsyncTask extends AsyncTask<Map<String, String>, Void, JSONObject> {
private Context context;
public SendInviteAsyncTask(Context context) {
this.context = context;
this.progressDialog = new ProgressDialog(context);
}
#Override
protected JSONObject doInBackground(Map<String, String>... params) {
try {
String api = context.getResources().getString(R.string.server_url) + "contactsapi/sendInvite.php";
Map2JSON mjs = new Map2JSON();
JSONObject jsonParams = mjs.getJSON(params[0]);
ServerRequest request = new ServerRequest(api, jsonParams);
return request.sendRequest();
} catch (JSONException je) {
return Excpetion2JSON.getJSON(je);
}
}
#Override
protected void onPostExecute(JSONObject jsonObject) {
super.onPostExecute(jsonObject);
Log.d("ServerResponse", jsonObject.toString());
try {
int result = jsonObject.getInt("status");
String message = jsonObject.getString("message");
if (result == 1) {
//Code for having successful result for register api goes here
} else {
Toast.makeText(context, message, Toast.LENGTH_LONG).show();
}
} catch (JSONException je) {
je.printStackTrace();
Toast.makeText(context, je.getMessage(), Toast.LENGTH_LONG).show();
}
}
}
Edit:
Trying like this it is giving an error when I try to pass an arraylist to the execute method of async task.
AsyncTask:
public class SendInviteAsyncTask extends AsyncTask<ArrayList<Invitation>, Void, JSONObject> {
private ProgressDialog progressDialog;
private Context context;
public SendInviteAsyncTask(Context context) {
this.context = context;
this.progressDialog = new ProgressDialog(context);
}
#Override
protected JSONObject doInBackground(ArrayList<Invitation>... arrayLists) {
try {
String api = context.getResources().getString(R.string.server_url) + "contactsapi/sendInvite.php";
ServerRequest request = new ServerRequest(api, jsonParams);
return request.sendRequest();
} catch (JSONException je) {
return Excpetion2JSON.getJSON(je);
}
}
Activity:
public class SendMultipleInvites extends AppCompatActivity {
private ArrayList<Invitation> invitationArrayList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_send_multiple_invites);
invitationArrayList = new ArrayList<>();
Invitation invitation = new Invitation("3","17/02/2016","55165122","1","user10");
invitationArrayList.add(invitation);
invitation = new Invitation("3","17/02/2016","282751221","1","user10");
invitationArrayList.add(invitation);
new SendMultipleInvitesAsyncTask(SendMultipleInvites.this).execute(invitationArrayList);
}
}
I was using hash map to send key and values. How can I do to send a json array?
How to modify my async Task? How can I send array to an async task? Can anyone help please.. Thank you..
To pass Array to your async Task do this:
SendInviteAsyncTask extends AsyncTask<ArrayList<Sring>, Void, JSONObject>
To make a Json object you can use Gson library
try this
JSONObject obj = new JSONObject();
JSONArray req = new JSONArray();
JSONObject reqObj = new JSONObject()
reqObj.put( "ctrlId", "txt1" );
req.put( reqObj );
reqObj = new JSONObject();
reqObj.put( "ctrlId", "txt2" );
req.put( reqObj );
obj.put( "req", req );
You can really simplify your code by using a few libraries for building json and sending http requests. Here is sample code using Gson for building the json string and Volley for the http request.
I also used this fantastic project for generating the json pojo objects below. It makes really quick work of it.
Invite ivt = new Invite();
ivt.getInvitations().add( new Invitation("3","17/02/2016","55165122","1","user10"));
ivt.getInvitations().add( new Invitation("3","17/02/2016","282751221","1","user10"));
Gson gson = new Gson();
String jsonString = gson.toJson(ivt);
String url = appContext.getResources().getString(R.string.server_url) + "contactsapi/sendInvite.php";
RequestQueue queue = Volley.newRequestQueue(appContext);
StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("TAG", "success: " + response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
queue.add(stringRequest);
Invite.java
public class Invite {
#SerializedName("invitations")
#Expose
private List<Invitation> invitations = new ArrayList<Invitation>();
public List<Invitation> getInvitations() {
return invitations;
}
public void setInvitations(List<Invitation> invitations) {
this.invitations = invitations;
}
}
Invitation.java
public class Invitation {
#SerializedName("date")
#Expose
private String date;
#SerializedName("invitee_no")
#Expose
private String inviteeNo;
#SerializedName("status")
#Expose
private String status;
#SerializedName("user_name")
#Expose
private String userName;
#SerializedName("user_id")
#Expose
private String userId;
public Invitation(String d, String one, String two, String three, String four) {
date = d;
inviteeNo = one;
status = two;
userName = three;
userId = four;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getInviteeNo() {
return inviteeNo;
}
public void setInviteeNo(String inviteeNo) {
this.inviteeNo = inviteeNo;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
}