I am using two spinners in my application one is for 'username' and second spinner for 'course'.
Still now i did load data from MySQL database and assign to spinner, its works fine! When i click on submit button in my application i want to sent those details to MySQL db.
Declaring an Spinner
private Spinner spinner2, spinner1;
//An ArrayList for Spinner Items
private ArrayList<String> students1;
private ArrayList<String> students2;
//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_d1);
//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);
// spinner1.setOnItemSelectedListener(this);
//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();
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
/* switch (view.getId()){
case R.id.spinner1:
getData1();
break;
case R.id.spinner2:
getData2();
break;
}*/
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
if (spinner1.getId() == R.id.spinner1) {
//do this
textViewName1.setText("");
} else if (spinner2.getId() == R.id.spinner2) {
//do this
textViewName2.setText("");
}
}
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_d2.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_d2.this, android.R.layout.simple_spinner_dropdown_item, students2));
}
}
Related
I have a spinner on activity a, the spinner values is taken from a table inside database. When a user select the value from the spinner the value will be saved into same database but different table.
Then there is a button to next activity, on the next activity there is another spinner but I need the spinner selection value to display what I have selected on previous activity.
Android Code:
String text;
String url = "http:///10.92.5.51/test/get.php";
String spinURL = "http://10.92.5.51/test/getSpin.php";
private JSONArray result;
private ArrayList<String> districts;
private ArrayList<Integer> position;
Spinner spinex;
TextView spintext;
Button uploadBtn;
Integer r;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
districts = new ArrayList<String>();
spinex = (Spinner) findViewById(R.id.spiner);
spintext = findViewById(R.id.spinText);
uploadBtn = findViewById(R.id.btnUpload);
getData();
spinex.post(new Runnable() {
#Override
public void run() {
spinex.setSelection(4);
}
});
getPosition();
}
private void getData() {
StringRequest stringRequest = new StringRequest(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("result");
getDistrict(result);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
//Creating a request queue
MySingleton.getInstance(this).addToRequestQueue(stringRequest);
}
private void getPosition() {
StringRequest stringRequest = new StringRequest(spinURL,
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("result");
getSpinPosition(result);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
//Creating a request queue
MySingleton.getInstance(this).addToRequestQueue(stringRequest);
}
private void getDistrict(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
districts.add(json.getString("city_name"));
} catch (JSONException e) {
e.printStackTrace();
}
}
spinex.setAdapter(new ArrayAdapter<String>(Main2Activity.this, android.R.layout.simple_spinner_dropdown_item, districts));
}
private void getSpinPosition(JSONArray j) {
//Traversing through all the items in the json array
try {
//Getting json object
JSONObject json = j.getJSONObject(1);
//Adding the name of the student to array list
r = Integer.valueOf(json.getString("city_id"));
} catch (JSONException e) {
e.printStackTrace();
}
}
Here is the php code:
<?php
require_once('DBConnect.php');
$sql = "select * from city ORDER BY city_id ASC";
$res = mysqli_query($con,$sql);
$result = array();
while($row = mysqli_fetch_array($res)){
array_push($result,
array(
'city_id'=>$row['city_id'],
'city_name'=>$row['city_name'],
)
);
}
echo json_encode(array("result"=>$result));
mysqli_close($con);
I am trying to fetch data from server into my spinner but its not showing any item in spinner , and i am not getting any logcat error also..i have taken this from 1 example , in my json output i want to fetch only name of country ..but its not showing anything:
this is my java class:
pmcountry = (Spinner) findViewById(R.id.country);
//citySpinner = (Spinner) findViewById(City);
//locationSpinner = (Spinner) findViewById(R.id.Location);
pmcountry .setOnItemSelectedListener(this);
country_list = new ArrayList<String>();
//location_list = new ArrayList<String>();
// city_list = new ArrayList<String>();
getData();
}
private void getData(){
StringRequest stringRequest = new StringRequest(Config.DATA_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
JSONObject j = null;
try {
Log.d("Test",response);
JSONArray result = new JSONArray(response);
//Calling method getCountry to get the Country from the JSON Array
getCountry(result);
} catch (JSONException e) {
e.printStackTrace();
}
}
},new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}});
RequestQueue requestQueue = Volley.newRequestQueue(this);
//Adding request to the queue
requestQueue.add(stringRequest);
}
private void getCountry(JSONArray jsonArrayCountry){
//Traversing through all the items in the json array
List<Country> countries = new ArrayList<>();
try {
String country_name, country_code;
JSONObject countries_object;
for (int i = 0; i < jsonArrayCountry.length(); i++) {
countries_object = jsonArrayCountry.getJSONObject(i);
country_code = countries_object.getString("id");
country_name = countries_object.getString("Name");
countries.add(new Country(country_code, country_name));
}
/*ArrayAdapter countryAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_dropdown_item, countries);
pmcountry.setPrompt("--Select Country--");
pmcountry.setAdapter(countryAdapter);
pmcountry.setAdapter(new NothingSelectedSpinnerAdapter(countryAdapter,
R.layout.contact_spinner_row_nothing_selected,this));*/
pmcountry.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
} catch (JSONException e) {
}
}
You are trying to set the list of Custom Objects List<Country>
By default array adapter takes list of String. List<String>.
You have to tweak your code to set List of Custom objects in spinner.
Android: How to bind spinner to custom object list?
This should solve your problem.
Uncomment your , You are not setting data to spinner anywhere..
ArrayAdapter countryAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_dropdown_item, countries);
pmcountry.setPrompt("--Select Country--");
pmcountry.setAdapter(countryAdapter);
pmcountry.setAdapter(new NothingSelectedSpinnerAdapter(countryAdapter,
R.layout.contact_spinner_row_nothing_selected,this));
I used two spinners one for 'username' and second for 'course'. I stored it in db, I retrieving spinners data from mysql database its works fine! now i want to select item from spinners, when I click on submit button then selected item should be inserted into a mysql db.please give me php and java code.
//java file
public class MainActivity_d3 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_d1);
//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);
// spinner1.setOnItemSelectedListener(this);
mBtnSave=(Button)findViewById(R.id.button2);
mBtnSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String str_spinner1 = spinner1.getSelectedItem().toString();
String str_spinner2 = spinner2.getSelectedItem().toString();
}
});
//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();
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if(spinner1.getId()==R.id.spinner1) {
str_spinner1 = spinner1.getSelectedItem().toString();
}
else if(spinner2.getId()==R.id.spinner2)
{
str_spinner2 = spinner2.getSelectedItem().toString();
}
/* switch (view.getId()){
case R.id.spinner1:
getData1();
break;
case R.id.spinner2:
getData2();
break;
}*/
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
if (spinner1.getId() == R.id.spinner1) {
//do this
textViewName1.setText("");
} else if (spinner2.getId() == R.id.spinner2) {
//do this
textViewName2.setText("");
}
}
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_d3.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_d3.this, android.R.layout.simple_spinner_dropdown_item, students2));
}
}
Here,I already fetched data from mysql db and this data shows into the spinner Now the problem is, I want to save spinner selected item into mysql database with different table, the item which i select from spinner it should save to database, how can i do this? By using php mysql i insert record into spinner and i want to update the records of register table with spinner selected item.Can i update the register table with spinner selected item values? please suggest me.
java file
public class MainActivity_d3 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_d1);
//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) {
/*if(spinner1.getId()==R.id.spinner1) {
textViewName1.setText(getName(position));
}
else if(spinner2.getId()==R.id.spinner2)
{
textViewName2.setText(getCourse(position));
}
/* switch (view.getId()){
case R.id.spinner1:
getData1();
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_d3.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_d3.this, android.R.layout.simple_spinner_dropdown_item, students2));
}
}
//InsertActivity
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://mangoair.in/Spinner/insert_s1.php" + data;
// link = "http://hostogen.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");
if (query_result.equalsIgnoreCase("SUCCESS")) {
Toast.makeText(context, "Data inserted successfully. Signup successfully.", Toast.LENGTH_LONG).show();
} else if (query_result.equalsIgnoreCase("FAILURE")) {
Toast.makeText(context, "Data could not be inserted, fill all records.", Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Get the value from the spinner as a string and just pass this string like a normal string
I want to display person details from reg_farmer table.. If i select an item from the spinner, i want to display the corresponding data matches with that item from the database.
Here is my android MainActivity.class file..
public class MainActivity extends AppCompatActivity {
//Declaring an Spinner
private Spinner spinner,spinner2;
//An ArrayList for Spinner Items
private ArrayList<String> states;
private ArrayList<String> district;
//JSON Array
private JSONArray States;
private JSONArray District;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Initializing the ArrayList
states = new ArrayList<String>();
district = new ArrayList<String>();
//Initializing Spinner
spinner = (Spinner) findViewById(R.id.spinner);
spinner2 = (Spinner) findViewById(R.id.spinner2);
//Adding an Item Selected Listener to our Spinner
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String sid="";
try {
//Getting object of given index
JSONObject json = States.getJSONObject(position);
//Fetching id from that object
sid = json.getString("id");
} catch (JSONException e) {
e.printStackTrace();
}
getDistrict(sid);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
Toast.makeText(MainActivity.this,"Nothing Selected",Toast.LENGTH_SHORT).show();
}
});
spinner2.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String Dname="";
try {
//Getting object of given index
JSONObject json = District.getJSONObject(position);
//Fetching name from that object
Dname = json.getString("dname");
} catch (JSONException e) {
e.printStackTrace();
}
Toast.makeText(MainActivity.this,Dname,Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
Toast.makeText(MainActivity.this,"Empty",Toast.LENGTH_SHORT).show();
}
});
//This method will fetch the States data from the URL
getStates();
}
private void getStates(){
//Creating a string request
StringRequest stringRequest = new StringRequest(Request.Method.POST,Config.DATA_State,
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
States = j.getJSONArray("States");
for(int i=0;i< States.length();i++){
try {
//Getting json object
JSONObject state = States.getJSONObject(i);
//Adding the name of the state to array list
MainActivity.this.states.add(state.getString("name"));
} catch (JSONException e) {
e.printStackTrace();
}
}
//Setting adapter to show the items in the spinner
spinner.setAdapter(new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_spinner_dropdown_item, states));
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this,error.toString(),Toast.LENGTH_LONG).show();
}
});
//Creating a request queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
//Adding request to the queue
requestQueue.add(stringRequest);
}
private void getDistrict(final String sid){
//Creating a string request
StringRequest dRequest = new StringRequest(Request.Method.POST,Config.DATA_District,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
JSONObject j = null;
try {
//Parsing the fetched Json String to JSON Object
Log.i("tagconvertstr", "[" + response + "]");
j = new JSONObject(response);
boolean error = j.getBoolean("error");
// Check for error node in json
if (!error) {
//Storing the Array of JSON String to our JSON Array
District = j.getJSONArray("District");
//Toast.makeText(MainActivity.this, District.toString(), Toast.LENGTH_SHORT).show();
district.removeAll(district);
for (int i = 0; i < District.length(); i++) {
try {
//Getting json object
JSONObject dist = District.getJSONObject(i);
//Adding the name of the district to array list
MainActivity.this.district.add(dist.getString("dname"));
} catch (JSONException e) {
e.printStackTrace();
}
}
//Setting adapter to show the items in the spinner
spinner2.setAdapter(new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_spinner_dropdown_item, district));
}else {
String errorMsg = j.getString("error_msg");
Toast.makeText(MainActivity.this,
errorMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this,error.toString(),Toast.LENGTH_LONG).show();
}
}){
#Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<String, String>();
params.put("state_id", sid);
return params;
}
};
//Creating a request queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
//Adding request to the queue
requestQueue.add(dRequest);
}
}
Here is my Config.java file.. In this file i give the url for fetching spinner items..
public class Config {
//JSON URL
public static final String DATA_State = "http://10.0.3.2/cof/state.php";
public static final String DATA_District = "http://10.0.3.2/cof/district.php";
}
I want to display the details like this.. I want to view code,name and mobile number of the person when i choose the district and state from the spinner
I guess you are trying to communicate with a local database. Getting data from an eternal database requires 3 steps.
Creating your database - it can be local using services like wamp or it can be present on actual server.
Creating webservice - In this step you need to create a Webservice which interacts with your database and responds to your android code. It includes making of config. php file which stores your server & database information, then you have your actual anyname.php file which include config.php file, the code to get the data from database and to respond back to android app.
Calling webservice from android - In this step you actually call the webservice from your code to retrieve data from it.
Now as we can see from your provided code. You might have completed most or all of these steps. According to me you have your database ready. You have shown the config folder with two php files which shows that you have your php files ready.
Now to debug, first try to open the links in your browser and see if you get any result. If you get the information correctly then it means that you have placed the files correctly. Now try to print the result of volley in logcat to see if you have the data in your app. If everything works fine then you only have to handle spinner listener. If any of these steps fail, tell us about it.
First you have to retrieve all the data then adding them to an array list so you could get the info again,
You can look at that example it does what you want exactly ,
private void retrieveJSON() {
StringRequest stringRequest = new StringRequest(
Request.Method.GET,
URLstring,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("strrrrr", ">>" + response);
try {
JSONObject obj = new JSONObject(response);
goodModelArrayList = new ArrayList<>();
JSONArray dataArray = obj.getJSONArray("data");
for (int i = 0; i < dataArray.length(); i++) {
PMenus playerModel = new PMenus();
JSONObject dataobj = dataArray.getJSONObject(i);
playerModel.setName(dataobj.getString("name"));
playerModel.setCountry(dataobj.getString("country"));
playerModel.setCity(dataobj.getString("city"));
playerModel.setImgURL(dataobj.getString("imgURL"));
goodModelArrayList.add(playerModel);
}
for (int i = 0; i < goodModelArrayList.size(); i++){
names.add(goodModelArrayList.get(i).getName().toString());
}
ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(AddPatient.this, simple_spinner_item, names);
spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // The drop down view
PmSpinner.setAdapter(spinnerArrayAdapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//displaying the error in toast if occurrs
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
// request queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
Now after adding the data into an array you can use this method
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String item = parent.getItemAtPosition(position).toString() ;
String city = goodModelArrayList.get(position).getCity().toString() ;
String country = goodModelArrayList.get(position).getCountry().toString() ;
testnotes.setText(item);
testno.setText(city);
testprice.setText(country);
}
and ofcourse don't forget to add this line in you onCreate
goodModelArrayList = new ArrayList<>();
and define it like that
private ArrayList<PMenus> goodModelArrayList;