I am new to android and I am unable to retrieve data from this JSON code below. Please reply with suggestions.
Json Code:-
{"category":{"name":["Spa","Salon","Makeup"],"brand_title":["Aura Thai Spa- Greater Kailash 1",.....]}}
Android code:
public class Salon extends AppCompatActivity {
String url="my_url";
String catname,brandname;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_salon);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
sname=(TextView)findViewById(R.id.person_name);
bname=(TextView)findViewById(R.id.person_age);
new MyAsyncTask().execute(url);
}
class MyAsyncTask extends AsyncTask<String, String, JSONObject> {
URLConnection urlConnection;
String result = "";
JSONObject jsonRootObject;
#Override
protected JSONObject doInBackground(String... params) {
try {
URL url_data = new URL(url);
urlConnection = url_data.openConnection();
urlConnection.connect();
// Convert response to string using String Builder
InputStream inputStream = urlConnection.getInputStream();
BufferedReader bReader = new BufferedReader(new InputStreamReader(inputStream, "utf-8"), 8);
StringBuilder sBuilder = new StringBuilder();
String line;
while ((line = bReader.readLine()) != null) {
sBuilder.append(line + "\n");
}
inputStream.close();
result = sBuilder.toString();
}catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
catch (Exception e) {
//Log.e("StringBuilding & BufferedReader", "Error converting result " + e.toString());
}
try{
jsonRootObject = new JSONObject(result);
}catch(JSONException e){
e.printStackTrace();
}
return jsonRootObject;
}
protected void onPostExecute(JSONObject result){
try {
//Iterate the jsonArray and print the info of JSONObjects
JSONArray jsonArray = jsonRootObject.getJSONArray("name");
for(int i=0; i < jsonArray.length(); i++) {
JSONObject name_0 = jsonArray.getJSONObject(i);
catname = name_0.getString("").toString();
}
/* JSONArray jsonArray2 = jsonRootObject.getJSONArray("brand_name");
JSONObject brand = jsonArray2.getJSONObject(0);
brandname = brand.getString("brand_title[0]");*/
//loat salary = Float.parseFloat(jsonObject.optString("salary").toString());
sname.setText(catname);
//bname.setText(brandname);
} catch (JSONException e) {e.printStackTrace();}
}
}
}
try replacing:
JSONArray jsonArray = jsonRootObject.getJSONArray("name");
with:
JSONArray jsonArray = jsonRootObject.getJSONObject("category").getJSONArray("name");
When you do:
jsonRootObject = new JSONObject(result);
You are getting the whole JSONobject string as itself, so you need to get just the category object:
jsonRootObject = jsonRootObject.getJSONObject("category")
and then you can get the array from the category:
JSONArray jsonArray = jsonRootObject.getJSONArray("name");
Try parsing like this. This will give you your required name and brand_title
// Declare outside onCreate
JSONObject topObject;
JSONObject category;
JSONArray name;
String json;
JSONArray brand_title;
// the parsing
json = "{\"category\":{\"name\":[\"Spa\",\"Salon\",\"Makeup\"],\"brand_title\":[\"Aura Thai Spa- Greater Kailash 1\"]}}";
try {
topObject = new JSONObject(json);
} catch (JSONException e) {
e.printStackTrace();
}
try {
category = topObject.getJSONObject("category");
} catch (JSONException e) {
e.printStackTrace();
}
try {
name = category.getJSONArray("name");
} catch (JSONException e) {
e.printStackTrace();
}
for(int i = 0; i<name.length(); i++){
try {
String parsedNanes = name.getString(i);
Log.i("parsedNames", parsedNanes);
} catch (JSONException e) {
e.printStackTrace();
}
}
try {
brand_title = category.getJSONArray("brand_title");
} catch (JSONException e) {
e.printStackTrace();
}
for(int i = 0; i<brand_title.length(); i++){
try {
String parsedBrandTitles = brand_title.getString(i);
Log.i("parsedBrandTitles", parsedBrandTitles);
} catch (JSONException e) {
e.printStackTrace();
}
}
Related
Url
private static String JSON_URL ="https://run.mocky.io/v3/aff3f637-d04f-45c0-b002-09be1a143784";
ArrayList<HashMap<String,String>> friendsList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
friendsList= new ArrayList<>();
lv = findViewById(R.id.listview);
GetData getData= new GetData();
getData.execute();
}
Getting the data
public class GetData extends AsyncTask<String, String, String>{
#Override
protected String doInBackground(String... strings) {
String current = "";
try {
URL url;
HttpURLConnection urlConnection = null;
try {
url = new URL(JSON_URL);
urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = urlConnection.getInputStream();
InputStreamReader isr = new InputStreamReader(in);
int data = isr.read();
while (data != -1) {
current += (char) data;
data = isr.read();
}
return current;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
} catch (Exception e){
e.printStackTrace();
}
return current;
}
Displaying the data
#Override
protected void onPostExecute(String s) {
try{
JSONObject jsonObject= new JSONObject(s);
JSONArray jsonArray = jsonObject.getJSONArray("Friends"); //name of array
for(int i = 0; i <jsonArray.length();i++)
{
JSONObject jsonObject1 = jsonArray.getJSONObject(i);
namey=jsonObject.getString("name");
age= jsonObject1.getString("age");
//Hashmap
HashMap<String, String> friends = new HashMap<>();
friends.put("name",namey);
friends.put("age", age);
friendsList.add(friends);
}
} catch (JSONException e) {
e.printStackTrace();
}
//Displaying the results
ListAdapter adapter = new SimpleAdapter(
MainActivity.this,
friendsList,
R.layout.row_layout,
new String[]{"name","age"},
new int[]{R.id.textView, R.id.textView2});
lv.setAdapter(adapter);
}
}
}
It doesnt display anything and i believe it has something to do with the url, but i am not quite sure so please help and thank you in advance
Your mocky JSON from https://run.mocky.io/v3/aff3f637-d04f-45c0-b002-09be1a143784 is wrong format, you need to remove the last character
please help me out from this i need to display the json array data but it will only show the first value from json .i tried to change the values but one value is shown not an array
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btnadd=(Button)findViewById(R.id.btnhit);
tvdata = (TextView)findViewById(R.id.tvJsonitem);
btnadd.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
new JSONTask().execute("https://api.myjson.com/bins/106o37");
}
}
);
}
public class JSONTask extends AsyncTask{
#Override
protected String doInBackground(String... params) {
HttpsURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
connection = (HttpsURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String finalJson = buffer.toString();
JSONArray jsonarray = new JSONArray(finalJson);
StringBuffer finalBufferedData=new StringBuffer();
for(int i=0; i<jsonarray.length(); i++){
JSONObject obj = jsonarray.getJSONObject(i);
String description = obj.getString("description");
finalBufferedData.append(description + "\t\n"
);
return finalBufferedData.toString();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
Your return statement should be outside of your for loop. Now it is inside so the method returns the first value.
use this
#Override
protected String doInBackground(String... params) {
HttpsURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
connection = (HttpsURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String finalJson = buffer.toString();
JSONArray jsonarray = new JSONArray(finalJson);
StringBuffer finalBufferedData=new StringBuffer();
for(int i=0; i<jsonarray.length(); i++){
JSONObject obj = jsonarray.getJSONObject(i);
String description = obj.getString("description");
finalBufferedData.append(description + "\t\n"
);
}
return finalBufferedData.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
I'm trying to troubleshoot my code, which has a array within an array, and then I want to retrieve all of the ID values inside it
private TextView tvData;
private ImageView imgtest;
String ChampionName;
String ChampionNameInLowerCase;
String item2;
String item3;
String Booked;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvData = (TextView) findViewById(R.id.tvJsonItem);
imgtest = (ImageView) findViewById(R.id.imageView);
// http://api.champion.gg/champion/Ekko/
new JSONTask().execute("http://api.champion.gg/champion/Ekko/");
}
public class JSONTask extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String finalJson = buffer.toString();
JSONArray jsonarray = new JSONArray(finalJson);
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject finalObject = jsonarray.getJSONObject(i);
ChampionName = finalObject.getString("key");
String role = finalObject.getString("role");
String items = finalObject.getString("items");
JSONObject ItemArray = new JSONObject(items);
item2 = ItemArray.getString("mostGames");
JSONObject ItemArray2 = new JSONObject(item2);
item3 = ItemArray2.getString("items");
JSONArray jsonarray2 = new JSONArray(item3);
for (int j=0;j<jsonarray2.length();j++) {
JSONObject finalObject2 = jsonarray.getJSONObject(j);
Booked = finalObject2.getString("id");
}
return ChampionName + role + item3 + Booked;
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
tvData.setText(result);
ChampionNameInLowerCase = ChampionName.toLowerCase().replaceAll("'", "");;
int id = getResources().getIdentifier("com.example.kripzy.url:drawable/" + ChampionNameInLowerCase+"_square_0", null ,null);
imgtest.setImageResource(id);
}
}
}
And then more closely the code up for question is this section;
JSONArray jsonarray2 = new JSONArray(item3);
for (int j=0;j<jsonarray2.length();j++) {
JSONObject finalObject2 = jsonarray.getJSONObject(j);
Booked = finalObject2.getString("id");
}
return ChampionName + role + item3 + Booked;
}
When the code directly above is added, it gives an error
org.json.JSONException: No value for id
When I delete that small snippet of code, the code produces
The problem is here Booked = finalObject2.getString("id"); use Booked = finalObject2.getInt("id");
and by the way you can use
JSONObject finalObject2 = jsonarray.getJSONObject(jsonarray2.length()-1); instead the the for (int j=0;j<jsonarray2.length();j++)
In the for-loop where you iterate over jsonarray2 you access jsonarray instead of jsonarray2 to get your JSONObject.
I tried to convert JSON from PHP server side to string in Android.
It force closes with (java.lang.String cannot be converted to JSONObject ) Error.
This is my Web class for HTTP connecting:
public class Web {
public static String readUrl(String url) {
try {
HttpClient client = new DefaultHttpClient();
HttpPost method = new HttpPost(url);
HttpResponse response = client.execute(method);
InputStream inputStream = response.getEntity().getContent();
String result = convertInputstreamToString(inputStream);
return result;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private static String convertInputstreamToString(InputStream inputStream){
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder builder = new StringBuilder();
String line ="";
while ((line = reader.readLine())!=null) {
builder.append(line);
}
return String.valueOf(builder);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
This is my Activity:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
try {
String result = Web.readUrl("http://192.168.1.53/mana/mana%20records.php");
if (result != null) {
try {
JSONArray records = new JSONArray(result);
for (int i = 0; i < records.length(); i++) {
JSONObject record = records.getJSONObject(i);
Log.d("Records", record.getString("date"));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
thread.start();
}
}
And this is my JSON:
[{"date":"2015-12-01","Shift Day":"on","Shift Night":"",
"Shift Person":"a","Code":"1","1st":"1000","Size 8":null,
"2nd":"1","3rd":"10","logo":"1000","Storage":"10000"},
{"date":"2015-12-02","Shift Day":"",
"Shift Night":"on","Shift Person":"b","Code":"2","1st":"2000",
"Size 8":null,"2nd":"2","3rd":"20","logo":"2000",
"Storage":"20000"}]
I want to display about_builder of given JSON url, but I am not able to declare properly JSONObject and JSONArray on MainActivity, so please anyone help me to display the data on TextView.
Error shown:
java.lang.RuntimeException: Unable to start activity
ComponentInfo{com.example.and_ws_builder/com.example.and_ws_builder.MainActivity}:
android.os.NetworkOnMainThreadException
MainActivity.java class
public class MainActivity extends Activity {
private static String url ="http://myfourwalls.in/services_microsite/project_builder.php";
private static final String TAG_Name = "about_builder";
JSONArray builder = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONFormUrl(url);
try {
builder = json.getJSONArray(TAG_Name);
JSONObject c = builder.getJSONObject(0);
for (int i = 0; i < json.length(); i++) {
String name = c.getString(TAG_Name);
final TextView nam = (TextView) findViewById(R.id.txtname);
nam.setText(name);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
JSONParser.java
public class JSONParser {
static InputStream is = null;
static JSONObject jobj = null;
static String json = "";
public JSONParser() {
}
public JSONObject getJSONFormUrl(String url) {
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}catch (ClientProtocolException e) {
e.printStackTrace();
}catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null ){
sb.append(line +"\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error","Error converting result" + e.toString());
}
try {
jobj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parse","error Parsing data" + e.toString());
}
return jobj;
}
}
main_activity.xml
<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" >
<TextView
android:id="#+id/txtname"
android:layout_width="fill_parent"
android:layout_height="100dp"/>
</RelativeLayout>
You are using Network related code in main thread. Use AsyncTask.
You are calling network calls inside the main thread means foreground which is not supported in android.So use assynctask class which will handle network calls in background.
1)inside on create method call like:
new GetJson().execute();
2) declare the following outside oncreate
private class GetJson extends AsyncTask<String, Void, String> {
JSONObject c=null;
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected JSONObject doInBackground(String... params) {
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONFormUrl(url);
try {
builder = json.getJSONArray(TAG_Name);
c = builder.getJSONObject(0);
} catch (JSONException e) {
e.printStackTrace();
}
return c;
}
#Override
protected void onPostExecute(final JSONObject result) {
for (int i = 0; i < result.length(); i++) {
String name = result.getString(TAG_Name);
final TextView nam = (TextView) findViewById(R.id.txtname);
nam.setText(name);
}
}