Remove Selected Spinner Item In Android - java

I have spinner in my Activity which is set the item from JSON data and when i select any item from spinner and set into the spinner, and i have done all this things properly.But when i want to remove selected item from spinner i got exception:
E/AndroidRuntime(1022): java.lang.UnsupportedOperationException"
and
E/AndroidRuntime(1022):atandroid.widget.ArrayAdapter.remove(ArrayAdapter.java:212)
at the code line of
E/AndroidRuntime(1022):at com.spinnerdemo.SpinDemo$1.onItemSelected(SpinDemo.java:102)
Here is my code:
public class SpinDemo extends Activity {
private static String strUrl = "http://192.168.1.61/jyoti/android_app/all_questions.php";
private static String TAG_ID = "id";
private static String TAG_CODE = "q_prefix";
private static String TAG_CODE_ARR = "Questions";
JSONArray jsonArray = null;
Spinner codeSpinner, spinner2;
EditText edTextSpinnerItem;
String[] items;
String strEdtext;
String strid , strcode ;
ArrayList<String> codeList;
public ArrayAdapter<String> adapter ;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
codeList = new ArrayList<String>();
codeSpinner = (Spinner) findViewById(R.id.spinner2);
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONFromUrl(strUrl);
try
{
jsonArray = json.getJSONArray(TAG_CODE_ARR);
// looping through All Contacts
final String[] items = new String[jsonArray.length()];
for(int i = 0; i < jsonArray.length(); i++)
{
JSONObject c = jsonArray.getJSONObject(i);
// Storing each json item in variable
strid = c.getString(TAG_ID);
strcode = c.getString(TAG_CODE);
items[i] = c.getString(TAG_CODE);
System.out.println("Hello events " + items);
adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item,items);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
codeSpinner.setAdapter(adapter);
}
}
catch (JSONException e) {
e.printStackTrace();
}
codeSpinner.setOnItemSelectedListener(new OnItemSelectedListener()
{
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int pos, long arg3)
{
// TODO Auto-generated method stub
String anyvariable=String.valueOf(codeSpinner.getSelectedItem());
System.out.println("anyvariable = " + anyvariable);
edTextSpinnerItem=(EditText)findViewById(R.id.editText_SpinnerItem);
edTextSpinnerItem.setText(anyvariable);
System.out.println("edTextSpinnerItem " + edTextSpinnerItem);
String t = adapter.getItem(pos);
System.out.println("Get The Item Position From Adapter = " + t);
adapter.remove(t);
adapter.notifyDataSetChanged();
codeSpinner.setAdapter(adapter);
//mySpinner.setAdapter(m_adapterForSpinner);
//adapter.remove((String)codeSpinner.getSelectedItem());
//adapter.notifyDataSetChanged();
//System.out.println("Item is Removed From The Spinner Drop Dwon List");
}
#Override
public void onNothingSelected(AdapterView<?> arg0)
{
// TODO Auto-generated method stub
}
});
}
}

I think that the problem is caused from the deleting an element that is actual selected
Try to use a list instead of an Array for the items:
http://developer.android.com/reference/android/widget/ArrayAdapter.html#ArrayAdapter(android.content.Context,%20int,%20int,%20java.util.List)
Then in the on item selected use
items.remove(t);
Instead of:
adapter.remove(t);
With this change you remove the item from the ArrayList(List) and not from the adapter.
The adapter notifyDataSetChanged capture the change on the List and refresh the spinner

Try this..
1) Give spinner setadapter after for loop
2) If you need to remove any item. You need to use ArrayList it is the easy way.
I Posted code after some changes.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
codeList = new ArrayList<String>();
codeSpinner = (Spinner) findViewById(R.id.spinner2);
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONFromUrl(strUrl);
try
{
jsonArray = json.getJSONArray(TAG_CODE_ARR);
// looping through All Contacts
final String[] items = new String[jsonArray.length()];
for(int i = 0; i < jsonArray.length(); i++)
{
JSONObject c = jsonArray.getJSONObject(i);
// Storing each json item in variable
strid = c.getString(TAG_ID);
strcode = c.getString(TAG_CODE);
items[i] = c.getString(TAG_CODE);
System.out.println("Hello events " + items);
codeList.add(strcode);
}
adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item,codeList);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
codeSpinner.setAdapter(adapter);
}
catch (JSONException e) {
e.printStackTrace();
}
codeSpinner.setOnItemSelectedListener(new OnItemSelectedListener()
{
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int pos, long arg3)
{
// TODO Auto-generated method stub
String anyvariable=String.valueOf(codeSpinner.getSelectedItem());
System.out.println("anyvariable = " + anyvariable);
edTextSpinnerItem=(EditText)findViewById(R.id.editText_SpinnerItem);
edTextSpinnerItem.setText(anyvariable);
System.out.println("edTextSpinnerItem " + edTextSpinnerItem);
String t = adapter.getItem(pos);
System.out.println("Get The Item Position From Adapter = " + t);
Object t2 = adapter.getItem(pos);
Log.v("t2", ""+t2);
codeList.remove(t2);
adapter.notifyDataSetChanged();
}
#Override
public void onNothingSelected(AdapterView<?> arg0)
{
// TODO Auto-generated method stub
}
});
}

