Handling a JSON Response - android

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.

Related

Parse the user data using JSON

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;
}

how to get userid and user name into spinnenr and send userid to server

I have json response like:
{
"Users":[
{
"username":"Varun",
"userid":"626"
}
]
}
I want to add a user in spinner and as well as get userid to pass to the server here my code.
spinnerUser=new ArrayList<>();
//spinnerUser=new ArrayList<>();
//display first question to the user
try {
JSONArray jsonArray = (JSONArray) response.get("Users");
for (int i=0;i<jsonArray.length();i++)
{
JSONObject json=jsonArray.getJSONObject(i);
{
/*User userData=new User();
userData.setUsername(json.optString("username"));
userData.setUserid(json.optString("userid"));
jsonSpinner.add(userData);
spinnerUser.add(json.optString("username"));*/
String name = json.optString("username").toString();
userid=json.optString("userId").toString();
spinnerUser.add(name);
}
}
}catch (Exception e)
{
e.printStackTrace();
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getContext(),
R.layout.simple_spinner_item, spinnerUser);
adapter.setDropDownViewResource(R.layout.simple_spinner_item);
user.setAdapter(adapter);
How can I achieve that.any help regarding on that please suggest me.
First create a POJO class User
public class User {
private String name;
private String userId;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
#Override
public String toString() {
return name;
}
}
Then change your code below
List<User> userList = new ArrayList<>();
spinnerUser = new ArrayList<>();
//display first question to the user
try {
JSONArray jsonArray = (JSONArray) response.get("Users");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject json = jsonArray.getJSONObject(i);
String name = json.optString("username").toString();
String userid = json.optString("userid").toString();
User user = new User();
user.setName(name);
user.setUserId(userid);
userList.add(user);
}
} catch (Exception e) {
e.printStackTrace();
}
ArrayAdapter<User> adapter = new ArrayAdapter<User>(getContext(), R.layout.simple_spinner_item, userList);
adapter.setDropDownViewResource(R.layout.simple_spinner_item);
user.setAdapter(adapter);
for accessing selected spinner item.
try below code
User selectedUser=(User) user.getSelectedItem();
Log.e("user Name", selectedUser.getName());
Log.e("user id", selectedUser.getuserId());
Try this:
Store value and key in HashMap
private HashMap<String, String> hmapcat = new HashMap<>();
String name = json.optString("username").toString();
String userid=json.optString("userId").toString();
hmapcat.put(name,userid);
Then Onclick of Spinner you will get ID, try below logic.
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
String items = spinner.getSelectedItem().toString();
Log.i("Selected item : ", items);
String id1=hmapcat.get(items ); // here you will get ids
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
I hope this will help you
"I" in userid is small in json object.
userid=json.optString("userid").toString();
public class User()
{
#SerializedName("userid")
private String userid;
#SerializedName("userName")
private String userName;
//define getter setter
}
User Gson to get of List.
How to parse json parsing Using GSON in android

cannot find symbol method getJSONArray(String) Volley

