Spinners are empty - android

I am trying to populate spinners with data from MySQL (I am having to rows) but they stay empty. Also, those spinners should be dependent on each other. Any ideas why? When I call url in local host it returns right values, so the PHP is working fine(example of one row from PHP: [{"Grad":"Beograd","Predmet":"matematika"}...], I m more worried about putting those rows in a list.
public class IzboraGrada extends Activity {
Spinner spinner1, spinner2;
private Button button,izlaz;
static String str_grad,str_predmet,url;
InputStream is=null;
String result=null;
String line=null;
String[] grad, predmet;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_izbora_grada);
spinner1=(Spinner) findViewById(R.id.spinner1);
spinner2=(Spinner) findViewById(R.id.spinner2);
final List<String> list1=new ArrayList<String>();
final List<String> list2=new ArrayList<String>();
Button b=(Button) findViewById(R.id.button);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
try
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://192.168.1.14/test/spinner1.php");
HttpResponse response = httpclient.execute(httppost);
Log.e("Fail 1", "3");
HttpEntity entity = response.getEntity();
Log.e("Fail 1", "4");
is = entity.getContent();
Log.e("Pass 1", "connection success ");
}
catch(Exception e)
{
Log.e("Fail 1", e.toString());
Toast.makeText(getApplicationContext(), "Invalid IP Address",Toast.LENGTH_LONG).show();
finish();
}
try
{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
is.close();
result = sb.toString();
}
catch(Exception e)
{
Log.e("Fail 2", e.toString());
}
try
{
JSONArray JA=new JSONArray(result);
JSONObject json= null;
grad = new String[JA.length()];
predmet = new String[JA.length()];
for(int i=0;i<JA.length();i++)
{
json=JA.getJSONObject(i);
grad[i] = json.getString("Grad");
predmet[i]=json.getString("Predmet");
}
Toast.makeText(getApplicationContext(), "sss",Toast.LENGTH_LONG).show();
for(int i=0;i<grad.length;i++)
{
list1.add(grad[i]);
list2.add(predmet[i]);
}
spinner_fn();
}
catch(Exception e)
{
Log.e("Fail 3", e.toString());
//login.this.finish();
}
}
});
}
private void spinner_fn() {
// TODO Auto-generated method stub
ArrayAdapter<String> dataAdapter1 = new ArrayAdapter<String>(getApplicationContext(),
android.R.layout.simple_spinner_item, grad);
dataAdapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner1.setAdapter(dataAdapter1);
ArrayAdapter<String> dataAdapter2 = new ArrayAdapter<String>(getApplicationContext(),
android.R.layout.simple_spinner_item, predmet);
dataAdapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner2.setAdapter(dataAdapter2);
spinner1.setOnItemSelectedListener(new OnItemSelectedListener()
{
public void onItemSelected(AdapterView<?> arg0, View arg1,int position, long id)
{
// TODO Auto-generated method stub
spinner2.setSelection(position);
}
#Override
public void onNothingSelected(AdapterView<?> arg0)
{
// TODO Auto-generated method stub
}
});
spinner2.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> arg0, View arg1,int position, long arg3) {
// TODO Auto-generated method stub
spinner1.setSelection(position);
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}
}
And PHP code:
$con = mysqli_connect($host, $user, $pwd, $db);
if(mysqli_connect_errno($con)) {
die("Failed to connect to MySQL: " . mysqli_connect_error());
}
$sql = "SELECT Grad, Predmet FROM lista";
$result = mysqli_query($con, $sql);
$rows = array();
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$rows[] = $row;
}
mysqli_close($con);
echo json_encode($rows);

