How to parse two string into one textview - android

I want my TextView contain 2 String of JSON data.
example.json
{
"volumeInfo": {
"title": "Computer Architecture",
"subTitle": "A Quantitative Approach"
}
So, from that JSON i want my TextView to be: Computer Architecture: A Quantitative Approach. How should i do? Thanks.
I only want using one TextView

Just do it
String title = "Computer Architecture";
String subtitle = "A Quantitative Approach";
TextView.setText(title + ": " + subtitle);

You can concatenate Strings and then set it to TextView like below:
String title = "Computer Architecture";
String subtitle = "A Quantitative Approach";
yourTextView.setText(title + "," + subtitle);

//Please check the below code will help you as you want to set the text.
String response = "{" +
" \"volumeInfo\": {" +
" \"title\": \"Computer Architecture\"," +
" \"subTitle\": \"A Quantitative Approach\"}" +
"}";
try {
String title = "", subTitle = "";
JSONObject jsonObject = new JSONObject(response);
if (jsonObject.has("volumeInfo")) {
JSONObject jsonObject1 = jsonObject.getJSONObject("volumeInfo");
if (jsonObject1.has("title")) {
title = jsonObject1.getString("title");
}
if (jsonObject1.has("subTitle")) {
subTitle = jsonObject1.getString("subTitle");
}
String combineString = title + ": " + subTitle;
TextView textView = findViewById(R.id.textView);
textView.setText(combineString);
}
} catch (JSONException e) {
e.printStackTrace();
}

Related

How to get data from key of a JSON [duplicate]

This question already has answers here:
How to iterate over a JSONObject?
(15 answers)
Closed 5 years ago.
I am creating an app in which i need to parse a list of contacts which is in JSONObject format, with key before each object, i don't know how to parse this format.
{
"1": {
"mobileContact": "98562325",
"systemContact": "9198562325"
},
"3": {
"mobileContact": "987563656",
"systemContact": "91987563656"
},
"4": {
"mobileContact": "965632525",
"systemContact": "91965632525"
},
"6": {
"mobileContact": "965436222",
"systemContact": "91965436222"
}
}
Use the keys() iterator to iterate over all the properties, and call get() for each.
Iterator<String> iter = json.keys();
while (iter.hasNext()) {
String key = iter.next();
try {
Object value = json.get(key);
} catch (JSONException e) {
// Something went wrong!
}
}
try{
JSONObject json = new JSONObject(jsonRespondeString);
Iterator<String> iterator = json.keys();
while (iterator.hasNext()){
String key = iterator.next();
JSONObject object = json.getJSONObject(key);
String value1 = object.getString("key1");
String value2 = object.getString("key2");
}
}
catch (JSONException e){
e.printStackTrace();
}
please try this it helps
You can use GSON library to parse it.
String data = "{\n" +
" \"1\": {\n" +
" \"mobileContact\": \"98562325\",\n" +
" \"systemContact\": \"9198562325\"\n" +
" },\n" +
" \"3\": {\n" +
" \"mobileContact\": \"987563656\",\n" +
" \"systemContact\": \"91987563656\"\n" +
" },\n" +
" \"4\": {\n" +
" \"mobileContact\": \"965632525\",\n" +
" \"systemContact\": \"91965632525\"\n" +
" },\n" +
" \"6\": {\n" +
" \"mobileContact\": \"965436222\",\n" +
" \"systemContact\": \"91965436222\"\n" +
" }\n" +
"}";
Map<String, Item> itemMap = new HashMap<>();
itemMap = new Gson().fromJson(data, itemMap.getClass());
Log.i("data", itemMap);
Item Class
private class Item {
String mobileContact;
String systemContact;
// getters and setters
public String getMobileContact() {
return mobileContact;
}
public void setMobileContact(String mobileContact) {
this.mobileContact = mobileContact;
}
public String getSystemContact() {
return systemContact;
}
public void setSystemContact(String systemContact) {
this.systemContact = systemContact;
}
}
You need to add the following to the build.gradle file,
compile 'com.google.code.gson:gson:2.8.0'

How to display data?

I am using this method to call my service in my application.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.next);
String url = "url";
AQuery mAQuery = new AQuery(Next.this);
mAQuery.ajax(url, String.class, new AjaxCallback<String>() {
#Override
public void callback(String url, String data, AjaxStatus status) {
super.callback(url, data, status);
if (BuildConfig.DEBUG) {
Log.d("###$Request URL", url + "");
Log.d("###$Response ", data + "");
Log.d("###$Status Message : ", status.getMessage() + "");
Log.d("###$Status Code : ", status.getCode() + "");
}
if (null != data && status.getCode() != -101) {
String StringData = "" + data;
try {
JSONObject json = new JSONObject(StringData);
String COMP_REQ_ID = json.getString("COMP_REQ_ID");
String CompanyName = json.getString("CompanyName");
String COMP_REQ_TYPE = json.getString("COMP_REQ_TYPE");
String Name = json.getString("Name ");
myAwesomeTextview.setText("COMP_REQ_ID: " + COMP_REQ_ID + "\n" + "CompanyName:" + CompanyName + "\n" + "COMP_REQ_TYPE: " + COMP_REQ_TYPE + "\n" + "Name : " + Name);
} catch (JSONException e) {
myAwesomeTextview.setText("" + e);
}
But the data coming from server is not getting display on my phone screen.
The data i got from my service is given below:
[{"Name":null,"PositionName":null,"DateOfEvent":null,"EvetnId":0,"HetId":0,"EventDate":null,"COMP_REQ_ID":9714,"COMP_REQ_TYPE":"Intership","JobTitle":"Administrator","CompanyName":"Jensor's International (Ltd).","ReqQualification":"","DegreeName":"B.E/B.Tech,M.C.A,M.B.A,B.A,B.A.M.S,B.Com,B.S.W","Post_Status":1,"Eventdate":"21/06/2016","JobsOrInternships":null},{"Name":null,"PositionName":null,"DateOfEvent":null,"EvetnId":0,"HetId":0,"EventDate":null,"COMP_REQ_ID":9713,"COMP_REQ_TYPE":"Intership","JobTitle":"junior counselor","CompanyName":"Jensor's International (Ltd).","ReqQualification":"","DegreeName":"B.E/B.Tech,M.C.A,M.B.A,B.B.M,B.Com,B.F.A","Post_Status":1,"Eventdate":"21/06/2016","JobsOrInternships":null}
How to display it.
You should use JSONArray to parse your result
JSONArray rootArray = new JSONArray(jsonString);
int len = rootArray.length();
for(int i = 0; i < len; ++i) {
JSONObject json = rootArray.getJSONObject(i);
String COMP_REQ_ID = json.getString("COMP_REQ_ID");
}
Or you can use GSon library to parse the result for you. I recommend this post as example how to query data from ASP.NET Web API.
I think you should make your question clear because I'm not sure if you have problem with getting data or showing data to ui.
public class ArrayBean {
public String Name;
public String PositionName;
public String DateOfEvent;
public String EvetnId;
public String HetId;
public String EventDate;
public String COMP_REQ_ID;
public String COMP_REQ_TYPE;
public String JobTitle;
public String CompanyName;
public String ReqQualification;
public String DegreeName;
public String Eventdate;
public String JobsOrInternships;
}
ArrayBean bean;
JSONArray array=new JSONArray("StringData ");
JSONObject json;
for(int i=0;i<array.length();i++){
bean=new ArrayBean();
json=new JSONObject();
json=array.getJSONObject(i);
bean.COMP_REQ_ID=json.getString("COMP_REQ_ID");
bean.COMP_REQ_TYPE=json.getString("COMP_REQ_TYPE");
bean.CompanyName=json.getString("CompanyName");
bean.DateOfEvent=json.getString("DateOfEvent");
bean.EventDate=json.getString("EventDate");
bean.EvetnId=json.getString("EvetnId");
bean.HetId=json.getString("HetId");
bean.JobsOrInternships=json.getString("JobsOrInternships");
bean.JobTitle=json.getString("JobTitle");
bean.Name=json.getString("Name");
bean.PositionName=json.getString("PositionName");
bean.ReqQualification=json.getString("ReqQualification");
}
Note, care about data-types in JSON e.g key COMP_REQ_ID has value data-type is int. You should use optString or optInt instead of getString or getInt to parse your result
JSONArray rootArray = new JSONArray(jsonString);
int len = rootArray.length();
for(int i = 0; i < len; ++i) {
JSONObject json = rootArray.optJSONObject(i);
int COMP_REQ_ID = json.optInt("COMP_REQ_ID");
String COMP_REQ_TYPE = json.optString("COMP_REQ_TYPE");
...
}
i used this code
JSONArray rootArray = new JSONArray(StringData);
int len = rootArray.length();
for (int i = 0; i < len; ++i) {
JSONObject json = rootArray.optJSONObject(i);
int COMP_REQ_ID = json.optInt("COMP_REQ_ID");
String COMP_REQ_TYPE = json.optString("COMP_REQ_TYPE");
String CompanyName = json.getString("CompanyName ");
String Name = json.getString("Name");
String PositionName = json.getString("PositionName");
myAwesomeTextview.setText("COMP_REQ_ID:" + COMP_REQ_ID + "\n" + "COMP_REQ_TYPE" + COMP_REQ_TYPE + "\n" + "CompanyName" + CompanyName + "\n" + "Name" + Name + "\n" + "PostionNmae" + PositionName);
}
But then also the result is not diplayed on my phone And in android studio logcat it showing me this:
reporting:java.lang.NullPointerException at com.example.anand.Next$1.callback(Next.java:55)
at com.example.anand.Next$1.callback(Next.java:24)
at

JSON parsing to List view with multiple objects Android [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
Need Help
I have Json through which i have to retrieve objects but unable to retrieve.
I have used multiple objects also to retrieve but no success.
JSON:
{
"status": 1,
"data": [{
"restaurent_id": "1",
"user_id": "6",
"zone_id": "1",
"restaurentAddress": {
"restaurent_address_id": "1"
},
"restaurentInfo": {
"restaurent_info_id": "1",
"restaurent_bussiness_owner_name": "Vijay"
},
"restaurentSetting": {
"restaurent_setting_id": "1",
"minimum_purcase": "200",
"payment_method_id": "1",
"title": "Best Hotel"
},
"zone": {
"zone_id": "1",
"by_zipcode": "1"
}
}]
}
and i want to fetch restaurentAddress and restaurentInfo
MY mainActivity.java file
package com.example.premi.jsonlist;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class MainActivity extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView output = (TextView) findViewById(R.id.textView1);
String strJson="{\n" +
"\t\"status\": 1,\n" +
"\t\"data\": [{\n" +
"\t\t\"restaurent_id\": \"1\",\n" +
"\t\t\"user_id\": \"6\",\n" +
"\t\t\"zone_id\": \"1\",\n" +
"\t\t\"restaurentAddress\": {\n" +
"\t\t\t\"restaurent_address_id\": \"1\"\n" +
"\t\t},\n" +
"\t\t\"restaurentInfo\": {\n" +
"\t\t\t\"restaurent_info_id\": \"1\",\n" +
"\t\t\t\"restaurent_bussiness_owner_name\": \"Vijay\"\n" +
"\t\t},\n" +
"\t\t\"restaurentSetting\": {\n" +
"\t\t\t\"restaurent_setting_id\": \"1\",\n" +
"\t\t\t\"minimum_purcase\": \"200\",\n" +
"\t\t\t\"payment_method_id\": \"1\",\n" +
"\t\t\t\"title\": \"Best Hotel\"\n" +
"\t\t},\n" +
"\t\t\"zone\": {\n" +
"\t\t\t\"zone_id\": \"1\",\n" +
"\t\t\t\"by_zipcode\": \"1\"\n" +
"\t\t}\n" +
"\n" +
"\t}]\n" +
"}";
String dataoutput = "";
try {
JSONObject jsonRootObject = new JSONObject(strJson);
//Get the instance of JSONArray that contains JSONObjects
JSONObject status = jsonRootObject.optJSONObject("status");
JSONArray Dataarray =status.getJSONArray("data");
//Iterate the jsonArray and print the info of JSONObjects
for(int i=0; i < Dataarray.length(); i++){
JSONObject jsonObject = Dataarray.getJSONObject(i);
JSONObject Data = jsonObject.getJSONObject("restaurentAddress");
for(int j = 0 ; j < Data.length(); j++){
JSONObject GetData =Data.getJSONObject(String.valueOf(j));
int id = Integer.parseInt(GetData.getString("restaurent_address_id"));
String postcode = GetData.getString("postcode");
String addresss = GetData.getString("restaurent_address");
dataoutput += " : \n id= "+ id +" \n postcode= "+ postcode +" \n address= "+ addresss +" \n ";
}}
output.setText(dataoutput);
} catch (JSONException e) {e.printStackTrace();}
}
}
Try this out:
try {
JSONObject object = (JSONObject) new JSONTokener(YOUR_JSON_STRING).nextValue();
String restaurentAddressId = object.getJSONArray("data").getJSONObject(0).getJSONObject("restaurentAddress").getString("restaurent_address_id");
String restaurentInfoId = object.getJSONArray("data").getJSONObject(1).getJSONObject("restaurentInfo").getString("restaurent_info_id");
String restaurentBizOwnerName = object.getJSONArray("data").getJSONObject(1).getJSONObject("restaurentInfo").getString("restaurent_business_owner_name");
}
catch (JSONException e) {
}
Its Done I tried this
try {
JSONObject jsonRootObject = new JSONObject(strJson);
//Get the instance of JSONArray that contains JSONObjects
JSONArray mainnode =jsonRootObject.getJSONArray("data");
//Iterate the jsonArray and print the info of JSONObjects
for(int i=0; i < mainnode.length(); i++){
JSONObject jsonObject = mainnode.getJSONObject(i);
JSONObject Data = jsonObject.getJSONObject("restaurentInfo");
int id = Integer.parseInt(Data.getString("restaurent_info_id"));
String postcode = Data.getString("restaurent_phone_number");
String addresss = Data.getString("restaurent_bussiness_owner_name");
dataoutput += " : \n restaurent_id= "+ id +" \n restaurent_info_id= "+ postcode +" \n restaurent_address_id= "+ addresss +" \n ";
}
output.setText(dataoutput);
} catch (JSONException e) {e.printStackTrace();}
}
I just removed Status Object
and another for loop Thanks For the Help Got little Bit Help from You :)

How i replace java multiple chars and strings with others;

I have a string from http request and i want to replace multiple chars and strings with others.How i can do this?With Array for more efficient way?
String result =" "hourly": [ {"cloudcover": "0", "humidity": "93", "precipMM": "0.0", "pressure": "1013", "sigHeight_m": "0.7", "swellDir": "70", "swellHeight_m": "0.5", "swellPeriod_secs": "1.0", "tempC": "9", "tempF": "48", "time": "0", "v";
String result2 = result.replace("{", " ");
String result3 = result2.replace("}", " ");
String result4 = result3.replace("[", " ");
String result5 = result4.replace("]", " ");
String result6 = result5.replace("\"", "");
String result7 = result6.replaceAll("......", " ");
String result8 = result7.replaceAll("cloudcover", "\n \ncloudcover");
String result9 = result8.replaceAll("winddir:", " \nwinddir:");
String result10 = result9.replaceAll("tempC:", " \ntempC:");
WeatherInfos.setText( result10 );//Shows the weather info
Try following
String result = "{\"hourly\": [ {\"cloudcover\": \"15\", \"humidity\": \"93\", \"pressure\": \"1013\", \"tempC\": \"9\", \"winddir\": \"25\"}]}";
if(!result.startsWith("{"))
result = "{" + result + "}";
JSONObject JSONResult = new JSONObject(result);
JSONResult = (JSONObject) JSONResult.getJSONArray("hourly").get(0);
String cloudcover = JSONResult.getString("cloudcover");
String tempC= JSONResult.getString("tempC");
String winddir= JSONResult.getString("winddir"); //i do not see winddir in your result
Toast.makeText(getapplicationContext(), "Cloud Cover is "+ cloudcover , Toast.LENGTH_LONG).show();
now print cloudcover, winddir and tempC where ever you want.

Trying to change string values to check if they're empty on my Android app

So, I'm getting a bunch of string values from a JSON object and then I'm printing them all. However, I wanted to put all the values in a String array and check to see if they're empty, and if so... change the value to "N/A" so they're not just blank. However, it recognizes which strings are blank but when I check them in the logcat, it doesn't print the name of the string that's empty. For instance, I know two strings are going to be empty, but when I check it with this:
System.out.println(nullCheck[i] + "is empty");
"is empty" just shows up twice in the logcat. And even if I want to change the values of ANY of them, it still won't do it. It retrieves all of the strings that have data in them and prints them out just fine. I might be just overlooking something incredibly easy, but I would appreciate any help. Here's the full snippet for reference:
String supplieraddress = "";
String supplierphone = "";
String supplieremail = "";
String supplierfax = "";
String vouchercontact = "";
String supplierid = "";
String suppliername = "";
String servicetype = "";
String serviceid = "";
String vouchernotes = "";
try {
voucher = reservation.getJSONArray("vouchers").getJSONObject(vouchNumber);
supplieraddress = voucher.getString("supplieraddress");
supplierphone = voucher.getString("supplierphone");
supplieremail = voucher.getString("supplieremail");
supplierfax = voucher.getString("supplierfax");
vouchercontact = voucher.getString("vouchercontact");
supplierid = voucher.getString("supplierid");
suppliername = voucher.getString("suppliername");
servicetype = voucher.getString("servicetype");
serviceid = voucher.getString("serviceid");
vouchernotes = voucher.getString("vouchernotes");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String[] nullCheck = {supplieraddress, supplierphone, supplieremail, supplierfax, vouchercontact,
supplierid, suppliername, servicetype, serviceid, vouchernotes};
for(int i = 0; i < nullCheck.length; i++)
{
if(nullCheck[i].equals(""))
{
System.out.println(nullCheck[i] + "is empty");
nullCheck[i] = "N/A";
}
}
content.setText(Html.fromHtml(
"</br><b>Supplier Address </b><br/>" + supplieraddress
+ "<br/><br/><b>Supplier Phone </b><br/>" + supplierphone
+ "<br/><br/><b>Supplier Email </b><br/>" + supplieremail
+ "<br/><br/><b>Supplier Fax </b><br/>" + supplierfax
+ "<br/><br/><b>Voucher Contact </b><br/>" + vouchercontact
+ "<br/><br/><b>Supplier ID </b><br/>" + supplierid
+ "<br/><br/><b>Supplier Name </b><br/>" + suppliername
+ "<br/><br/><b>Service Type </b><br/>" + servicetype
+ "<br/><br/><b>Service ID </b><br/>" + serviceid
+ "<br/><br/><b>Voucher Notes </b><br/>" + vouchernotes
));
}
Thanks guys!
do it in your try block like this:
String s = voucher.getString("supplieraddress");
supplieraddress = TextUtils.isEmpty(s)? "N/A" : s;
s = voucher.getString("supplierphone");
supplierphone = TextUtils.isEmpty(s)? "N/A" : s;
s = voucher.getString("supplieremail");
supplieremail = TextUtils.isEmpty(s)? "N/A" : s;
// and so on....

Categories

Resources