hi everyone i am working on a android project where i have to retrive the data form JSON. here is my link
I am trying to get the data using the below code
public class DisplayUser extends AppCompatActivity {
private TextView textViewResult;
private ProgressDialog loading;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_user);
textViewResult = (TextView) findViewById(R.id.check_data_id); // in this text view i will display the text
loading = ProgressDialog.show(this,"Please wait...","Fetching...",false,false);
String url = statics_demo.USER_URL+"7";// this is fixed url where i am getting the data
StringRequest stringRequest = new StringRequest(url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
loading.dismiss();
showJSON(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(DisplayUser.this,error.getMessage().toString(),Toast.LENGTH_LONG).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
JSONObject result;
private void showJSON(String response) {
try {
JSONArray obj = response.getJSONArray("responseMs");
for (int i = 0; i < obj.length(); i++) {
JSONObject jsonObject = obj.getJSONObject(i);
String name = jsonObject.getString("name");
System.out.println("luckyyyyyy"+name);
// String type = jsonObject.getString("type");
// retrieve the values like this so on..
}
}
catch (JSONException e) {
e.printStackTrace();
}
}
}
When i run the code i am getting a erorr saying
"Error:(60, 37) error: cannot find symbol method getJSONArray(String)"
String s = "[]"; JsonParser parser = new JsonParser(); JsonElement tradeElement = parser.parse(s); JsonArray trade = tradeElement.getAsJsonArray();
you need to convert string to jsonarray first

Android - Same JSON parsing class for different web services

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.

Android Facebook Response parsing

{Response: responseCode: 200, graphObject: {"id":"98374978103","birthday":"04\/19\/1991","gender":"male","email":"email#gmail.com","name":"Wasfasf"}, error: null}
I am getting facebook response as above string
How to parse this string.
I am doing it this way
try {
String res = response.toString();
JSONObject obj = new JSONObject(res);
JSONArray arr = obj.optJSONArray("graphObject");
for(int i=0; i < arr.length(); i++) {
JSONObject jsonObject = arr.getJSONObject(i);
String id = jsonObject.optString("id").toString();
String bday = jsonObject.optString("birthday").toString();
String gender = jsonObject.optString("gender").toString();
String email = jsonObject.optString("email").toString();
String name = jsonObject.optString("name").toString();
}
} catch (Exception e) {
e.printStackTrace();
}
It throws the exception :
Unterminated object at character 25 of {Response: responseCode: 200, graphObject: {"id":"983797084978103","birthday":"04\/19\/1991","gender":"male","email":"waleedbinilyas#gmail.com","name":"Waleed Bin Ilyas"}, error: null}
I have done in this way and works fine perfectly
public class SignIn extends AppCompatActivity {
CallbackManager callbackManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//before set conteview
FacebookSdk.sdkInitialize(getApplicationContext());
// AppEventsLogger.activateApp(this);
callbackManager = CallbackManager.Factory.create();
setContentView(R.layout.activity_signin);
LoginButton loginButton = (LoginButton) findViewById(R.id.login_button);
loginButton.setReadPermissions(Arrays.asList("public_profile", "email"));
loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
GraphRequest graphRequest=GraphRequest.newMeRequest(loginResult.getAccessToken(), new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject jsonObject, GraphResponse graphResponse) {
Log.d("Graph Response",graphResponse.toString());
String myCustomizedResponse = graphResponse.getJSONObject().toString();
Log.d("Ketan_Ramani",graphResponse.getJSONObject().toString());
try {
JSONObject obj = new JSONObject(myCustomizedResponse);
String id = obj.getString("id");
String first_name = obj.getString("first_name");
String last_name = obj.getString("last_name");
String email = obj.getString("email");
Log.d("Id",id);
Log.d("FirstName",first_name);
Log.d("LastName",last_name);
Log.d("Email",email);
} catch (JSONException e) {
Utils.hide_dialog();
e.printStackTrace();
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,first_name,last_name,email");
graphRequest.setParameters(parameters);
graphRequest.executeAsync();
}
#Override
public void onCancel() {
// App code
}
#Override
public void onError(FacebookException exception) {
// App code
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
}
}
I think this would work for you.
try {
String res = response.toString();
JSONObject obj = new JSONObject(res);
JSONArray arr = obj.getJSONArray("graphObject");
for(int i=0; i < arr.length(); i++) {
JSONObject jsonObject = arr.getJSONObject(i);
String id = jsonObject.getString("id").toString();
String bday = jsonObject.getString("birthday").toString();
String gender = jsonObject.getString("gender").toString();
String email = jsonObject.getString("email").toString();
String name = jsonObject.getString("name").toString();
}
}
catch (Exception e) {
e.printStackTrace();
}
Note : I have not tested this code.
The given json is invalid,you can use jsonLint to validte your json Feed
assuming feed below the correct feed
{
"Response": {
"responseCode": 200,
"graphObject": {
"id": "983797088103",
"birthday": "04/19/1991",
"gender": "male",
"email": "email#wamil",
"name": "name"
},
" error": null
}
}
If you are using an IDE like intellij/Android studio use the plugin like Dtonator to generate the Gson DTO's,which will look like this
public class FaceBookResponse {
#SerializedName("Response")
public Response Response;
public static class GraphObject {
#SerializedName("birthday")
public String birthday;
#SerializedName("gender")
public String gender;
#SerializedName("name")
public String name;
#SerializedName("id")
public String id;
#SerializedName("email")
public String email;
}
public static class Response {
#SerializedName("error")
public String error;
#SerializedName("graphObject")
public GraphObject graphObject;
#SerializedName("responseCode")
public int responseCode;
}
}
Now you can simply parse your feed using the below two lines.
private final Gson gson = new Gson();
FaceBookResponse response=mGson.fromJson(json, mClazz);
If you want get a object like graphObject do this:
JSONObject jObj = new JSONObject([jsonString]);
ArrayList<SomeClass> listObj = jObj.getJSONArray("graphObject");
if (listObj.length() != 0){
for (int i = 0; i < listObj.length(); i++) {
JSONObject c = listObj.getJSONObject(i);
c.getString("name");
c.getString("gender");
.
.
.
}
}
Edit: SomeClass = Same Fields that you have in your jsonĀ“s fields, in this case: id,birthday,gender,email,name.
I did it in this way
try {
String id = object.getString("id");
String uname = object.getString("name");
String emailid = object.getString("email");
String gender = object.getString("gender");
String bday = object.getString("birthday");
} catch (Exception e) {
e.printStackTrace();
}
Graph object is an object not array.
public void onCompleted(JSONObject facebookResponseObject, GraphResponse response) {
// Application code
// Log.v("LoginActivity", response.toString());
Log.v("facebook_response", facebookResponseObject.toString());
}}
You are converting response object of type GraphResponse and then doing operations on it.
Instead do this:facebookResponseObject.toString() and then you can easily do this --> Log.e("facebook_response_id",id);

Categories

Resources