you aren't populating your spinners, look to a part of your code ;
ArrayAdapter<String> dataAdapter1 = new ArrayAdapter<String>(getApplicationContext(),
dataAdapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
Android is reading it as one line, without valid references to the right data. Please replace it by the following,
// adapter for spinner
ArrayAdapter<String> dataAdapter1 = new ArrayAdapter<String>(getApplicationContext(), $$$, list1);
// set layout
dataAdapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
replace the $$$ to the spinner item-id in your XML layout. Do the same for spinner2

Related

display data in listview from database in asynctask by getting response from server in array

I want to display some data in a listview from database using asynctask.
I want that firstly user inputs some data and on submit button click in doinbackground in asynctask, database checks for result like login something and from there details or response comes from database in the form of array. Now i want that details to be displayed in a listview.
I want the details to be displayed in another activity.
Here is my code:
public class Address extends AppCompatActivity{
Button showRest;
Toolbar toolbar;
String city,location;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.address);
final Spinner spinnercity = (Spinner) findViewById(R.id.cityname);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
R.array.city_name, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnercity.setAdapter(adapter);
spinnercity.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
city = spinnercity.getSelectedItem().toString().trim();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
final Spinner spinnerlocation = (Spinner) findViewById(R.id.citylocation);
ArrayAdapter<CharSequence> adapterloc = ArrayAdapter.createFromResource(this,
R.array.city_location, android.R.layout.simple_spinner_item);
adapterloc.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerlocation.setAdapter(adapterloc);
spinnerlocation.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
location = spinnerlocation.getSelectedItem().toString().trim();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
toolbar = (Toolbar) findViewById(R.id.toolbar_invite);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("");
toolbar.setNavigationIcon(R.drawable.back);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent mainpage = new Intent(Address.this,Open.class);
startActivity(mainpage);
}
});
showRest = (Button)findViewById(R.id.btnshow_rest);
showRest.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
checkInto(city,location);
}
});
}
private void checkInto(final String city, String location) {
class CheckAsync extends AsyncTask<String, Void, String> {
private Dialog loadingDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
loadingDialog = ProgressDialog.show(Address.this, "Please wait", "Loading...");
}
#Override
protected String doInBackground(String... params) {
String city = params[0];
String location = params[1];
InputStream is = null;
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("city", city));
nameValuePairs.add(new BasicNameValuePair("location", location));
String result = null;
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(
RestConfig.DATA_URL);
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
result = sb.toString();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
#Override
protected void onPostExecute(String result){
String s = result.trim();
loadingDialog.dismiss();
if(s.equalsIgnoreCase("success")){
Toast.makeText(Address.this, "Succes", Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(getApplicationContext(), "Not found", Toast.LENGTH_LONG).show();
}
}
}
CheckAsync la = new CheckAsync();
la.execute(city, location);
}
}

Update the second spinner based on first spinner item

