Parsing a JSON object in Android - android

I am trying to parse a single JSON object that looks like this:
{
"message":"Request Successful",
"data":{
"id":"g8nEDt",
"name":"Twins Bazil Twins",
"nameDisplay":"Twins Bazil Twins",
"abv":"6.75",
"isOrganic":"N",
"description":"Beers",
}
},
"status":"success"
}
This is the code that I am using.
public class randomBeer extends Activity {
TextView name1;
TextView description1;
TextView abv1;
TextView ibu1;
Button Btngetdata;
//URL to get JSON Array
private static String urlRandom = "http://api.brewerydb.com/v2/beer/random?key=mykey";
//JSON Node Names
private static final String TAG_DATA = "data";
private static final String TAG_NAME = "name";
private static final String TAG_DESCRIPTION = "description";
private static final String TAG_ABV = "abv";
private static final String TAG_IBU = "ibu";
JSONObject data = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.randombeer);
Btngetdata = (Button)findViewById(R.id.getdata);
Btngetdata.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new JSONParse().execute();
}
});
}
private class JSONParse extends AsyncTask<String, String, JSONObject> {
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
name1 = (TextView)findViewById(R.id.name);
description1 = (TextView)findViewById(R.id.description);
abv1 = (TextView)findViewById(R.id.abv);
ibu1 = (TextView)findViewById(R.id.ibu);
pDialog = new ProgressDialog(randomBeer.this);
pDialog.setMessage("Getting Data ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected JSONObject doInBackground(String... args) {
JSONParser jParser = new JSONParser();
// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrl(urlRandom);
return json;
}
#Override
protected void onPostExecute(JSONObject json) {
pDialog.dismiss();
try {
// Getting JSON Array
data= json.getJSONArray(TAG_DATA);
JSONObject c = data.getJSONObject(0);
// Storing JSON item in a Variable
String name = c.getString(TAG_NAME);
String ibu;
if(c.has("ibu")) {
ibu = c.getString(TAG_IBU);
} else {
ibu = "No ibu value";
}
String abv;
if(c.has("abv")) {
abv = c.getString(TAG_ABV);
} else {
abv = "No abv value";
}
String description;
if(c.has("description")) {
description = c.getString(TAG_DESCRIPTION);
} else {
description = "No description available";
}
//Set JSON Data in TextView
name1.setText(name);
description1.setText(description);
abv1.setText(abv);
ibu1.setText(ibu);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
The problem is that it is trying to get an array but I just need and object.
How can I transform this code so it gets the object instead of trying to get an array?
I tried to change
data = json.getJSONArray(TAG_DATA);
to
data = json.getJSONObject(TAG_DATA);
but then on the line
JSONObject c = data.getJSONObject(0);
I get an Error:
(87, 51) error: incompatible types: int cannot be converted to
String.

It should be
data= json.getJSONObject(TAG_DATA);
instead of
data= json.getJSONArray(TAG_DATA);
in onPostExecute. It now has
"data":{
"id":"g8nEDt",
"name":"Twins Bazil Twins",
"nameDisplay":"Twins Bazil Twins",
"abv":"6.75",
"isOrganic":"N",
"description":"Beers",
}
in it. To get i.e. the "name" use
String name = data.getString("name");
IN ADDITION:
Make sure to execute HttpGet instead of HttpPost when using this link
http://api.brewerydb.com/v2/beer/random?key=mykey

Replace this:
// Getting JSON Array
data= json.getJSONArray(TAG_DATA);
JSONObject c = data.getJSONObject(0);
with:
// Getting JSON Object
data= json.getJSONObject(TAG_DATA);
Also, replace all "c" variable usages with "data".

Related

Get information from an ObjectJson without Array

I have the class below and I can fetch information from a JSONArray in this format:
{"cliente":[{"id":"1334","nome":"Bruno"}]}
TextView nome_usuario;
private static final String TAG_CLIENTE = "cliente";
private static final String TAG_NOME = "nome";
JSONArray cliente = null;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View grafico = inflater.inflate(R.layout.fragment_fragment_perfil, container, false);
nome_usuario = (TextView ) grafico.findViewById(R.id.txtNome);
new JSONParse().execute();
return grafico;
}
private class JSONParse extends AsyncTask<String, String, JSONObject> {
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Atualizando");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected JSONObject doInBackground(String... args) {
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONFromUrl("url do json");
return json;
}
#Override
protected void onPostExecute(JSONObject json) {
pDialog.dismiss();
try {
cliente = json.getJSONArray(TAG_CLIENTE);
JSONObject c = cliente.getJSONObject(0);
String nome = c.getString(TAG_NOME);
nome_usuario.setText(nome);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
But now I would like to work with a json in the following format:
{"name": "Bruno"}
I found a question similar to my How to parse JSON Object Android Studio, but I could not apply it to my example.
Getting information from an JSONObject:
JSONObject aJsonObject = new JSONObject(aJsonResponse);
JSONArray aJsonArray = aJsonObject.getJSONArray("cliente");
for (int i = 0; i < aJsonArray.length(); i++) {
aJsonObject = aJsonArray.getJSONObject(i);
String aId = aJsonObject .getString("id");
String aNome = aJsonObject .getString("nome");
}
Try using this, you should replace aJsonResponse with the response from the server
JSONObject aJsonObject = new JSONObject(aJsonResponse);
String aId = aJsonObject.getString("id");
String aNome = aJsonObject.getString("name");

json data is not fetching from url

I am making an android app to fetch the mailaddress which store in mysql data to check if mail address typed in edittext is unique or not but i always get null fron json url. My json code is
{"result":[{"mailId":"nikhilmanali#gmail.com"}]}
my android code is:
EditText et1,et2,et3,et4,et5;
Button bu1;
String mailCheck;
String mail;
// TextView alert;
String name,password,mailId,repass,number;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new AsyncTaskParse().execute();
Toast.makeText(MainActivity.this,mailCheck,Toast.LENGTH_SHORT).show();
et1=(EditText)findViewById(R.id.et1);
et2=(EditText)findViewById(R.id.et2);
et3=(EditText)findViewById(R.id.et3);
et4=(EditText)findViewById(R.id.et4);
et5=(EditText)findViewById(R.id.et5);
name=et1.getText().toString();
password=et2.getText().toString();
/// alert=(TextView)findViewById(R.id.alert);4
repass=et4.getText().toString();
mailId=et3.getText().toString();
number=et5.getText().toString();
bu1=(Button)findViewById(R.id.bu1);
bu1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String t = et1.getText().toString();
String t5 = et5.getText().toString();
String one = et2.getText().toString();
String two = et4.getText().toString();
mail = et3.getText().toString();
if(one.equals(two) ){
if (one.equals(two) && isEmailValid(mail,et3)) {
isInternetOn();
}
} else {
et4.setError(Html.fromHtml("<font color='#000'>Password not Match!</font>"));
focus(et4);
}
}
}
});
}
////////////////////////
public class AsyncTaskParse extends AsyncTask<String, String, String> {
final String TAG = "AsyncTaskParseJson.java";
// set your json string url here
String yourJsonStringUrl = "http://www.example.com/checkMail.php?mailId="+mailId;
// contacts JSONArray
JSONArray dataJsonArr = null;
#Override
protected void onPreExecute() {}
protected String doInBackground(String... arg0) {
try {
JSONParser jParser = new JSONParser();
// get json string from url
JSONObject json = jParser.getJSONFromUrl(yourJsonStringUrl);
if(json!=null) {
// get the array of users
dataJsonArr = json.getJSONArray("result");
JSONObject c = dataJsonArr.getJSONObject(0);
// na=c.getString("avg");
mailCheck = c.getString("mailId");
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
}
Put your new AsyncTaskParse().execute(); after mail = et3.getText().toString();
Maybe you need to keep AsyncTaskParse().execute(); inside your onClick

How to solve org.json.JSONException: Index 0 out of range [0..0) using android

I am developing an app, here i want to display fetched items of table I tried following code but it gives error at this line JSONObject c = result.getJSONObject(0);.
How do i solve this?
//java file
public class Details extends Activity {
TextView uid;
TextView name1, amount1;
TextView email1;
Button Btngetdata;
//URL to get JSON Array
private static String url = "http://example.in/ticket1.php";
//JSON Node Names
private static final String TAG_USER = "result";
// private static final String TAG_ID = "id";
private static final String TAG_NAME = "pname";
private static final String TAG_AMOUNT = "pamount";
JSONArray result = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.details);
Btngetdata = (Button)findViewById(R.id.getdata);
Btngetdata.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new JSONParse().execute();
}
});
}
private class JSONParse extends AsyncTask<String, String, JSONObject> {
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
uid = (TextView)findViewById(R.id.uid);
name1 = (TextView)findViewById(R.id.name);
amount1 = (TextView)findViewById(R.id.email);
pDialog = new ProgressDialog(Details.this);
pDialog.setMessage("Getting Data ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected JSONObject doInBackground(String... args) {
JSONParser jParser = new JSONParser();
// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrl(url);
return json;
}
#Override
protected void onPostExecute(JSONObject json) {
pDialog.dismiss();
try {
// Getting JSON Array
result = json.getJSONArray(TAG_USER);
JSONObject c = result.getJSONObject(0);
// Storing JSON item in a Variable
// String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String amount = c.getString(TAG_AMOUNT);
//Set JSON Data in TextView
// uid.setText(id);
name1.setText(name);
amount1.setText(amount);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
Check the size of the result array before you iterate over it.
#Override
protected void onPostExecute(JSONObject json) {
{
pDialog.dismiss();
try {
// Getting JSON Array
result = json.getJSONArray(TAG_USER);
if (result.length() > 0) {
JSONObject c = result.getJSONObject(0);
// Storing JSON item in a Variable
// String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String amount = c.getString(TAG_AMOUNT);
//Set JSON Data in TextView
// uid.setText(id);
name1.setText(name);
amount1.setText(amount);
}
} catch (JSONException e) {
e.printStackTrace();
}
}

Android, random from external json

I am working on an android app. I want the app to select randomly a name from json.
Here is the json :
{
"user": [
{
"id": "001",
"name": "Raj Amal",
"email": "raj.amalw#gmail.com"
},
{
"id": "002",
"name": "Raj",
"email": "amalw#gmail.com"
}
]
}
And here is my android code :
public class MainActivity extends Activity {
TextView uid;
TextView name1;
TextView email1;
Button Btngetdata;
//URL to get JSON Array
private static String url = "http://weblink/json/index.php";
//JSON Node Names
private static final String TAG_USER = "user";
private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";
private static final String TAG_EMAIL = "email";
JSONArray user = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Btngetdata = (Button)findViewById(R.id.getdata);
Btngetdata.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new JSONParse().execute();
}
});
}
private class JSONParse extends AsyncTask<String, String, JSONObject> {
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
uid = (TextView)findViewById(R.id.uid);
name1 = (TextView)findViewById(R.id.name);
email1 = (TextView)findViewById(R.id.email);
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Getting Data ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected JSONObject doInBackground(String... args) {
JSONParser jParser = new JSONParser();
// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrl(url);
return json;
}
#Override
protected void onPostExecute(JSONObject json) {
pDialog.dismiss();
try {
// Getting JSON Array
user = json.getJSONArray(TAG_USER);
JSONObject c = user.getJSONObject(0);
// Storing JSON item in a Variable
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String email = c.getString(TAG_EMAIL);
//Set JSON Data in TextView
uid.setText(id);
name1.setText(name);
email1.setText(email);
} catch (JSONException e) {
e.printStackTrace();
}
}
}`
I would that when I presse the button a random name shows and loops.
Please help
Thank you
Change JSONObject c = user.getJSONObject(0); by this line ->
JSONObject c = user.getJSONObject(new Random().nextInt(user.length()));
you need to generate Random number from your array
first try this to add items in temp Arraylist. i am just only adding characters you need to replace name instead of characters
String json="{'abridged_cast':
[{'name':'JeffBridges','id':'162655890','characters':['JackPrescott']},
{'name':'CharlesGrodin','id':'162662571','characters':['FredWilson']},
{'name':'JessicaLange','id':'162653068','characters':['Dwan']},
{'name':'JohnRandolph','id':'162691889','characters':['Capt.Ross']},
{'name':'ReneAuberjonois','id':'162718328','characters':['Bagley']}]}";
JSONObject jsonResponse;
try {
temp = new ArrayList<String>();
jsonResponse = new JSONObject(json);
JSONArray movies = jsonResponse.getJSONArray("abridged_cast"); // add
//user here instead of abridged_cas
for(int i=0;i<movies.length();i++){
JSONObject movie = movies.getJSONObject(i);
JSONArray characters = movie.getJSONArray("characters"); // replace
//name instead of characters
for(int j=0;j<characters.length();j++){
temp.add(characters.getString(j));
}
}
Toast.makeText(this, "Json: "+temp, Toast.LENGTH_LONG).show();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
here is you get names randomly using onclick or whatever you want.
Random randomizer = new Random();
String RandomName = temp.get(randomizer.nextInt(temp.size()));
Loop through the JSON input. You can use java function int random = Random.nextInt(n). This returns a random int in range[0, n-1].
ArrayList<String> names = new ArrayList<>();
JSONArray socialArray = response.getJSONArray(data);
for (int i = 0; i < socialArray.length(); i++) {
JSONObject currentJSON = socialArray.getJSONObject(i);
names.add(currentJSON.getString("name");
}
final int random = Random.nextInt(names.size() + 1);
Toast.makeText(this, "Random Name: " + names.get(random), LENGTH.SHORT).show();

send a consult to one url but the JSON return is null always

i have a problem i try to extract info of one php in my server but the response is null always
i attach the code that i use next, I'm new in android but i think that the PC don't send anything to the app
public class MainActivity extends Activity {
//URL to get JSON Array
private static String url = "http://10.69.44.108/odin/mobile/json/";
//JSON Node Names
private static final String TAG_USER = "user";
private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";
private static final String TAG_EMAIL = "email";
JSONArray user = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Creating new JSON Parser
JSONParser jParser = new JSONParser();
// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrl(url);
try {
// Getting JSON Array
user = json.getJSONArray(TAG_USER);
JSONObject c = user.getJSONObject(0);
// Storing JSON item in a Variable
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String email = c.getString(TAG_EMAIL);
//Importing TextView
final TextView uid = (TextView)findViewById(R.id.uid);
final TextView name1 = (TextView)findViewById(R.id.name);
final TextView email1 = (TextView)findViewById(R.id.email);
//Set JSON Data in TextView
uid.setText(id);
name1.setText(name);
email1.setText(email);
} catch (JSONException e) {
e.printStackTrace();
}
}
In android you are not allowed to perform network operation on main thread:
you cant do :
// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrl(url);
in onCreate, you have to put it in an asyncTask.
you can do it quick and dirty like this (not tested!):
//Importing TextView
final TextView uid = (TextView)findViewById(R.id.uid);
final TextView name1 = (TextView)findViewById(R.id.name);
final TextView email1 = (TextView)findViewById(R.id.email);
new AsyncTask<String, JSONObject, JSONObject>(){
#Override
protected JSONObject doInBackground(String ... Urls) {
// Creating new JSON Parser
JSONParser jParser = new JSONParser();
// Getting JSON from URL
JSONObject json = new JSONObject();
try {
json = jParser.getJSONFromUrl(Urls[]);
} catch(JSONException e) {
// do somthing
return null
}
return json;
}
protected void onPostExecute(JSONObject json) {
try {
// Getting JSON Array
user = json.getJSONArray(TAG_USER);
JSONObject c = user.getJSONObject(0);
// Storing JSON item in a Variable
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String email = c.getString(TAG_EMAIL);
//Set JSON Data in TextView
uid.setText(id);
name1.setText(name);
email1.setText(email);
} catch (JSONException e) {
e.printStackTrace();
}
}
}.execute(url);

Categories

Resources