Related

Getting data from webservice android studio

I am working on an android application. In this application, I have to retrieve data from a web service and put it in a listview, but it is not retrieving anything. I don't know what I am doing wrong here. Maybe someone can help me with this.
Webservice: http://10.247.240.53/kas/lampen.php
Mainactivity:
`
public class MainActivity extends AppCompatActivity {
ListView listView;
ArrayAdapter<String> adapter;
String[] data;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = findViewById(R.id.listview);
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().permitNetwork().build());
getData();
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(MainActivity.this, Showdata.class);
intent.putExtra("teeltbed", listView.getItemAtPosition(position).toString());
startActivity(intent);
}
});
}
private void getData()
{
String getData = null;
String dbResult = "empty";
dbConnect database = new dbConnect(this);
try{
String query = "SELECT * FROM Lamp";
getData = "?query=" + URLEncoder.encode(query, "UTF-8");
String link = "http://10.247.240.53/kas/lampen.php";
dbResult = database.execute(link).get();
}
catch (Exception e){
}
try{
JSONArray ja = new JSONArray(dbResult);
JSONObject jo = null;
data = new String[ja.length()];
for (int i = 0; i < ja.length(); i++)
{
jo = ja.getJSONObject(i);
data[i] = jo.getString("teeltbed");
}
adapter = new ArrayAdapter<String>(this, R.layout.layout_list, R.id.list_item, data);
listView.setAdapter(adapter);
}
catch (Exception e)
{
e.printStackTrace();
}
}
}`

Data is not showing in spinner using volley -Real Device Issue