i have created the two spinner in xml namely myspinner and myspinner1. The myspinner value is obtained from the json value.Based on myspinner item selected,we get the hotel id.That retrieved hotel id is used to call the another AsyncT1.In the AsyncT1 the myspinner1 value get listed out.My problem is,if i select the myspinner the myspinner1 value is not updated it remains same.I have tried the adapter.notifydatasetchanged() but till now not updated.`
class AsyncT extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
SharedPreferences prefs = getSharedPreferences(MyPREFERENCES, MODE_PRIVATE);
String userID = prefs.getString("userid", null);
System.out.println("userID---"+userID);
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://airbnb.abservetech.com/demo/public/mobile/hotelroom/hotel");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("user_id", userID));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
Log.e("mainToPost", "mainToPost" + nameValuePairs.toString());
/* execute */
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
InputStream inputStream = response.getEntity().getContent();
InputStreamToStringExample str = new InputStreamToStringExample();
responseServer = str.getStringFromInputStream(inputStream);
Log.d("response", "response -----" + responseServer);
//Get the instance of JSONArray that contains JSONObjects
// postData(responseServer);
JSONObject jsonRootObject = new JSONObject(responseServer);
JSONArray jsonArray = jsonRootObject.optJSONArray("Hotel_details");
//Iterate the jsonArray and print the info of JSONObjects
for (int i1 = 0; i1 < jsonArray.length(); i1++) {
try {
JSONObject jsonObject = jsonArray.getJSONObject(i1);
Movie movie = new Movie();
movie.setHotelid1(jsonObject.optString("hotel_id").toString());
movie.setHotelname1(jsonObject.optString("hotel_name").toString());
hotelNames.add(jsonObject.optString("hotel_name").toString());
movieList.add(movie);
System.out.println("movie list" + movieList);
runOnUiThread(new Runnable() {
#Override
public void run() {
Adapter = (new ArrayAdapter<String>(Edit_room.this, android.R.layout.simple_spinner_dropdown_item, hotelNames));
mySpinner.setAdapter(Adapter);
Adapter.notifyDataSetChanged();
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
// Set the text followed by the position
hotelid= (movieList.get(position).getHotelid1());
System.out.println("name--"+hotelid);
new AsyncT1().execute(hotelid);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}
});
}
catch (JSONException e) {
e.printStackTrace();
}
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String aVoid) {
super.onPostExecute(aVoid);
}
}
class AsyncT1 extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
// http://airbnb.abservetech.com/demo/public/mobile/hotelroom/roomid?hotel_id=79
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://airbnb.abservetech.com/demo/public/mobile/hotelroom/show");
SharedPreferences prefs = getSharedPreferences(MyPREFERENCES, MODE_PRIVATE);
String userID = prefs.getString("userid", null);
System.out.println("userID---"+userID);
/*hotel_id&room_type&room_prize&is_active&available_status&adults_count&room_count&room_images&
room_desc&room_name&room_footage&General&Services&Food_Beverages&Outdoors&Activities&
Dining&Media_Entertainment&Kitchen&Others*/
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("hotel_id", hotelid));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
Log.e("mainToPost", "mainToPost" + nameValuePairs.toString());
/* execute */
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
InputStream inputStream = response.getEntity().getContent();
InputStreamToStringExample str = new InputStreamToStringExample();
responseServer = str.getStringFromInputStream(inputStream);
Log.d("response", "viewroomresponse -----" + responseServer);
JSONObject jsonRootObject = new JSONObject(responseServer);
JSONArray jsonArray = jsonRootObject.optJSONArray("view_room_details");
//Iterate the jsonArray and print the info of JSONObjects
for (int i1 = 0; i1 < jsonArray.length(); i1++) {
try {
JSONObject jsonObject = jsonArray.getJSONObject(i1);
Movie movie = new Movie();
// movie.setViewRoomtype(jsonObject.optString("room_type").toString());
movie.setViewRoomprice(jsonObject.optString("room_prize").toString());
movie.setViewIsActive(jsonObject.optString("is_active").toString());
movie.setViewAvailablestatus(jsonObject.optString("available_status").toString());
movie.setViewAdultcount(jsonObject.optString("adults_count").toString());
movie.setViewRoomcount(jsonObject.optString("room_count").toString());
movie.setViewRoomdesc(jsonObject.optString("room_desc").toString());
movie.setViewRoomname(jsonObject.optString("room_name").toString());
movie.setViewRoomfootage(jsonObject.optString("room_footage").toString());
RoomNames.add(jsonObject.optString("room_type").toString());
movieList.add(movie);
runOnUiThread(new Runnable() {
#Override
public void run() {
// ArrayAdapter<String> Adapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1,RoomNames);
// Adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Adapter.notifyDataSetChanged();
// mySpinner1.setAdapter(Adapter);
Adapter1 =(new ArrayAdapter<String>(Edit_room.this, android.R.layout.simple_spinner_dropdown_item, RoomNames));
if(Adapter1!=null){
Adapter1.notifyDataSetChanged();
mySpinner1.setAdapter(Adapter1);
}
else{ mySpinner1.setAdapter(Adapter1);}
mySpinner1.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
// Set the text followed by the position
hotelid= (movieList.get(position).getHotelid1());
room_price.setText(movieList.get(position).getViewRoomprice());
description.setText(movieList.get(position).getViewRoomdesc());
adult_count.setText(movieList.get(position).getViewAdultcount());
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}
});
}
catch (JSONException e) {
e.printStackTrace();
}
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String aVoid) {
super.onPostExecute(aVoid);
}
}
`
Use this link, it might help you.
http://www.javaknowledge.info/populate-second-spinner-based-on-selection-of-first-spinner/

Android: populate second spinner depending on the selection of first spinner

