Android, random from external json - android

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();

Related

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

Parsing a JSON object in 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".

Android loopj AsyncHttpClient, parsing JSON example

I was looking for a simple example on parsing a JSON file, using the loopj AsyncHttpClient. But so far I could not find any useful information. :(
Simple JSON file to parse:
{
"contact": [
{
"id": "10",
"name": "Tom",
"email": "tom#gmail.com"
}
}
]
}
I would be grateful for any suggestion.
Thanks!!
You need to get the json first. I assume you have done that
{ // json object node
"contact": [ //json array contact
{ // json object node
To parse
JSONObject jb = new JSONObject("your json");
JSONArray con = jb.getJSONArray("contact");
JSONObject contact = (JSONObject) con.getJSONObject(0);
String id = contact.getString("id");
String name = contact.getString("name");
String id = contact.getString("id");
public class MainActivity extends Activity {
private ProgressDialog pdialog;
private static String url = "http://highspecificationservers.com/apk/webservice.php";
private static final String TAG_STUDENT = "student";
private static final String TAG_FNAME = "fname";
private static final String TAG_EMAIL = "email";
private static final String TAG_MOBILE = "mobile";
JSONArray student = null;
ArrayList<HashMap<String, String>> studentlist;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
studentlist = new ArrayList<HashMap<String, String>>();
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
String fname = ((TextView) view.findViewById(R.id.fname))
.getText().toString();
String cost = ((TextView) view.findViewById(R.id.email))
.getText().toString();
String description = ((TextView) view.findViewById(R.id.mobile))
.getText().toString();
Intent in = new Intent(getApplicationContext(),
SingleContactActivity.class);
in.putExtra(TAG_FNAME, fname);
in.putExtra(TAG_EMAIL, cost);
in.putExtra(TAG_MOBILE, description);
startActivity(in);
}
});
new GetStudent().execute();
}
private class GetStudent extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
pdialog = new ProgressDialog(MainActivity.this);
pdialog.setMessage("please wait");
pdialog.setCancelable(false);
pdialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
ServiceHandler sh = new ServiceHandler();
String jString = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response:", "> " + jString);
if (jString != null) {
try {
JSONObject Jsonobj = new JSONObject(jString);
student = Jsonobj.getJSONArray(TAG_STUDENT);
for (int i = 0; i < student.length(); i++) {
JSONObject c = student.getJSONObject(i);
String fname = c.getString(TAG_FNAME);
String email = c.getString(TAG_EMAIL);
String mobile = c.getString(TAG_MOBILE);
HashMap<String, String> student = new HashMap<String, String>();
student.put(TAG_FNAME, fname);
student.put(TAG_EMAIL, email);
student.put(TAG_MOBILE, mobile);
studentlist.add(student);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
if (pdialog.isShowing())
pdialog.dismiss();
ListAdapter adapter = new SimpleAdapter(MainActivity.this,
studentlist, R.layout.list_item, new String[] { TAG_FNAME,
TAG_EMAIL, TAG_MOBILE }, new int[] { R.id.fname,
R.id.email, R.id.mobile });
setListAdapter(adapter);
}
private void setListAdapter(ListAdapter adapter) {
// TODO Auto-generated method stub
}
}
private ListView getListView() {
// TODO Auto-generated method stub
return null;
}
}
Go with this...
// JSON Node names
private static final String TAG_CONTACTS = "contacts";
private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";
private static final String TAG_EMAIL = "email";
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
contacts = jsonObj.getJSONArray(TAG_CONTACTS);
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String email = c.getString(TAG_EMAIL);
// tmp hashmap for single contact
HashMap<String, String> contact = new HashMap<String, String>();
// adding each child node to HashMap key => value
contact.put(TAG_ID, id);
contact.put(TAG_NAME, name);
contact.put(TAG_EMAIL, email);
// adding contact to contact list
contactList.add(contact);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}

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