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
Related
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();
}
}
I am developing an app where on some page user need to select one option from given 4-5 options currently I'm using spinner for this functionality now the question is, if user selects 3rd or 4th option(only single option selection permitted) select how do i insert that particular option in mysql php database.following is the code I'm using right now..
//MainActivity.java
public class MainActivity_D extends AppCompatActivity implements AdapterView.OnItemSelectedListener{
//Declaring an Spinner
private Spinner spinner2, spinner1;
private String str_spinner1, str_spinner2, s_name, s_course;
//An ArrayList for Spinner Items
private ArrayList<String> students1;
private ArrayList<String> students2;
Button mBtnSave;
//JSON Array
private JSONArray result1, result2, result;
//TextViews to display details
private TextView textViewName1;
private TextView textViewName2;
private TextView textViewCourse;
private TextView textViewSession;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mainactivity_d);
//Initializing the ArrayList
students1 = new ArrayList<String>();
students2 = new ArrayList<String>();
//Initializing Spinner
//Adding an Item Selected Listener to our Spinner
//As we have implemented the class Spinner.OnItemSelectedListener to this class iteself we are passing this to setOnItemSelectedListener
spinner1 = (Spinner) findViewById(R.id.spinner1);
spinner2 = (Spinner) findViewById(R.id.spinner2);
spinner1.setOnItemSelectedListener(this);
spinner2.setOnItemSelectedListener(this);
mBtnSave = (Button) findViewById(R.id.button2);
mBtnSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
submitForm();
}
});
//Initializing TextViews
textViewName1 = (TextView) findViewById(R.id.textViewName1);
textViewName2 = (TextView) findViewById(R.id.textViewName2);
// textViewCourse = (TextView) findViewById(R.id.textViewCourse);
// textViewSession = (TextView) findViewById(R.id.textViewSession);
//This method will fetch the data from the URL
getData1();
getData2();
}
private void submitForm() {
// Submit your form here. your form is valid
//Toast.makeText(this, "Submitting form...", Toast.LENGTH_LONG).show();
// s_name = spinner1.getSelectedItem().toString();
// s_course = spinner2.getSelectedItem().toString();
Toast.makeText(this, "Signing up...", Toast.LENGTH_SHORT).show();
new InsertActivity(this).execute(s_name, s_course);
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
switch (parent.getId()){
case R.id.spinner1:
spinner1.setSelection(position);
s_name = (String) spinner1.getSelectedItem();
// getData1();
// showToast("Spinner1: position=" + position);
break;
case R.id.spinner2:
spinner2.setSelection(position);
s_course = (String) spinner2.getSelectedItem();
// getData2();
break;
}
/*if(spinner1.getId()==R.id.spinner1) {
textViewName1.setText(getName(position));
}
else if(spinner2.getId()==R.id.spinner2)
{
textViewName2.setText(getCourse(position));
}
switch (parent.getId()){
case R.id.spinner1:
// getData1();
// showToast("Spinner1: position=" + position);
break;
case R.id.spinner2:
// getData2();
break;
}*/
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
/* private String getName(int position){
String name="";
try {
//Getting object of given index
JSONObject json = result.getJSONObject(position);
//Fetching name from that object
name = json.getString(Config.TAG_NAME);
} catch (JSONException e) {
e.printStackTrace();
}
//Returning the name
return name;
}
private String getCourse(int position){
String course="";
try {
JSONObject json = result.getJSONObject(position);
course = json.getString(Config.TAG_COURSE);
} catch (JSONException e) {
e.printStackTrace();
}
return course;
}*/
private void getData1() {
//Creating a string request
StringRequest stringRequest1 = new StringRequest(Config.DATA_URL1,
new Response.Listener<String>() {
#Override
public void onResponse(String response1) {
JSONObject j1 = null;
try {
//Parsing the fetched Json String to JSON Object
j1 = new JSONObject(response1);
//Storing the Array of JSON String to our JSON Array
result1 = j1.getJSONArray(Config.JSON_ARRAY1);
//Calling method getStudents to get the students from the JSON Array
getStudents1(result1);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error1) {
}
});
//Creating a request queue
RequestQueue requestQueue1 = Volley.newRequestQueue(this);
//Adding request to the queue
requestQueue1.add(stringRequest1);
}
private void getStudents1(JSONArray j1) {
//Traversing through all the items in the json array
for (int i = 0; i < j1.length(); i++) {
try {
//Getting json object
JSONObject json1 = j1.getJSONObject(i);
//Adding the name of the student to array list
students1.add(json1.getString(Config.TAG_COURSE));
} catch (JSONException e) {
e.printStackTrace();
}
}
//Setting adapter to show the items in the spinner
spinner1.setAdapter(new ArrayAdapter<String>(MainActivity_D.this, android.R.layout.simple_spinner_dropdown_item, students1));
}
//Initializing TextViews
// textViewCourse = (TextView) findViewById(R.id.textViewCourse);
// textViewSession = (TextView) findViewById(R.id.textViewSession);
//This method will fetch the data from the URL
private void getData2() {
//Creating a string request
StringRequest stringRequest2 = new StringRequest(Config.DATA_URL2,
new Response.Listener<String>() {
#Override
public void onResponse(String response2) {
JSONObject j2 = null;
try {
//Parsing the fetched Json String to JSON Object
j2 = new JSONObject(response2);
//Storing the Array of JSON String to our JSON Array
result = j2.getJSONArray(Config.JSON_ARRAY);
//Calling method getStudents to get the students from the JSON Array
getStudents2(result);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error1) {
}
});
//Creating a request queue
RequestQueue requestQueue2 = Volley.newRequestQueue(this);
//Adding request to the queue
requestQueue2.add(stringRequest2);
}
private void getStudents2(JSONArray j2) {
//Traversing through all the items in the json array
for (int i = 0; i < j2.length(); i++) {
try {
//Getting json object
JSONObject json2 = j2.getJSONObject(i);
//Adding the name of the student to array list
students2.add(json2.getString(Config.TAG_USERNAME));
} catch (JSONException e) {
e.printStackTrace();
}
}
//Setting adapter to show the items in the spinner
spinner2.setAdapter(new ArrayAdapter<String>(MainActivity_D.this, android.R.layout.simple_spinner_dropdown_item, students2));
}
}
//InsertActivity.java
public class InsertActivity extends AsyncTask<String, Void, String> {
private Context context;
Boolean error, success;
public InsertActivity(Context context) {
this.context = context;
}
protected void onPreExecute() {
}
#Override
protected String doInBackground(String... arg0) {
String s_name = arg0[0];
// String userName = arg0[1];
String s_course = arg0[1];
String link;
String data;
BufferedReader bufferedReader;
String result;
try {
data = "?s_name=" + URLEncoder.encode(s_name, "UTF-8");
// data += "&username=" + URLEncoder.encode(userName, "UTF-8");
data += "&s_course=" + URLEncoder.encode(s_course, "UTF-8");
link = "http://insert_s1.php" + data;
// link = "http://example.com/mangoair10/tryrr.php" + data;
URL url = new URL(link);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
result = bufferedReader.readLine();
return result;
} catch (Exception e) {
// return new String("Exception: " + e.getMessage());
// return null;
}
return null;
}
/* #Override
protected void onPostExecute(String result) {
String jsonStr = result;
try {
JSONObject jsonObj = new JSONObject(jsonStr);
String query_result = jsonObj.getString("success");
String message_result = jsonObj.getString("message");
if (query_result.equalsIgnoreCase("1")) {
Toast.makeText(context,message_result , Toast.LENGTH_LONG).show();
} else if (query_result.equalsIgnoreCase("-1")) {
Toast.makeText(context, message_result, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}*/
#Override
protected void onPostExecute(String result) {
String jsonStr = result;
try {
JSONObject jsonObj = new JSONObject(jsonStr);
String query_result = jsonObj.getString("query_result");
Log.e("TAG", String.valueOf(query_result));
// String message_result = jsonObj.getString("message");
/* if (query_result.equals("SUCCESS")) {
Toast.makeText(context, "Insert", Toast.LENGTH_LONG).show();
} else if(query_result.equals("FAILURE")){
Toast.makeText(context, "Unable to Insert", Toast.LENGTH_LONG).show();
}*/
} catch (JSONException e) {
e.printStackTrace();
}
}
}
//Config.java
public class Config {
//JSON URL
// public static final String DATA_URL = "http://example.com/jsonphp1.php";
public static final String DATA_URL1 = "http://example.com/jsonphp2.php";
public static final String DATA_URL2 = "http://example.com/jsonphp1.php";
//Tags used in the JSON String
public static final String TAG_USERNAME = "username";
public static final String TAG_NAME = "name";
public static final String TAG_COURSE = "course";
public static final String TAG_SESSION = "session";
//JSON array name
public static final String JSON_ARRAY = "result";
public static final String JSON_ARRAY1 = "result1";
public static final String JSON_ARRAY2 = "result2";
}
//this is my php file
<?php
$con = mysqli_connect(HOST,USER,PASS,DB) or die('Unable to Connect');
$s_name=$_POST['s_name'];
$s_course=$_POST['s_course'];
Sid=$_GET['id'];
$query = "UPDATE `students` SET s_name = '$s_name', s_course= '$s_course' WHERE id='$id'";
$inserted = mysqli_query($con, $query);
// echo $inserted;
if($inserted) {
echo '{"query_result":"SUCCESS"}';
}
else{
echo '{"query_result":"FAILURE"}';
}
mysqli_close($con);
?>
The error is self explanatory. You are getting an Integer in your response which cannot be converted to a JSONObject. Log your response and check if it is a valid JSON.
In your asyntask onPostExecute method print response like this and post your response then error will be detected
#Override
protected void onPostExecute(String result) {
String jsonStr = result;
Log.e("TAG",jsonStr );
}
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();
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".
Below I have attached my code for trying to add my string array, names, to the spinner as the options. As of now, I am not getting anything populating the array, and I am really not sure what I'm doing wrong. I have looked over other similar questions on this site, as well as using Google, and have come up empty. Can anyone give me some guidance? Thanks
public class RunesActivity extends Activity {
public static String page;
TextView textName;
Spinner spinner;
ArrayAdapter<String> adapter;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.rune_activity);
GetRunes getRunes = new GetRunes();
getRunes.execute();
spinner = (Spinner) findViewById(R.id.rune_selector);
}
public void addListenerOnSpinnerSelection() {
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
((TextView) adapterView.getChildAt(0)).setTextColor(Color.parseColor("#C49246"));
Toast.makeText(adapterView.getContext(),
"Page Selected: " + adapterView.getItemAtPosition(i).toString(),
Toast.LENGTH_SHORT).show();
page = adapterView.getItemAtPosition(i).toString();
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
}
class GetRunes extends AsyncTask<String, String, JSONObject> {
private String api_key="d96236d2-6ee3-4cfd-afa7-f41bdbc11128";
String region = MainActivity.region.toLowerCase();
String id = StatsActivity.sumID;
String encodedKey = null;
String encodedRegion = null;
String encodedId = null;
String url = null;
// JSON Node Names
String TAG_NAME = "name";
String TAG_CURRENT = "current";
String TAG_SLOTS = "slots";
String TAG_RUNEID = "runeId";
String TAG_RUNESLOTID = "runeSlotId";
#Override
protected void onPreExecute() {
super.onPreExecute();
try {
// Assign views
textName = (TextView) findViewById(R.id.name);
// Encode URL variables
encodedId = URLEncoder.encode(id, "UTF-8");
encodedKey = URLEncoder.encode(api_key, "UTF-8");
encodedRegion = URLEncoder.encode(region, "UTF-8");
url = "http://prod.api.pvp.net/api/lol/" + region + "/v1.4/summoner/" + id + "/runes?api_key=" + api_key;
Log.i("..........", url);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
#Override
protected JSONObject doInBackground(String... arg0) {
JSONParser jParser = new JSONParser();
// Get JSON from URL
JSONObject json = jParser.getJSONFromUrl(url);
Log.i("............", "" + json);
return json;
}
#Override
protected void onPostExecute(JSONObject json) {
try {
// Get JSON Object
JSONObject runes = json.getJSONObject(encodedId);
// Get JSON Array node
JSONArray rune = runes.getJSONArray("pages");
// Loop through pages, page names stored in string array
String[] name = new String[rune.length()];
String curr;
ArrayList<String> runePageNames = new ArrayList<String>();
for(int i = 0; i < rune.length(); i++) {
JSONObject c = rune.getJSONObject(i);
name[i] = c.getString(TAG_NAME);
curr = c.getString(TAG_CURRENT);
if(curr.equals("true"))
name[i] = name[i] + " [Active]";
runePageNames.add(name[i]);
Log.i(".........", name[i]);
}
adapter = new ArrayAdapter(RunesActivity.this,
android.R.layout.simple_spinner_dropdown_item,
runePageNames);
addListenerOnSpinnerSelection();
// Set TextView
textName.setText(name[0]);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
Try this..
before calling addListenerOnSpinnerSelection(); method set adapter for that spinner.
adapter = new ArrayAdapter(RunesActivity.this,
android.R.layout.simple_spinner_dropdown_item,
runePageNames);
spinner.setAdapter(adapter );
addListenerOnSpinnerSelection();