The code is working fine when testing in emulator-Android 7.1, API 25 but when I test same code in Real Device-Android 4.4.4, API 19 spinner is not showing. And there is no error message even
Config.java
public class Config {
public static String mLocation ="http://towncitycards.com/webservice_action.php?action=";
//http://towncitycards.com/webservice_action.php?action=filter_location
public static final String DATA_URL = mLocation+"filter_location";
//Tags used in the JSON String
public static final String TAG_USERNAME = "name";
public static final String TAG_NAME = "slug";
public static final String TAG_COURSE = "name";
public static final String TAG_SESSION = "slug";
//JSON array name
public static final String JSON_ARRAY = "location";
}
DemoSpinner.java
public class DemoSpinner extends AppCompatActivity implements Spinner.OnItemSelectedListener{
//Declaring an Spinner
private Spinner spinner;
//An ArrayList for Spinner Items
private ArrayList<String> students;
//JSON Array
private JSONArray result;
//TextViews to display details
private TextView textViewName;
private TextView textViewCourse;
private TextView textViewSession;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.demo);
//Initializing the ArrayList
students = new ArrayList<String>();
//Initializing Spinner
spinner = (Spinner) findViewById(R.id.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
spinner.setOnItemSelectedListener(this);
//Initializing TextViews
textViewName = (TextView) findViewById(R.id.textViewName);
textViewCourse = (TextView) findViewById(R.id.textViewCourse);
textViewSession = (TextView) findViewById(R.id.textViewSession);
//This method will fetch the data from the URL
getData();
}
private void getData(){
//Creating a string request
StringRequest stringRequest = new StringRequest(Config.DATA_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(Config.JSON_ARRAY);
//Calling method getStudents to get the students from the JSON Array
getStudents(result);
} 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 getStudents(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
students.add(json.getString(Config.TAG_USERNAME));
} catch (JSONException e) {
e.printStackTrace();
}
}
//Setting adapter to show the items in the spinner
spinner.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, students));
}
//Method to get student name of a particular position
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;
}
//Doing the same with this method as we did with getName()
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;
}
//Doing the same with this method as we did with getName()
private String getSession(int position){
String session="";
try {
JSONObject json = result.getJSONObject(position);
session = json.getString(Config.TAG_SESSION);
} catch (JSONException e) {
e.printStackTrace();
}
return session;
}
//this method will execute when we pic an item from the spinner
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
//Setting the values to textviews for a selected item
textViewName.setText(getName(position));
textViewCourse.setText(getCourse(position));
textViewSession.setText(getSession(position));
}
//When no item is selected this method would execute
#Override
public void onNothingSelected(AdapterView<?> parent) {
textViewName.setText("");
textViewCourse.setText("");
textViewSession.setText("");
}
}
Please use this edited code this will work for you:
public class DemoSpinner extends AppCompatActivity implements Spinner.OnItemSelectedListener{
//Declaring an Spinner
private Spinner spinner;
//An ArrayList for Spinner Items
private ArrayList<String> students;
//JSON Array
private JSONArray result;
//TextViews to display details
private TextView textViewName;
private TextView textViewCourse;
private TextView textViewSession;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.demo);
//Initializing the ArrayList
students = new ArrayList<String>();
//Initializing Spinner
spinner = (Spinner) findViewById(R.id.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
spinner.setOnItemSelectedListener(this);
//Initializing TextViews
textViewName = (TextView) findViewById(R.id.textViewName);
textViewCourse = (TextView) findViewById(R.id.textViewCourse);
textViewSession = (TextView) findViewById(R.id.textViewSession);
//This method will fetch the data from the URL
getData();
}
private void getData(){
//Creating a request queue
JsonObjectRequest StringRequest = new JsonObjectRequest(Request.Method.GET, Config.DATA_URL, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
if (response != null) {
JSONObject j = null;
try {
//Parsing the fetched Json String to JSON Object
j = response;
//Storing the Array of JSON String to our JSON Array
result = j.getJSONArray(Config.JSON_ARRAY);
//Calling method getStudents to get the students from the JSON Array
getStudents(result);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
System.out.println("Volly error is this >>" + error);
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(StringRequest);
}
private void getStudents(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
students.add(json.getString(Config.TAG_USERNAME));
} catch (JSONException e) {
e.printStackTrace();
}
}
Log.e("student >>",students.toString());
//Setting adapter to show the items in the spinner
spinner.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, students));
}
//Method to get student name of a particular position
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;
}
//Doing the same with this method as we did with getName()
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;
}
//Doing the same with this method as we did with getName()
private String getSession(int position){
String session="";
try {
JSONObject json = result.getJSONObject(position);
session = json.getString(Config.TAG_SESSION);
} catch (JSONException e) {
e.printStackTrace();
}
return session;
}
//this method will execute when we pic an item from the spinner
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
//Setting the values to textviews for a selected item
textViewName.setText(getName(position));
textViewCourse.setText(getCourse(position));
textViewSession.setText(getSession(position));
}
//When no item is selected this method would execute
#Override
public void onNothingSelected(AdapterView<?> parent) {
textViewName.setText("");
textViewCourse.setText("");
textViewSession.setText("");
}
}
StringRequest stringRequest = new StringRequest(Request. Method.GET,Config.DATA_URL, new Response.Listener()
Use it in getData(). Because you wasn't specified Request.Method.GET
::OR::
You can use same like this:
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("action", "filter_location");
return params;
}
};
Then remove the parameter "action=filter_location" from url.

Populate Android spinner from PHP MySql