How can I do this: I have 2 Spinners in my app and one is for Departament and other is for Doctor, when I select one department in Departament spinner I want my second spinner to show only the doctor's who belong to that department. I'm using MYSQL Database to fetching data from two different tables. I populate both table with a urlconection. Here is my code:
int id_departament;
String[] nume_doctor = null;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.programare_online, container, false);
sp = (Spinner) view.findViewById(R.id.spinner1);
adapter = new ArrayAdapter<String>(getActivity(), R.layout.spinner1_layout, R.id.txt1, listItems);
sp.setAdapter(adapter);
sp.setFocusable(true);
sp.clearFocus();
sp2 = (Spinner) view.findViewById(R.id.spinner2);
adapter2 = new ArrayAdapter<String>(getActivity(), R.layout.spinner2_layout, R.id.txt2, listItems2);
sp2.setAdapter(adapter2);
sp2.setFocusable(true);
sp2.clearFocus();
return view;
}
this is the BlackTask
private class BackTask extends AsyncTask<Void, Void, Void> {
ArrayList<String> list;
ArrayList<String> list2;
protected void onPreExecute() {
super.onPreExecute();
list = new ArrayList<>();
list2 = new ArrayList<>();
}
protected Void doInBackground(Void... params) {
InputStream is = null;
String result = "";
InputStream is2 = null;
String result2 = "";
so here I open the connection with database
try {
URL url = new URL("http://192.168.1.5/clinicco/departament.php");
urlConnection = (HttpURLConnection) url.openConnection(); //here open the connection with database
urlConnection.connect(); //here connect to database
is = urlConnection.getInputStream(); //here open the stream for reading data from database
URL url2 = new URL("http://192.168.1.5/clinicco/doctori.php");
urlConnection2 = (HttpURLConnection) url2.openConnection();
urlConnection2.connect(); //here connect to database
is2 = urlConnection2.getInputStream(); //here open the stream for reading data from database
} catch (IOException e) {
e.printStackTrace();
}
//convert response to string
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "utf-8"));
String line = null;
while ((line = reader.readLine()) != null) {
result += line;
}
is.close();
BufferedReader reader2 = new BufferedReader(new InputStreamReader(is2, "utf-8"));
String line2 = null;
while ((line2 = reader2.readLine()) != null) {
result2 += line2;
}
is2.close();
//result=sb.toString();
} catch (Exception e) {
e.printStackTrace();
}
// parse json data
try {
JSONArray jArray = new JSONArray(result);
for (int i = 0; i < jArray.length(); i++) {
JSONObject jsonObject = jArray.getJSONObject(i);
//id_departament = jsonObject.getInt("id_departament");
// add departament's name to arraylist
list.add(jsonObject.getString("nume_departament"));
}
JSONArray jArray2 = new JSONArray(result2);
JSONObject jsonObject2=null;
nume_doctor=new String[jArray2.length()];
id_departament = jsonObject2.getInt("id_departament");
for (int i = 0; i < jArray2.length(); i++) {
jsonObject2 = jArray2.getJSONObject(i);
list2.add(jsonObject2.getString("nume_doctor"));
id_departament = jsonObject2.getInt("id_departament");
nume_doctor[i] = jsonObject2.getString("nume_doctor");
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
this is onPostExecute with the OnItemselectedLiSTENER
protected void onPostExecute(Void result) {
listItems.addAll(list);
adapter.notifyDataSetChanged();
listItems2.addAll(list2);
adapter2.notifyDataSetChanged();
sp.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int position, long id) {
// TODO Auto-generated method stu
// sp.getSelectedItem().toString();
int pos = sp.getSelectedItemPosition();
sp2.setSelection(position);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
sp2.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int position, long arg3) {
// TODO Auto-generated method stub
// sp2.getSelectedItem().toString();
sp.setSelection(position);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}
}
public void onStart() {
super.onStart();
BackTask bt = new BackTask();
bt.execute();
}

trouble with adding Spinner in CSipSimple

I'm trying to add spinner in my CSipSimple account registration form. but i'm having error at few lines.
first i'm having error at
accountUserName = (Spinner) findViewById("username");
findViewById is undefined.
Second is at
ArrayAdapter dataAdapter = new ArrayAdapter(this, R.layout.spinner_item, list);
saying Constructor ArrayAdapter is undefined.
this code was working fine in a saperate program but when i tried to put this code in CSipsimple Basic.java file it showed these two errors. can someone please help me?
public class Basic extends BaseImplementation {
protected static final String THIS_FILE = "Basic W";
InputStream is=null;
String result=null;
String line=null;
JSONObject json = null;
private Spinner accountUserName;
private EditTextPreference accountDisplayName;
//private EditTextPreference accountUserName;
private EditTextPreference accountServer;
private EditTextPreference accountPassword;
private void bindFields() {
accountDisplayName = (EditTextPreference) findPreference("display_name");
accountUserName = (Spinner) findViewById("username");
accountServer = (EditTextPreference) findPreference("server");
accountPassword = (EditTextPreference) findPreference("password");
}
public void fillLayout(final SipProfile account) {
bindFields();
accountDisplayName.setText(account.display_name);
//fetching values fro mysql database
String serverFull = account.reg_uri;
if (serverFull == null) {
serverFull = "";
}else {
serverFull = serverFull.replaceFirst("sip:", "");
}
ParsedSipContactInfos parsedInfo = SipUri.parseSipContact(account.acc_id);
//accountUserName.setText(parsedInfo.userName);
try
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://192.168.xx.xxx/conIds.php");
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
Log.e("Pass 1", "connection success ");
}
catch(Exception e)
{
Log.e("Fail 1", e.toString());
Toast.makeText(getApplicationContext(),e.toString(),Toast.LENGTH_LONG).show();
}
try
{
BufferedReader reader = new BufferedReader
(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
is.close();
result = sb.toString();
System.out.println(result);
Log.e("Pass 2", "connection success ");
}
catch(Exception e)
{
Log.e("Fail 2", e.toString());
}
//
try
{
JSONArray NJA=new JSONArray(result);
String arr=NJA.getString(1);
Log.d("My arry", ""+arr);
JSONArray JA=new JSONArray(arr);
final String[] str2 = new String[JA.length()];
for(int i=0;i<JA.length();i++)
{
str2[i] = JA.getString(i);
}
List<String> list = new ArrayList<String>();
for(int i=0;i<str2.length;i++)
{
list.add(str2[i]);
}
Collections.sort(list);
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, R.layout.spinner_item, list);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
accountUserName.setAdapter(dataAdapter);
accountUserName.setOnItemSelectedListener(new OnItemSelectedListener()
{
public void onItemSelected(AdapterView<?> arg0, View arg1,int position, long id)
{
// TODO Auto-generated method stub
String Item=accountUserName.getSelectedItem().toString();
Toast.makeText(getApplicationContext(), Item,Toast.LENGTH_LONG).show();
}
public void onNothingSelected(AdapterView<?> arg0)
{
// TODO Auto-generated method stub
}
});
}
catch(Exception e)
{
Log.e("Fail 3", e.toString());
}
accountServer.setText(serverFull);
accountPassword.setText(account.data);
}
Have you imported android.app.Activity (in which findViewById(int) is defined) and android.widget.ArrayAdapter?

pass the spinner selected value to mysql using php from response in android

Hi In My Application I have two spinners class and section names displaying with date and one submit Button. After click the submit button the class name,section Name,date available in database or not.If Exist I want response from php.
I tested this code by using toast message it showing whatever I selected data displaying.
Can any one please help me how to resolve this issues.
Attendance.class
public class Attendance extends Activity implements OnClickListener {
private EditText fromDateEtxt;
private DatePickerDialog fromDatePickerDialog;
private SimpleDateFormat dateFormatter;
InputStream is = null;
String result = null;
String line = null;
int class_id;
//String className = "";
String sectionName = "";
String[] class_name, section_name;
Spinner classSpinner, sectionSpinner;
private Map<String, Set<String>> classSectionMap = new HashMap<String, Set<String>>();
#TargetApi(Build.VERSION_CODES.GINGERBREAD)
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
}
// Spinner element
classSpinner = (Spinner) findViewById(R.id.spinner);
sectionSpinner = (Spinner) findViewById(R.id.spinner1);
Button submit = (Button) findViewById(R.id.button1);
submit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(AndroidSpinnerExampleActivity.this,
"Result : " +
"\nclassName : "+ String.valueOf(classSpinner.getSelectedItem()) +
"\nSectionName : "+ String.valueOf(sectionSpinner.getSelectedItem()),
Toast.LENGTH_SHORT).show();
}
});
dateFormatter = new SimpleDateFormat("dd-MM-yyyy", Locale.US);
findViewsById();
setDateTimeField();
// Spinner click listener
// spinner.setOnItemSelectedListener(this);
// Spinner Drop down elements
final List<String> list1 = new ArrayList<String>();
final List<String> list2 = new ArrayList<String>();
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(
"http://10.0.2.2/android_connect/getuser.php");
HttpResponse response = httpclient.execute(httppost);
Log.e("Fail 1", "3");
HttpEntity entity = response.getEntity();
Log.e("Fail 1", "4");
is = entity.getContent();
Log.e("Pass 1", "connection success ");
} catch (Exception e) {
Log.e("Fail 1", e.toString());
Toast.makeText(getApplicationContext(), "Invalid IP Address",
Toast.LENGTH_LONG).show();
finish();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
} catch (Exception e) {
Log.e("Fail 2", e.toString());
}
try {
JSONArray JA = new JSONArray(result);
JSONObject json = null;
class_name = new String[JA.length()];
section_name = new String[JA.length()];
String className = "";
String sectionName = "";
Set<String> sections;
for (int i = 0; i < JA.length(); i++) {
json = JA.getJSONObject(i);
// class_name[i] = json.getString("class_name");
// section_name[i]=json.getString("section_name");
className = json.getString("class_name");
sectionName = json.getString("section_name");
//Toast.makeText(getApplicationContext(), "classname"+sectionName, Toast.LENGTH_LONG).show();
if (classSectionMap.containsKey(className)) {
sections = classSectionMap.get(className);
} else {
sections = new HashSet<String>();
//Toast.makeText(getApplicationContext(), "classname"+className, Toast.LENGTH_LONG).show();
}
sections.add(sectionName);
classSectionMap.put(className, sections);
}
Set<String> classKeys = classSectionMap.keySet();
class_name = classKeys.toArray(new String[classKeys.size()]);
Set<String> sectionkeys = classSectionMap.get(class_name[0]);
if (sectionkeys != null) {
section_name = sectionkeys.toArray(new String[sectionkeys
.size()]);
}
/*
* for(int i=0;i<class_name.length;i++) { list1.add(class_name[i]);
* list2.add(section_name[i]);
*
* }
*/
spinner_fn();
} catch (Exception e) {
Log.e("Fail 3", e.toString());
e.printStackTrace();
// login.this.finish();
}
}
private void spinner_fn() {
// TODO Auto-generated method stub
ArrayAdapter<String> dataAdapter1 = new ArrayAdapter<String>(
getApplicationContext(), android.R.layout.simple_spinner_item,
class_name);
dataAdapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
classSpinner.setAdapter(dataAdapter1);
classSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int position, long id) {
Log.e("Position new", class_name[position]);
Set<String> sectionkeys = classSectionMap
.get(class_name[position]);
if (sectionkeys != null) {
section_name = sectionkeys.toArray(new String[sectionkeys
.size()]);
//Toast.makeText(getApplicationContext(), "sectionName"+section_name, Toast.LENGTH_LONG).show();
}
ArrayAdapter<String> dataAdapter2 = new ArrayAdapter<String>(
getApplicationContext(), android.R.layout.simple_spinner_item,
section_name);
dataAdapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sectionSpinner.setAdapter(dataAdapter2);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
sectionSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View arg1,
int position, long arg3) {
// TODO Auto-generated method stub
// spinner.setSelection(position);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}
private void findViewsById() {
fromDateEtxt = (EditText) findViewById(R.id.etxt_fromdate);
fromDateEtxt.setInputType(InputType.TYPE_NULL);
fromDateEtxt.requestFocus();
// toDateEtxt = (EditText) findViewById(R.id.etxt_todate);
// toDateEtxt.setInputType(InputType.TYPE_NULL);
}
private void setDateTimeField() {
fromDateEtxt.setOnClickListener(this);
// toDateEtxt.setOnClickListener(this);
Calendar newCalendar = Calendar.getInstance();
fromDatePickerDialog = new DatePickerDialog(this,
new OnDateSetListener() {
public void onDateSet(DatePicker view, int year,
int monthOfYear, int dayOfMonth) {
Calendar newDate = Calendar.getInstance();
newDate.set(year, monthOfYear, dayOfMonth);
fromDateEtxt.setText(dateFormatter.format(newDate
.getTime()));
}
}, newCalendar.get(Calendar.YEAR),
newCalendar.get(Calendar.MONTH),
newCalendar.get(Calendar.DAY_OF_MONTH));
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
#Override
public void onClick(View view) {
if (view == fromDateEtxt) {
fromDatePickerDialog.show();
}
}
Thanks In Advance

Categories

Resources