I am parsing JSON data into ListView, and successfully parsed first level of JSON in MainActivity.java, where i am showing list of Main Locations, like:
Inner Locations
Outer Locations
Now i want whenever i do tap on Inner Locations then in SecondActivity it should show Delhi and NCR in a List, same goes for Outer Locations as well, in this case whenever user do tap need to show USA
JSON look like:
{
"all": [
{
"title": "Inner Locations",
"maps": [
{
"title": "Delhi",
"markers": [
{
"name": "Connaught Place",
"latitude": 28.632777800000000000,
"longitude": 77.219722199999980000
},
{
"name": "Lajpat Nagar",
"latitude": 28.565617900000000000,
"longitude": 77.243389100000060000
}
]
},
{
"title": "NCR",
"markers": [
{
"name": "Gurgaon",
"latitude": 28.440658300000000000,
"longitude": 76.987347699999990000
},
{
"name": "Noida",
"latitude": 28.570000000000000000,
"longitude": 77.319999999999940000
}
]
}
]
},
{
"title": "Outer Locations",
"maps": [
{
"title": "United States",
"markers": [
{
"name": "Virgin Islands",
"latitude": 18.335765000000000000,
"longitude": -64.896335000000020000
},
{
"name": "Vegas",
"latitude": 36.114646000000000000,
"longitude": -115.172816000000010000
}
]
}
]
}
]
}
Note: But whenever i do tap on any of the ListItem in first activity, not getting any list in SecondActivity, why ?
MainActivity.java:-
#Override
protected Void doInBackground(Void... params) {
// Create an array
arraylist = new ArrayList<HashMap<String, String>>();
// Retrieve JSON Objects from the given URL address
jsonobject = JSONfunctions
.getJSONfromURL("http://10.0.2.2/locations.json");
try {
// Locate the array name in JSON
jsonarray = jsonobject.getJSONArray("all");
for (int i = 0; i < jsonarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
jsonobject = jsonarray.getJSONObject(i);
// Retrieve JSON Objects
map.put("title", jsonobject.getString("title"));
arraylist.add(map);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void args) {
// Locate the listview in listview_main.xml
listview = (ListView) findViewById(R.id.listview);
// Pass the results into ListViewAdapter.java
adapter = new ListViewAdapter(MainActivity.this, arraylist);
// Set the adapter to the ListView
listview.setAdapter(adapter);
// Close the progressdialog
mProgressDialog.dismiss();
listview.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(MainActivity.this, String.valueOf(position), Toast.LENGTH_LONG).show();
// TODO Auto-generated method stub
Intent sendtosecond = new Intent(MainActivity.this, SecondActivity.class);
// Pass all data rank
sendtosecond.putExtra("title", arraylist.get(position).get(MainActivity.TITLE));
Log.d("Tapped Item::", arraylist.get(position).get(MainActivity.TITLE));
startActivity(sendtosecond);
}
});
}
}
}
SecondActivity.java:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get the view from listview_main.xml
setContentView(R.layout.listview_main);
Intent in = getIntent();
strReceived = in.getStringExtra("title");
Log.d("Received Data::", strReceived);
// Execute DownloadJSON AsyncTask
new DownloadJSON().execute();
}
// DownloadJSON AsyncTask
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
// Create an array
arraylist = new ArrayList<HashMap<String, String>>();
// Retrieve JSON Objects from the given URL address
jsonobject = JSONfunctions
.getJSONfromURL("http://10.0.2.2/locations.json");
try {
// Locate the array name in JSON
jsonarray = jsonobject.getJSONArray("maps");
for (int i = 0; i < jsonarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
jsonobject = jsonarray.getJSONObject(i);
// Retrieve JSON Objects
map.put("title", jsonobject.getString("title"));
arraylist.add(map);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
try below method:-
try
{
JSONObject j = new JSONObject("your json response");
JSONArray all = j.getJSONArray("all");
for (int i = 0; i < all.length(); i++)
{
JSONObject data = all.getJSONObject(i);
System.out.println("title =>"+data.getString("title"));
JSONArray maps = data.getJSONArray("maps");
for (int k = 0; k < maps.length(); k++)
{
JSONObject data_sec = maps.getJSONObject(k);
System.out.println("name => "+data_sec.getString("name"));
System.out.println("latitude => "+data_sec.getString("latitude"));
System.out.println("longitude => "+data_sec.getString("longitude"));
}
}
}
catch (Exception e)
{
// TODO: handle exception
}
// Try this way,hope this will help you to solve your problem.
#Override
protected Void doInBackground(Void... params) {
// Create an array
arraylist = new ArrayList<HashMap<String, String>>();
// Retrieve JSON Objects from the given URL address
jsonobject = JSONfunctions
.getJSONfromURL("http://10.0.2.2/locations.json");
try {
// Locate the array name in JSON
jsonarray = jsonobject.getJSONArray("all");
for (int i = 0; i < jsonarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
jsonobject = jsonarray.getJSONObject(i);
// Retrieve JSON Objects
map.put("title", jsonobject.getString("title"));
map.put("index", i);
arraylist.add(map);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void args) {
// Locate the listview in listview_main.xml
listview = (ListView) findViewById(R.id.listview);
// Pass the results into ListViewAdapter.java
adapter = new ListViewAdapter(MainActivity.this, arraylist);
// Set the adapter to the ListView
listview.setAdapter(adapter);
// Close the progressdialog
mProgressDialog.dismiss();
listview.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(MainActivity.this, String.valueOf(position), Toast.LENGTH_LONG).show();
// TODO Auto-generated method stub
Intent sendtosecond = new Intent(MainActivity.this, SecondActivity.class);
// Pass all data rank
sendtosecond.putExtra("title", arraylist.get(position).get(MainActivity.TITLE));
sendtosecond.putExtra("index", arraylist.get(position).get(MainActivity.INDEX));
Log.d("Tapped Item::", arraylist.get(position).get(MainActivity.TITLE));
Log.d("Tapped Item Index::", arraylist.get(position).get(MainActivity.INDEX));
startActivity(sendtosecond);
}
});
}
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get the view from listview_main.xml
setContentView(R.layout.listview_main);
Intent in = getIntent();
strReceived = in.getStringExtra("title");
strReceivedIndex = in.getStringExtra("index");
Log.d("Received Data::", strReceived);
// Execute DownloadJSON AsyncTask
new DownloadJSON().execute();
}
// DownloadJSON AsyncTask
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
// Create an array
arraylist = new ArrayList<HashMap<String, String>>();
// Retrieve JSON Objects from the given URL address
jsonobject = JSONfunctions
.getJSONfromURL("http://10.0.2.2/locations.json");
try {
// Locate the array name in JSON
jsonarray = jsonobject.getJSONArray("all").getJSONObject(Integer.parseInt(strReceivedIndex)).getgetJSONArray("maps");
for (int i = 0; i < jsonarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
jsonobject = jsonarray.getJSONObject(i);
// Retrieve JSON Objects
map.put("title", jsonobject.getString("title"));
arraylist.add(map);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
Related
I have created a Recycler view that is supposed to be created when the activity is created. Currently, when I click a button on my MainActivity, an intent launches the ListActivity which has my recyclerview but it doesn't load. I have used toast message to confirm that each method is getting called, and that I am getting the correct data from the API. If I reset the activity using the restart activity option in Android Studio the Recycler shows up and functions correctly. I don't know what I'm doing wrong.
Here is my ListActivity:
private RecyclerView myrecyclerview;
private RecyclerView.Adapter myadapter;
private RecyclerView.LayoutManager mylayoutmanager;
static RequestQueue listqueue;
static final private String url = "https://swapi.dev/api/people/";
static ArrayList<RecyclerItem> list = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
getSupportActionBar().hide();
listqueue = Volley.newRequestQueue(this);
myrecyclerview = findViewById(R.id.characterlist);
myadapter = new MyAdapter(list, this);
myrecyclerview.setAdapter(myadapter);
myrecyclerview.setHasFixedSize(true);
mylayoutmanager = new LinearLayoutManager(getApplicationContext());
myrecyclerview.setLayoutManager(mylayoutmanager);
parseJsonData();
}
public void parseJsonData(){
JsonObjectRequest request = new JsonObjectRequest(
Request.Method.GET,
url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Toast.makeText(getApplicationContext(), response.toString(), Toast.LENGTH_SHORT).show();
try {
JSONArray jsonarray = response.getJSONArray("results");
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject jsonobject = jsonarray.getJSONObject(i);
String name = jsonobject.getString("name");
String height = jsonobject.getString("height");
String mass = jsonobject.getString("mass");
String eyecolor = jsonobject.getString("eye_color");
String birthyear = jsonobject.getString("birth_year");
//list.add(new RecyclerItem("darth vader", "200", "128", "1950", "red"));
list.add(new RecyclerItem(name, "Height: " + height, "Mass: " + mass, "Birth Year: " + birthyear, eyecolor));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
listqueue.add(request);
}
#Override
public void onCharacterClick(int position) {
String color = list.get(position).getEyecolor();
Toast.makeText(getApplicationContext(), color, Toast.LENGTH_SHORT).show();
}
} ```
Like I mentioned, once I reload the activity, it works correctly. But I want the recycler view to show when I navigate to the activity.
The problem is that the first time that the activity is create, list is empty and parseJsonData() is running on the background filling that list.
Once you reload the activiy, the list and adapter are filled therefore when you call
myadapter = new MyAdapter(list, this);
myrecyclerview.setAdapter(myadapter);
myrecyclerview.setHasFixedSize(true);
mylayoutmanager = new LinearLayoutManager(getApplicationContext());
myrecyclerview.setLayoutManager(mylayoutmanager);
the recycler view is show. Try to do this on your parseJsonData(); after the loop ends, then create the adapter and show the rv
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject jsonobject = jsonarray.getJSONObject(i);
....
}
myadapter = new MyAdapter(list, this);
....
myrecyclerview.setLayoutManager(mylayoutmanager);
I hope it help for u
Creat a List
private List< TipsList > tipsLists = new ArrayList<>();
SET UP RECYCLERVIEW LIKE THIS
RecyclerView tipsRv = findViewById(R.id.tips_rv);
TipsAdapter adapter = new TipsAdapter(tipsLists, this);
tipsRv.setAdapter(adapter);
tipsRv.setHasFixedSize(true);
tipsRv.setLayoutManager(new LinearLayoutManager(this));
getDATA
public void getWallis() {
String myJSONStr = method.loadJSON();
try {
JSONObject ROOT_OBJ = new JSONObject(myJSONStr);
JSONArray MAIN_ARRAY = ROOT_OBJ.getJSONArray("ff_api");
JSONObject TIPS_OBJ = MAIN_ARRAY.getJSONObject(3);
JSONArray TIPS_ARRAY = TIPS_OBJ.getJSONArray("Tips");
for (int i = 0; i < TIPS_ARRAY.length(); i++) {
TipsList tipsList = new TipsList();
JSONObject jsonObject = TIPS_ARRAY.getJSONObject(i);
tipsList.setId(jsonObject.getInt("id"));
tipsList.setTipsTitle(jsonObject.getString("tipsTitle"));
tipsList.setTipsDec(jsonObject.getString("tipsDec"));
tipsLists.add(tipsList);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
I want to parse a JSON file with nested arrays and objects, and use the parsed info to populate a spinner.
Now I'm stuck in the progress window, only showing "loading"...I only want to extract the name tag (navn) to the spinner, and nsrID stored in a variable, for later use.
JSON format:
[
{
"nsrId": "1018038",
"koordinatLatLng": [
59.6908,
9.04228
],
"navn": "Gransherad barnehage",
"fylkesnummer": "08",
"kommunenummer": "0807",
"alder": "1 - 5",
"eierform": "Kommunal",
"antallBarn": 26
},
{
"nsrId": "1012983",
"koordinatLatLng": [
59.5763,
9.19806
],
"navn": "Trolldalen Gårdsbarnehage",
"fylkesnummer": "08",
"kommunenummer": "0807",
"alder": "1 - 5",
"eierform": "Privat",
"antallBarn": 24
},
etc...
My code:
spinner = findViewById(R.id.barneHage_Spinner);
hentJSON();
}
private void hentJSON() {
showSimplProgressDialog(this, "loading...", "Henter Json", false);
StringRequest stringRequest = new StringRequest(Request.Method.GET, barnehager_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("strrrrr", ">>" + response);
try {
JSONObject obj = new JSONObject(response);
barnehageArrayList = new ArrayList<>();
JSONArray dataArray = obj.getJSONArray("navn");
for (int i = 0; i < dataArray.length(); i++) {
Barnehage model = new Barnehage();
JSONObject dataobj = dataArray.getJSONObject(i);
model.setNavn(dataobj.getString("navn"));
// model.setNsrId(dataArray.getNsrId(Integer.parseInt("nsrId")));
barnehageArrayList.add(model);
}
for (int i = 0; i < barnehageArrayList.size(); i++) {
names.add(barnehageArrayList.get(i).getNavn());
}
ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(BarneHager.this, simple_spinner_item, names);
spinner.setAdapter(spinnerArrayAdapter);
removeSimpleProgressDialog();
} catch (JSONException e) {
e.printStackTrace();
}
}
I expect the output to be a spinner with the only values showing
1: Gransherad barnehage
2: Trolldalen Gårdsbarnehage
3: ..
4: ..
etc
I think you were wrong when getting JSON array by JSONArray dataArray = obj.getJSONArray("navn").
Let try using this code:
#Override
public void onResponse (String response) {
try {
JSONArray dataArray = new JSONArray(response);
for (int i = 0; i < dataArray.length(); i++) {
JSONObject dataobj = dataArray.getJSONObject(i);
You have to add an item at zero position of your list
barnehageArrayList.add(0,new MODELCLASS("Select option"))
And add below code to populate your Spinner
SPINNER_NAME.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if (position != 0) {
} else {
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
I am just starting to learn java and Android , Ia m trying to parse json data and apply the data to recyclerview but i am not able to do it. here is my code
public void JSON_DATA_WEB_CALL(){
jsonArrayRequest = new JsonArrayRequest(GET_JSON_DATA_HTTP_URL,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
progressBar.setVisibility(View.INVISIBLE);
JSON_PARSE_DATA_AFTER_WEBCALL(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue = Volley.newRequestQueue(this);
requestQueue.add(jsonArrayRequest);
}
public void JSON_PARSE_DATA_AFTER_WEBCALL(JSONArray array){
for(int i = 0; i<array.length(); i++) {
GetDataAdapter GetDataAdapter2 = new GetDataAdapter();
JSONObject json = null;
try {
json = array.getJSONObject(i);
GetDataAdapter2.setImageTitleNamee(json.getString(JSON_IMAGE_TITLE_NAME));
//GetDataAdapter2.setImageServerLarger(json.getString(JSON_IMAGE_LARGER));
GetDataAdapter2.setImageServerUrl(json.getString(JSON_IMAGE_URL));
GetDataAdapter2.setMrp_price(json.getString(JSON_MRP_PRICE));
GetDataAdapter2.setDisc_price(json.getString(JSON_DISC_PRICE));
} catch (JSONException e) {
e.printStackTrace();
}
GetDataAdapter1.add(GetDataAdapter2);
}
recyclerViewadapter = new RecyclerViewAdapter(GetDataAdapter1, this);
recyclerView.setAdapter(recyclerViewadapter);
}
And here is my JSON Response
{"118":{"garment_color":"Blue","garment_name":"skjhkds","garment_price":"232"},"119":{"garment_color":"hjsadjjs","garment_name":"sdasd","garment_price":"23478"}}
Please someone give a brief explanation of the correct code. it would be very helpful. Thanks
rvAdapter = new RvAdapter(getActivity());
recyclerview.setAdapter(rvAdapterHScode);
rvAdapter.set(responce.getcodes());
recyclerview.setLayoutManager(new GridLayoutManager(getActivity(), 3));
then in adapter
accept the set values
or
call your response inside the recyclerview adapter
like this way
your jsonArray should be in following way:
{
"jArray": [{
"id": "118",
"garment_color": "Blue",
"garment_name": "skjhkds",
"garment_price": "232"
},
{
"id": "119",
"garment_color": "hjsadjjs",
"garment_name": "sdasd",
"garment_price": "23478"
}
]
}
then read that json like this way:
// Getting JSON Array node
JSONArray contacts = jsonObj.getJSONArray("jArray");
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
try {
GetDataAdapter2.setImageTitleNamee(c.getString("garment_name"));
GetDataAdapter2.setMrp_price(c.getString("garment_price"));
} catch (JSONException e) {
e.printStackTrace();
}
GetDataAdapter1.add(GetDataAdapter2);
}
recyclerViewadapter = new RecyclerViewAdapter(GetDataAdapter1, this);
recyclerView.setAdapter(recyclerViewadapter);
public class FindPlaces extends AppCompatActivity {
private static final String MAP_API_URL = "https://api.foursquare.com/v2/venues/categories?client_id=AW31XQWUOLJWFZCFNZZ04I4IQFUFYIFAFDEHEYITEBBDHIVB&client_secret=R10S3ACA5VFOTGVG2LW1N4YONU30LQ3IE0DKIG1JNHN2QNWE&v=20170811&m=foursquare";
JSONObject jsonobject;
JSONArray jsonarray;
ProgressDialog mProgressDialog;
ArrayList<String> categoriesList;
ArrayList<Categories> categories;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_find_places);
new DownloadJSON().execute();
}
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
// Locate the Categories Class
categories = new ArrayList<Categories>();
// Create an array to populate the spinner
categoriesList = new ArrayList<String>();
// JSON file URL address
jsonobject = JSONfunctions
.getJSONfromURL("https://api.foursquare.com/v2/venues/categories?client_id=CONSUMER_KEY&client_secret=CONSUMER_SECRET&v=20170811&m=foursquare");
try {
// Locate the NodeList name
jsonarray = jsonobject.getJSONArray("categories");
for (int i = 0; i < jsonarray.length(); i++) {
jsonobject = jsonarray.getJSONObject(i);
Categories cat = new Categories();
cat.setName(jsonobject.optString("name"));
categories.add(cat);
// Populate spinner with country names
categoriesList.add(jsonobject.optString("name"));
}
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void args) {
// Locate the spinner in activity_main.xml
Spinner mySpinner = (Spinner) findViewById(R.id.spinnerCategories);
// Spinner adapter
mySpinner
.setAdapter(new ArrayAdapter<String>(FindPlaces.this,
android.R.layout.simple_spinner_dropdown_item,
categoriesList));
// Spinner on item click listener
mySpinner
.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0,
View arg1, int position, long arg3) {
// TODO Auto-generated method stub
// Locate the textviews in activity_main.xml
TextView txtname = (TextView) findViewById(R.id.tvName);
txtname.setText(categories.get(position).getName());
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}
}
This is my class to inflate the spinner.
public class JSONfunctions {
public static JSONObject getJSONfromURL(String url) {
InputStream is = null;
String result = "";
JSONObject jArray = null;
// Download JSON data from URL
try {
HttpClient httpclient = new DefaultHttpClient();
HttpGet httppost = new HttpGet(url);
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {
Log.e("log_tag", "Error in http connection " + e.toString());
}
// Convert response to string
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();
result = sb.toString();
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
try {
jArray = new JSONObject(result);
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
return jArray;
}
}
This is where i handle with the http request
{ "response": {
"categories": [
{
"id": "4d4b7104d754a06370d81259",
"name": "Arts & Entertainment",
"pluralName": "Arts & Entertainment",
"shortName": "Arts & Entertainment",
"icon": {
"prefix": "https://ss3.4sqi.net/img/categories_v2/arts_entertainment/default_",
"suffix": ".png"
},
"categories": [
{
"id": "56aa371be4b08b9a8d5734db",
"name": "Amphitheater",
"pluralName": "Amphitheaters",
"shortName": "Amphitheater",
"icon": {
"prefix": "https://ss3.4sqi.net/img/categories_v2/arts_entertainment/default_",
"suffix": ".png"
}
and this is the json.
How can i change to get request instead a post request?
and how can i populate my spinner?
Thanks in advance.
In Activity B there has a spinner where the data were get from MySQL (Table location).
Activity B
private ArrayList<String> froms;
private JSONArray resultFrom;
public void addItemsOnFrom() {
travelFrom = (Spinner) findViewById(R.id.travelFrom);
StringRequest stringRequest = new StringRequest(Configs.FROM_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
JSONObject j = null;
try {
//Parsing the fetched Json String to JSON Object
j = new JSONObject(response);
//Storing the Array of JSON String to our JSON Array
resultFrom = j.getJSONArray(Configs.JSON_ARRAY);
//Calling method getStudents to get the students from the JSON Array
getFrom(resultFrom);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
//Creating a request queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
//Adding request to the queue
requestQueue.add(stringRequest);
}
private void getFrom(JSONArray j) {
//Traversing through all the items in the json array
for (int i = 0; i < j.length(); i++) {
try {
//Getting json object
JSONObject json = j.getJSONObject(i);
//Adding the name of the student to array list
froms.add(json.getString(Configs.TAG_LOCATION));
} catch (JSONException e) {
e.printStackTrace();
}
}
//Setting adapter to show the items in the spinner
travelFrom.setAdapter(new ArrayAdapter<String>(Add_Details_Information.this, android.R.layout.simple_spinner_dropdown_item, froms));
}
When save button is clicked, it will return the selected value(OFFICE) to Activity A listView. And in Activity A, when the list is pressed, it will intent to Activity B. In this time, the spinner in Activity B will display the selected item first(OFFICE).
**Table location** // table location has 2 data
NONE
OFFICE
Assume OFFICE is selected in B. When list is clicked, I want OFFICE display first in spinner B.
Code in Activity B for display OFFICE first.
if(getIntent().getExtras()!=null)
{
final String from = getIntent().getStringExtra("from");
selectedItemFrom(from);
}
public void selectedItemFrom(final String value)// display OFFICE first
{
travelFrom = (Spinner) findViewById(R.id.travelFrom);
StringRequest stringRequest = new StringRequest(Configs.FROM_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
JSONObject j = null;
try {
//Parsing the fetched Json String to JSON Object
j = new JSONObject(response);
//Storing the Array of JSON String to our JSON Array
result = j.getJSONArray(Configs.JSON_ARRAY);
//Calling method getStudents to get the students from the JSON Array
getFrom(result, value);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
//Creating a request queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
//Adding request to the queue
requestQueue.add(stringRequest);
}
private void getFrom(JSONArray j, String value) {
int position = 0;
//Traversing through all the items in the json array
for (int i = 0; i < j.length(); i++) {
try {
//Getting json object
JSONObject json = j.getJSONObject(i);
//Adding the name of the student to array list
froms.add(json.getString(Configs.TAG_LOCATION));
if (froms.get(i).equalsIgnoreCase(value)) {
position = i;
//Toast.makeText(getApplicationContext(),position+"",Toast.LENGTH_LONG).show();
break;
}
} catch (JSONException e) {
e.printStackTrace();
}
}
travelFrom.setAdapter(new ArrayAdapter<String>(Add_Details_Information.this, android.R.layout.simple_spinner_dropdown_item, froms));
travelFrom.setSelection(position);
}
The OFFICE can display first, but the problem is when I checked the spinner B, it shows NONE,OFFICE,NONE OFFICE ..Why the spinner data will get duplicated ? Thanks
I think problem is in this line travelFrom.setAdapter(new ArrayAdapter<String>(Add_Details_Information.this, android.R.layout.simple_spinner_dropdown_item, froms));...But how to solve??? Anyone?
And sometimes the spinner will display the selected item first but sometimes it will not...What are the better way to write?
Edit
{"result":[{"name":"NONE"},{"name":"OFFICE"}]}
I put forms.clear in beginning of both getFrom method now. But the problem is when I select NONE and return to A, then goes to B again,the spinner now has NONE only...
Please try something like this.
This activity will expect a Intent with the key "from" that is set to either "NONE" or "OFFICE". If the intent does not have the data, then it will default to whatever was inserted into the Spinner first.
public class MainActivity extends AppCompatActivity {
private Spinner travelFrom;
private ArrayAdapter<String> mSpinnerAdapter;
private List<String> mSpinnerData;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String from = null;
Bundle extras = getIntent().getExtras();
if (extras != null) {
from = extras.getString("from");
}
setupFromSpinner(from);
}
private void setupFromSpinner(final String value) {
travelFrom = (Spinner) findViewById(R.id.travelFrom);
mSpinnerData = new ArrayList<String>();
mSpinnerAdapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_spinner_item, mSpinnerData);
mSpinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
travelFrom.setAdapter(mSpinnerAdapter);
JsonObjectRequest req = new JsonObjectRequest(Configs.FROM_URL,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
mSpinnerData.clear();
try {
JSONArray resultFrom = response.getJSONArray("result");
for (int i = 0; i < resultFrom.length(); i++) {
JSONObject fromObj = resultFrom.getJSONObject(i);
String name = fromObj.getString("name");
mSpinnerData.add(name);
}
mSpinnerAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
if (value != null) {
int position = mSpinnerAdapter.getPosition(value);
travelFrom.setSelection(position);
} else {
travelFrom.setSelection(0);
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}
);
//Creating a request queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
//Adding request to the queue
requestQueue.add(req);
}
}
add froms.clear() to this piece of code;
private void getFrom(JSONArray j) {
//Traversing through all the items in the json array
froms.clear();
for (int i = 0; i < j.length(); i++) {
try {
//Getting json object
JSONObject json = j.getJSONObject(i);
//Adding the name of the student to array list
froms.add(json.getString(Configs.TAG_LOCATION));
} catch (JSONException e) {
e.printStackTrace();
}
}
//Setting adapter to show the items in the spinner
travelFrom.setAdapter(new ArrayAdapter<String>(Add_Details_Information.this, android.R.layout.simple_spinner_dropdown_item, froms));
}