I have populate spinner from PHP MySql.While i select 1st item then populate another spinner from item click.But the problem is in second spinner populate the data doubly.Whenever i select the item of 1st Spinner.Can someone help me for only once add the data in Second spinner.
Here is my Screen Shot
Here is my Activity Code
spinnerCategory.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View arg1,
int pos, long arg3) {
// TODO Auto-generated method stub
Toast.makeText(parent.getContext(), "On Item Select : \n" + parent.getItemAtPosition(pos).toString(), Toast.LENGTH_LONG).show();
strSelected_Category=parent.getItemAtPosition(pos).toString();
System.out.println("strSelected_Category = " + strSelected_Category);
spinnerSubCategory.setEnabled(true);
ServiceHandler jsonParser = new ServiceHandler();
String json = jsonParser.makeServiceCall(URL_SUB_CATEGORIES, ServiceHandler.GET);
Log.e("Response: ", " > " + json);
if (json != null)
{
try {
JSONArray array=new JSONArray(json);
JSONArray sortedArray = new JSONArray();
for(int i=0;i<array.length();i++)
{
JSONObject obj=array.getJSONObject(i);
if(obj.getString("cat_name").equalsIgnoreCase(strSelected_Category))
{
sortedArray.put(obj);
Log.e("sortedArray"," = " +sortedArray);
}
}
if (sortedArray != null)
{
for (int i = 0; i < sortedArray.length(); i++)
{
JSONObject catObj = (JSONObject) sortedArray.get(i);
Category cat = new Category(catObj.getInt("subcat_id"),catObj.getString("subcat_name"));
sub_categoriesList.add(cat);
Log.e("cat "," = " + cat);
}
populateSubCategory();
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else
{
Log.e("JSON Data", "Didn't receive any data from server!");
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}
/**
* Adding Category spinner data
* */
private void populateSpinner() {
List<String> lables = new ArrayList<String>();
for (int i = 0; i < categoriesList.size(); i++)
{
lables.add(categoriesList.get(i).getName());
}
ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item, lables);
spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerCategory.setAdapter(spinnerAdapter);
}
private void populateSubCategory() {
List<String> lables = new ArrayList<String>();
for (int i = 0; i < sub_categoriesList.size(); i++)
{
lables.add(sub_categoriesList.get(i).getName());
}
ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item, lables);
spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerSubCategory.setAdapter(spinnerAdapter);
}
spinnerCategory.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View arg1,
int pos, long arg3) {
// TODO Auto-generated method stub
Toast.makeText(parent.getContext(), "On Item Select : \n" + parent.getItemAtPosition(pos).toString(), Toast.LENGTH_LONG).show();
strSelected_Category=parent.getItemAtPosition(pos).toString();
System.out.println("strSelected_Category = " + strSelected_Category);
spinnerSubCategory.setEnabled(true);
ServiceHandler jsonParser = new ServiceHandler();
String json = jsonParser.makeServiceCall(URL_SUB_CATEGORIES, ServiceHandler.GET);
Log.e("Response: ", " > " + json);
if (json != null)
{
try {
JSONArray array=new JSONArray(json);
JSONArray sortedArray = new JSONArray();
for(int i=0;i<array.length();i++)
{
JSONObject obj=array.getJSONObject(i);
if(obj.getString("cat_name").equalsIgnoreCase(strSelected_Category))
{
sortedArray.put(obj);
Log.e("sortedArray"," = " +sortedArray);
}
}
sub_categoriesList.clear();
if (sortedArray != null)
{
for (int i = 0; i < sortedArray.length(); i++)
{
JSONObject catObj = (JSONObject) sortedArray.get(i);
Category cat = new Category(catObj.getInt("subcat_id"),catObj.getString("subcat_name"));
sub_categoriesList.add(cat);
Log.e("cat "," = " + cat);
}
populateSubCategory();
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else
{
Log.e("JSON Data", "Didn't receive any data from server!");
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}
/**
* Adding Category spinner data
* */
private void populateSpinner() {
List<String> lables = new ArrayList<String>();
for (int i = 0; i < categoriesList.size(); i++)
{
lables.add(categoriesList.get(i).getName());
}
ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item, lables);
spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerCategory.setAdapter(spinnerAdapter);
}
private void populateSubCategory() {
List<String> lables = new ArrayList<String>();
for (int i = 0; i < sub_categoriesList.size(); i++)
{
lables.add(sub_categoriesList.get(i).getName());
}
ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item, lables);
spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerSubCategory.setAdapter(spinnerAdapter);
}
TRY THIS , HAPPY CODING :)

Matching json parsed value with user entered value

I parsed json to adapt for my autocompleteTextView. I tried to match the value parsed by my json object with the value entered by user.
But some where i am failing. please help me in matching these values.
i have to match the string(acity) that is entered by user with my parsed json value stored in responseList.
This is how i am trying.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);
new HttpGetTask().execute();
Button shwBtn = (Button) findViewById(R.id.showBtn);
shwBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
AutoCompleteTextView city1 = (AutoCompleteTextView) findViewById(R.id.autoCity);
EditText area1 = (EditText) findViewById(R.id.edArea);
String aCity = city1.getText().toString().trim();
String aArea = area1.getText().toString().trim();
//here i have to match acity with all the values in responseList before sending it to next activity
Intent myInt = new Intent(getBaseContext(),
Map1Activity.class);
String city = city1.getText().toString();
String area = area1.getText().toString();
myInt.putExtra("city", city);
myInt.putExtra("area", area);
startActivity(myInt);
}
});
}
private class HttpGetTask extends AsyncTask<Void, Void, String> {
String URL = "xyzz.cities.json?app_id=test";
AndroidHttpClient mClient = AndroidHttpClient.newInstance("");
#Override
protected String doInBackground(Void... params) {
// http stuff
return null;
}
#Override
protected void onPostExecute(String result) {
try {
JSONArray json = new JSONArray(result);
//getting my response(cities)
Log.v("ResponseCity", result);
final List<String> responseList = new ArrayList<String>();
for (int i = 0; i < json.length(); i++) {
final JSONObject e = json.getJSONObject(i);
String name = e.getString("name");
//Adding all values to a stringList
responseList.add(name);
ArrayAdapter<String> adapter;
adapter = new ArrayAdapter<String>(SearchActivity.this,
android.R.layout.simple_dropdown_item_1line,
responseList);
AutoCompleteTextView textView = (AutoCompleteTextView) findViewById(R.id.autoCity);
textView.setAdapter(adapter);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (null != mClient)
mClient.close();
}
}
So lets assume you need to match a certain city before you intent to a map :
private final List<String> responseList;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);
new HttpGetTask().execute();
Button shwBtn = (Button) findViewById(R.id.showBtn);
shwBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
AutoCompleteTextView city1 = (AutoCompleteTextView) findViewById(R.id.autoCity);
EditText area1 = (EditText) findViewById(R.id.edArea);
String aCity = city1.getText().toString().trim();
String aArea = area1.getText().toString().trim();
//here i have to match acity with all the values in responseList before sending it to next activity
for(int i=0; i<responseList.size(); i++) {
if(responseList.get(i).equals(aCity)) {
Intent myInt = new Intent(getBaseContext(),
Map1Activity.class);
String city = city1.getText().toString();
String area = area1.getText().toString();
myInt.putExtra("city", city);
myInt.putExtra("area", area);
startActivity(myInt);
}
}
}
});
}
private class HttpGetTask extends AsyncTask<Void, Void, String> {
String URL = "xyzz.cities.json?app_id=test";
AndroidHttpClient mClient = AndroidHttpClient.newInstance("");
#Override
protected String doInBackground(Void... params) {
// http stuff
return null;
}
#Override
protected void onPostExecute(String result) {
try {
JSONArray json = new JSONArray(result);
//getting my response(cities)
Log.v("ResponseCity", result);
responseList = new ArrayList<String>();
for (int i = 0; i < json.length(); i++) {
final JSONObject e = json.getJSONObject(i);
String name = e.getString("name");
//Adding all values to a stringList
responseList.add(name);
ArrayAdapter<String> adapter;
adapter = new ArrayAdapter<String>(SearchActivity.this,
android.R.layout.simple_dropdown_item_1line,
responseList);
AutoCompleteTextView textView = (AutoCompleteTextView) findViewById(R.id.autoCity);
textView.setAdapter(adapter);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (null != mClient)
mClient.close();
}
}
It should be something like that if I didnt guess your intent wrongly.

How to handle items inside onListItemClick of ArrayListAdapter?

I want to create a list view with names. Clicking on each name will give me different grade.
All names and grades ara taken by a database and stored into json format which is passed through activities with intents:
public class StudentList extends ListActivity {
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
/**get the intent*/
Intent studentIntent = getIntent();
/**retrieve the string extra passed*/
ArrayList<String> nameRecd = studentIntent.getStringArrayListExtra("name");
ArrayList<String> gradeRecd = studentIntent.getStringArrayListExtra("grade");
try {
JSONArray jsonData = new JSONArray(getIntent().getStringExtra("data"));
Log.i("json review:", "Check out my JSON, looks like his JMother");
ArrayAdapter<String> adapter = new ArrayAdapter<String>
(this, android.R.layout.simple_list_item_1, nameRecd);
setListAdapter(adapter);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
String item = (String) getListAdapter().getItem(position);
int pos = position;
Toast.makeText(this, item + " selected" + "Grade:" , Toast.LENGTH_LONG).show();
}
}
So I want for every selected name to be able to toast or handle otherwise tha grade of the same position so I can build some kind of profile for the specific student and be able to access it by clicking on students name!
Problem solved starting the sameintent inside onListItemClick...
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
String item = (String) getListAdapter().getItem(position);
/**get the intent*/
Intent studentIntent = getIntent();
/**retrieve the data extra passed*/
ArrayList<String> names = new ArrayList<String>();
ArrayList<String> grades = new ArrayList<String>();
JSONObject json_data = new JSONObject();
try {
JSONArray jARR = new JSONArray(getIntent().getStringExtra("data"));
Log.i("json review:", "Check out my JSON, looks like his JMother");
for(int i=0;i<jARR.length();i++){
json_data = jARR.getJSONObject(i);
names.add((json_data.getString("name"))) ;
grades.add((json_data.getString("grade"))) ;
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

Categories