Outline:
I have to get some operators list from server.
Below is my JSON data
{"PrepaidServiceList":[{"operator_id":"2","operator_name":"Reliance GSM"},{"operator_id":"9","operator_name":"TATA CDMA\/Walky"},{"operator_id":"10","operator_name":"Virgin GSM - TATA"},{"operator_id":"17","operator_name":"Docomo Mobile"},{"operator_id":"18","operator_name":"Idea Mobile"},{"operator_id":"35","operator_name":"T24 (DOCOMO)"},{"operator_id":"22","operator_name":"VodaFone Mobile"},{"operator_id":"28","operator_name":"MTS DataCard"},{"operator_id":"29","operator_name":"Reliance CDMA\/NetConnect\/Land Line"},{"operator_id":"30","operator_name":"TATA Photon"},{"operator_id":"32","operator_name":"Idea Netsetter"},{"operator_id":"33","operator_name":"MTS Prepaid"},{"operator_id":"38","operator_name":"Bsnl - Data\/Validity"},{"operator_id":"39","operator_name":"Bsnl Topup"},{"operator_id":"41","operator_name":"Bsnl Data Card"},{"operator_id":"45","operator_name":"Aircel"},{"operator_id":"46","operator_name":"Aircel Pocket Internet"},{"operator_id":"52","operator_name":"Virgin CDMA - TATA"},{"operator_id":"53","operator_name":"Docomo Special"},{"operator_id":"55","operator_name":"Videocon"},{"operator_id":"56","operator_name":"MTNL Mumbai"},{"operator_id":"57","operator_name":"MTNL Mumbai Special"},{"operator_id":"58","operator_name":"Uninor"},{"operator_id":"59","operator_name":"MTNL Delhi"},{"operator_id":"60","operator_name":"MTNL Delhi Special"},{"operator_id":"61","operator_name":"Uninor Special"},{"operator_id":"62","operator_name":"Videocon Special"},{"operator_id":"63","operator_name":"MTNL Delhi"},{"operator_id":"64","operator_name":"MTNL Mumbai"}]}
JSON data has "operator_id" and "operator_name".
I have to get both from url and display only "operator_name" in a spinner.
I Have already implemented the above. Please find the main_activity for reference
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
spinner = (Spinner) findViewById(R.id.spinner);
plans = (TextView)findViewById(R.id.browseplans);
plans.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent in = new Intent(getApplicationContext(), BrowsePlans.class);
in.putExtra("operator_id", id_click);
startActivity(in);
}
});
SimpleDateFormat sdf = new SimpleDateFormat("ddMMyyyyHHmmss");
sdf.setTimeZone(TimeZone.getTimeZone("GMT+5:30"));
currentDateandTime = sdf.format(new Date());
apikey = API_KEY.toString();
currentDateandTime.toString();
codetohash = currentDateandTime + apikey;
SHA1Hash = computeSha1OfString(codetohash);
uri = new Uri.Builder()
.scheme("http")
.authority("xxx.in")
.path("atm")
.appendQueryParameter("op", "GetPrepaidServiceList")
.appendQueryParameter("responseType", "json")
.appendQueryParameter("time", currentDateandTime)
.appendQueryParameter("clientId", ClientId)
.appendQueryParameter("hash", SHA1Hash)
.build();
stringUri = uri.toString();
new DataFromServer().execute();
} //end onCreate()
private class DataFromServer extends AsyncTask<String, Void, Void> {
#Override
protected void onPreExecute() {
}
#Override
protected Void doInBackground(String... params) {
try {
url = new URL(stringUri);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Host", "xxx.in");
/* Uri.Builder builder = new Uri.Builder()
.appendQueryParameter("val1", from)
.appendQueryParameter("val2", to);
String query = builder.build().getEncodedQuery();
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
writer.write(query);
writer.flush();
writer.close();
os.close();*/
conn.connect();
reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
text = sb.toString();
} catch (Exception ex) {
ex.toString();
} finally {
try {
reader.close();
} catch (Exception ex) {
ex.toString();
}
}
/*//only for json object not array
JSONObject parentObject = new JSONObject(text);
name = parentObject.getString("Hello");*/
try {
JSONObject jsonObj = new JSONObject(text);
// Getting JSON Array node
JSONArray jsonArray = jsonObj.getJSONArray("PrepaidServiceList");
// looping through All Contacts
for (int i = 0; i < jsonArray.length(); i++) {
c = jsonArray.getJSONObject(i);
id = c.getString("operator_id");
name = c.getString("operator_name");
list.add(name);
}
} catch (Exception e) {
e.toString();
}
return null;
}
#Override
protected void onPostExecute(Void unused) {
ArrayAdapter adapter =
new ArrayAdapter(getApplication(), R.layout.list_item, R.id.text1, list);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> arg0, View view, int position, long id) {
int item = spinner.getSelectedItemPosition();
id_click = spinner.getSelectedItem().toString();
}
public void onNothingSelected(AdapterView<?> arg0) {
}
});
}
}
Problem:
I am able to get user selected "operator_name" from spinner using "onItemSelectedListener".
But i need the "operator_id" of user selected "operator_name"
I have to pass the exact user selected "operator_id" to another class.
If i directly pass the operator_id, it has only the last id which is not the user selected one.
I am confused and don't know how to implement this.
Any Help would be greatly appreciated.
Thanks.
Try this way it worked for me
class LoadAlbums extends AsyncTask<String, String, ArrayList<HashMap<String,String>>> {
ArrayAdapter<String> adaptercountry ;
#Override
protected void onPreExecute() {
super.onPreExecute();
}
protected ArrayList<HashMap<String,String>> doInBackground(String... args) {
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
data = new ArrayList<HashMap<String, String>>();
String jsonStr = sh.makeServiceCall(COUNTRY_URL, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node your array
country_list = jsonObj.getJSONArray(COUNTRY_LIST);
// looping through All Contacts
for (int i = 0; i < country_list.length(); i++) {
JSONObject c = country_list.getJSONObject(i);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(OP_ID, c.getString(OP_ID));
map.put(OP_NAME,c.getString(OP_NAME));
data.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return data;
}
protected void onPostExecute(ArrayList<HashMap<String,String>> result) {
super.onPostExecute(result);
String[] arrConuntry=new String[data.size()];
for(int index=0;index<data.size();index++){
HashMap<String, String> map=data.get(index);
arrConuntry[index]=map.get(OP_NAME);
}
// pass arrConuntry array to ArrayAdapter<String> constroctor :
adaptercountry = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_spinner_dropdown_item,
arrConuntry);
spcountry.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View w) {
new AlertDialog.Builder(getActivity())
.setTitle("Select")
.setAdapter(adaptercountry, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
spcountry.setText(adaptercountry.getItem(which).toString());
try {
cname=country_list.getJSONObject(which).getString("operator_id");
Log.d("Response: ", "> " + cname);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
dialog.dismiss();
}
}).create().show();
}
});
}
In this case you can modify the AsyncTask to return in the doInBackground() method a List<HashMap<Integer, String>>. So you can store both operator_id and operator_name in the list and display each wanted item in the spinner.
Hope it helps!!!
Create a new ArrayList like
operator_List = new ArrayList<String>();
Add value in ArrayList like
opt_code.setName(jsonobject.optString("operator_name"));
opt_code.setId(jsonobject.optString("operator_id"));
list.add(opt_code);
datalist.add(jsonobject.optString("operator_name"));
operator_List .add(jsonobject.getString("operator_id")
and get operator_id
protected void onPostExecute(Void unused) {
ArrayAdapter adapter =
new ArrayAdapter(getApplication(), R.layout.list_item, R.id.text1, list);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> arg0, View view, int position, long id) {
id_click = spinner.getSelectedItemPosition();
String opt_code = operator_List.get(position);
String selectedItem = arg0.getItemAtPosition(position).toString();
}
public void onNothingSelected(AdapterView<?> arg0) {
}
});
}
May be help you
Your can get Whole object of selected Spinner item use below code:
Object item = arg0.getItemAtPosition(position);
Related
im trying to parse data from SQL Database into Listview.
My PHP script is working because if i run it in the browser i get the content.
If im trying to get the data from my SQL Databse into the listview my app shows nothing.
Here is my MainActivity:
public class Locations extends AppCompatActivity implements AdapterView.OnItemClickListener {
ArrayList<productforloc> arrayList;
ListView lv;
private String TAG = Locations.class.getSimpleName();
private TextView addressField; //Add a new TextView to your activity_main to display the address
private LocationManager locationManager;
private String provider;
int i = 1;
private ProgressDialog pDialog;
String name;
// URL to get contacts JSON
private static String url = "Mylink";
ArrayList<HashMap<String, String>> contactList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content_main);
Intent i = getIntent();
String cityname = i.getExtras().getString("cityname");
TextView city = (TextView) findViewById(R.id.ort);
city.setText(cityname);
pDialog = new ProgressDialog(Locations.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(true);
pDialog.show();
arrayList = new ArrayList<>();
lv = (ListView) findViewById(R.id.lv);
lv.setOnItemClickListener((AdapterView.OnItemClickListener) this);
runOnUiThread(new Runnable() {
#Override
public void run() {
new ReadJSON().execute(url);
}
});
final ImageButton filteropen = (ImageButton) findViewById(R.id.aufklaupen);
filteropen.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
RelativeLayout filter = (RelativeLayout) findViewById(R.id.filterloc);
filter.setVisibility(View.VISIBLE);
ImageButton filterclose = (ImageButton) findViewById(R.id.zuklappen);
filterclose.setVisibility(View.VISIBLE);
filteropen.setVisibility(View.INVISIBLE);
}
});
final ImageButton filterclose = (ImageButton) findViewById(R.id.zuklappen);
filterclose.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
RelativeLayout filter = (RelativeLayout) findViewById(R.id.filterloc);
filter.setVisibility(View.INVISIBLE);
ImageButton filteropen = (ImageButton) findViewById(R.id.aufklaupen);
filteropen.setVisibility(View.VISIBLE);
filterclose.setVisibility(View.INVISIBLE);
}
});
}
class ReadJSON extends AsyncTask<String,Integer,String> {
#Override
protected String doInBackground(String... params) {
return readURL(params[0]);
}
#Override
protected void onPostExecute(String content) {
try{
JSONObject jo = new JSONObject(content);
JSONArray ja = jo.getJSONArray("contacts");
for(int i=0;i<ja.length();i++){
JSONObject po = ja.getJSONObject(i);
arrayList.add(new productforloc(
po.getString("imageurl"),
po.getString("name"),
po.getString("street"),
po.getString("postalcode"),
po.getString("musicstyle"),
po.getString("musicsecond"),
po.getString("entry"),
po.getString("opening"),
po.getString("agegroup"),
po.getString("urlbtn"),
po.getString("Fsk"),
po.getString("city"),
po.getString("bg")
));
}
} catch (JSONException e) {
e.printStackTrace();
}
final CustomListAdapterforloc adapter = new CustomListAdapterforloc(getApplicationContext(),R.layout.model,arrayList);
lv.setAdapter(adapter);
if(pDialog.isShowing()){
pDialog.dismiss();
}
}
}
private String readURL(String url){
StringBuilder content = new StringBuilder();
try{
URL uri = new URL(url);
URLConnection urlConnection = uri.openConnection();
BufferedReader bufferedReader= new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
String line;
while((line = bufferedReader.readLine()) !=null){
content.append(line+"\n");
}
bufferedReader.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return content.toString();
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
productforloc pForloc = arrayList.get(position);
Intent intent = new Intent();
intent.setClass(this,DetailActivity.class);
intent.putExtra("name",pForloc.getName());
intent.putExtra("imageurl",pForloc.getImage());
intent.putExtra("street",pForloc.getStreet());
intent.putExtra("postalcode",pForloc.getPostalcode());
intent.putExtra("entry",pForloc.getEntry());
intent.putExtra("agegroup",pForloc.getAgegroup());
intent.putExtra("opening",pForloc.getOpening());
intent.putExtra("urlbtn",pForloc.getUrlbtn());
intent.putExtra("Fsk",pForloc.getFsk());
intent.putExtra("city",pForloc.getCity());
intent.putExtra("musicstyle",pForloc.getMusicstyle());
intent.putExtra("musicsecond",pForloc.getMusicsecond());
intent.putExtra("bg",pForloc.getBg());
startActivity(intent);
}
/**
* Async task class to get json by making HTTP call
}
*/
}
and here is my Customlistadapter Activity:
public class CustomListAdapterforloc extends ArrayAdapter<productforloc>{
ArrayList<productforloc> products;
Context context;
int resource;
public CustomListAdapterforloc(Context context, int resource, List<productforloc> products) {
super(context, resource, products);
this.products = (ArrayList<productforloc>) products;
this.context = context;
this.resource = resource;
}
#NonNull
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView== null){
LayoutInflater layoutInflater = (LayoutInflater) getContext().getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = layoutInflater.inflate(R.layout.model,null,true);
}
productforloc product = getItem(position);
ImageView imageView = (ImageView) convertView.findViewById(R.id.imagelist);
Picasso.with(context).load(product.getImage()).into(imageView);
TextView txtName= (TextView) convertView.findViewById(R.id.namelist);
txtName.setText(product.getName());
return convertView;
}
}
i solved it using this code in my MAinActivity:
public class Locations extends AppCompatActivity {
private String TAG = Locations.class.getSimpleName();
private ProgressDialog pDialog;
private ListView lv;
// URL to get contacts JSON
private static String url = "http://partypeople.bplaced.net/loli.php";
ArrayList<HashMap<String, String>> contactList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
contactList = new ArrayList<>();
lv = (ListView) findViewById(R.id.lv);
new GetContacts().execute();
}
/**
* Async task class to get json by making HTTP call
*/
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(Locations.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
JSONArray contacts = new JSONArray(jsonStr);
// Getting JSON Array node
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String id = c.getString("id");
String name = c.getString("name");
String email = c.getString("email");
String address = c.getString("address");
String gender = c.getString("gender");
// tmp hash map for single contact
HashMap<String, String> contact = new HashMap<>();
// adding each child node to HashMap key => value
contact.put("id", id);
contact.put("name", name);
contact.put("email", email);
// adding contact to contact list
contactList.add(contact);
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG)
.show();
}
});
}
} else {
Log.e(TAG, "Couldn't get json from server.");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Couldn't get json from server. Check LogCat for possible errors!",
Toast.LENGTH_LONG)
.show();
}
});
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**3
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
Locations.this, contactList,
R.layout.model, new String[]{"name", "email",
"mobile"}, new int[]{R.id.namelist,
});
lv.setAdapter(adapter);
}
}
and used in my CustomlistadapterActivity:
public class HttpHandler {
private static final String TAG = HttpHandler.class.getSimpleName();
public HttpHandler() {
}
public String makeServiceCall(String reqUrl) {
String response = null;
try {
URL url = new URL(reqUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
// read the response
InputStream in = new BufferedInputStream(conn.getInputStream());
response = convertStreamToString(in);
} catch (MalformedURLException e) {
Log.e(TAG, "MalformedURLException: " + e.getMessage());
} catch (ProtocolException e) {
Log.e(TAG, "ProtocolException: " + e.getMessage());
} catch (IOException e) {
Log.e(TAG, "IOException: " + e.getMessage());
} catch (Exception e) {
Log.e(TAG, "Exception: " + e.getMessage());
}
return response;
}
private String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line;
try {
while ((line = reader.readLine()) != null) {
sb.append(line).append('\n');
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
}
Thanks for your input
Override getCount method into adapter class.
I am new to android. I need to pass values from the spinner to asynctask as an parameter and till now I am successful in showing the results in spinner successfully. Now i need to pass the selected value from the spinner to another activity on a button click (as an parameter to asynctask). Below is the code. Thanks in advance.
BackgroundFetchWorker.java:
public class BackgroundFetchWorker extends AsyncTask<String,Void,String> {
String json_string;
ProgressDialog progressDialog;
Context context;
BackgroundFetchWorker(Context ctx)
{
context = ctx;
}
#Override
protected String doInBackground(String... params) {
String type2 = params[0];
String student_fetch_url = "http://pseudoattendance.pe.hu/studentFetch.php";
if (type2.equals("fetchSubject")) {
try {
String semester = params[1];
String stream = params[2];
URL url = new URL(student_fetch_url);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoOutput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
String post_data = URLEncoder.encode("semester", "UTF-8") + "=" + URLEncoder.encode(semester, "UTF-8")
+ URLEncoder.encode("stream","UTF-8")+"="+URLEncoder.encode(stream,"UTF-8");
bufferedWriter.write(post_data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"));
String result = " ";
String line = "";
while ((line = bufferedReader.readLine()) != null) {
result += line;
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return result;
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPreExecute() {
progressDialog = new ProgressDialog(context);
progressDialog.setTitle("Fetching Data....");
progressDialog.setMessage("This may take a while..");
progressDialog.show();
}
#Override
protected void onPostExecute(String result) {
progressDialog.dismiss();
String s = result.trim();
if(s.equals("{\"result\":[]}")){
Toast.makeText(context, "ERROR OCCURED", Toast.LENGTH_SHORT).show();
}
else {
json_string = result;
Intent i = new Intent(context, TakeAttendanceActivity.class);
i.putExtra("studentdata", json_string);
context.startActivity(i);
Toast.makeText(context, "Success", Toast.LENGTH_SHORT).show();
}
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
}
FacultyWelcomeActivity.java:
public class FacultyWelcomeActivity extends AppCompatActivity implements Spinner.OnItemSelectedListener{
String JSON_STRING;
JSONObject jsonObject;
JSONArray jsonArray;
ContactAdapter contactAdapter;
ListView listView;
//Declaring an Spinner
private Spinner spinner;
private Spinner spinner1;
//An ArrayList for Spinner Items
private ArrayList<String> students;
private ArrayList<String> stream;
//JSON Array
private JSONArray result;
private JSONArray result1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_faculty_welcome);
//Initializing the ArrayList
students = new ArrayList<String>();
stream = new ArrayList<String>();
//Initializing Spinner
spinner = (Spinner) findViewById(R.id.spinner);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String semesters= parent.getItemAtPosition(position).toString();
String stream= parent.getItemAtPosition(position).toString();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
spinner1 = (Spinner) findViewById(R.id.spinner1);
//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
getData();
getData1();
listView = (ListView) findViewById(R.id.lectureList);
contactAdapter = new ContactAdapter(this, R.layout.rowlayout);
listView.setAdapter(contactAdapter);
JSON_STRING = getIntent().getExtras().getString("JSON Data");
try {
jsonObject = new JSONObject(JSON_STRING);
jsonArray = jsonObject.getJSONArray("result");
int count = 0;
String sub1, sub2, sub3, sub4;
while (count < jsonArray.length()) {
JSONObject JO = jsonArray.getJSONObject(count);
sub1 = JO.getString("fname");
sub2 = JO.getString("lname");
sub3 = JO.getString("id");
sub4 = JO.getString("email");
Contacts contacts = new Contacts(sub1, sub2, sub3, sub4);
contactAdapter.add(contacts);
count++;
}
} catch (JSONException e) {
e.printStackTrace();
}
}
public void fetchSubject(View view) {
String type2 = "fetchSubject";
String spinnerdata = spinner.getSelectedItem().toString();
String spinner1data = spinner1.getSelectedItem().toString();
BackgroundFetchWorker background = new BackgroundFetchWorker(this);
background.execute(type2,spinnerdata,spinner1data);
}
private void getData1(){
StringRequest stringRequest = new StringRequest(Config2.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
result1 = j.getJSONArray(Config2.JSON_ARRAY);
getStudents1(result1);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
private void getData(){
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);
result = j.getJSONArray(Config.JSON_ARRAY);
getStudents(result);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
private void getStudents(JSONArray j){
for(int i=0;i<j.length();i++){
try {
//Getting json object
JSONObject json = j.getJSONObject(i);
students.add(json.getString(Config.TAG_SEMESTER));
} catch (JSONException e) {
e.printStackTrace();
}
}
spinner.setAdapter(new ArrayAdapter<String>(FacultyWelcomeActivity.this, android.R.layout.simple_spinner_dropdown_item, students));
}
private void getStudents1(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
stream.add(json.getString(Config2.TAG_STREAM));
} catch (JSONException e) {
e.printStackTrace();
}
}
spinner1.setAdapter(new ArrayAdapter<String>(FacultyWelcomeActivity.this, android.R.layout.simple_spinner_dropdown_item, stream));
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
//check which spinner triggered the listener
}
#Override
public void onNothingSelected(AdapterView<?> parent) {}}
You are passing parameters to doInBackground() this way:
background.execute("your string");
Now the string "your string" will be the parameter within doInBackground() callback:
#Override
protected String doInBackground(String... params) {
String type2 = params[0]; // type2 == "your string"
...
}
See docs for more info.
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();
}
I'm trying to retrieve data from MySql database and put it on a ListView, everything works fine, I even put that data into textviews(dynamically) and it works fine. But when I used a ListView, only the last element was displayed, I think that means every new element is overwritten the old one, right?
What can I do to solve this? here's my code tell what's wrong??
public class MakeAppointementActivity extends AppCompatActivity {
public List<AvailabilityList> customList;
public ListView lv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_make_appointement);
lv=(ListView)findViewById(R.id.listView);
Intent intent=getIntent();
new RetrieveTask().execute();
}
private class RetrieveTask extends AsyncTask<Void, Void, String> {
#Override
protected String doInBackground(Void... params) {
String strUrl = "availableAppointments1.php";
URL url;
StringBuffer sb = new StringBuffer();
try {
url = new URL(strUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream iStream = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(iStream));
String line;
while( (line = reader.readLine()) != null){
sb.append(line);
}
reader.close();
iStream.close();
} catch (IOException e) {
e.printStackTrace();
}
return sb.toString();
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
new ParserTask().execute(result);
}
}
// Background thread to parse the JSON data retrieved from MySQL server
private class ParserTask extends AsyncTask<String, Void, List<HashMap<String, String>>> {
#Override
protected List<HashMap<String, String>> doInBackground(String... params) {
AppointementJSONParser appointementParser = new AppointementJSONParser();
JSONObject json = null;
try {
json = new JSONObject(params[0]);
} catch (JSONException e) {
e.printStackTrace();
}
return appointementParser.parse(json);
}
#Override
protected void onPostExecute(List<HashMap<String, String>> result) {
customList=new ArrayList<>(); / move it to here
for (int i = 0; i < result.size(); i++) {
HashMap<String, String> appointement = result.get(i);
String fromT = appointement.get("fromT");
String toT = appointement.get("toT");
String date = appointement.get("date");
addAvailableAppoint(fromT,toT,date);
}
updateListView(); // update listview when you add all data to arraylist
}
}
private void addAvailableAppoint(final String fromT, final String toT, final String date) {
customList.add(new AvailabilityList(fromT));
}
// split new function for update listview
private updateListView(){
ArrayAdapter adapter=new DoctorAvailabilityAdapter(MakeAppointementActivity.this,R.layout.list_items,customList);
adapter.notifyDataSetChanged();
lv.setAdapter(adapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(MakeAppointementActivity.this, AppointementActivity.class);
intent.putExtra("fromT", fromT);
intent.putExtra("toT", toT);
intent.putExtra("date", date);
startActivity(intent);
}
});
}
}
Try this code
.....// your above code
#Override
protected void onPostExecute(List<HashMap<String, String>> result) {
customList=new ArrayList<>(); / move it to here
for (int i = 0; i < result.size(); i++) {
HashMap<String, String> appointement = result.get(i);
String fromT = appointement.get("fromT");
String toT = appointement.get("toT");
String date = appointement.get("date");
addAvailableAppoint(fromT,toT,date);
}
updateListView(); // update listview when you add all data to arraylist
}
}
private void addAvailableAppoint(final String fromT, final String toT, final String date) {
customList.add(new AvailabilityList(fromT));
}
// split new function for update listview
private updateListView(){
ArrayAdapter adapter=new DoctorAvailabilityAdapter(MakeAppointementActivity.this,R.layout.list_items,customList);
adapter.notifyDataSetChanged();
lv.setAdapter(adapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(MakeAppointementActivity.this, AppointementActivity.class);
// intent.putExtra("fromT", fromT); // change it to
intent.putExtra("fromT", customList.get(position).getFromT());
intent.putExtra("toT", toT);
intent.putExtra("date", date);
startActivity(intent);
}
});
}
}
Hope this help
You create new ArrayList for every item customList=new ArrayList<>();
Create list only once in OnCreate for example.
Also you create new Adapter every time you add an item, adapter should also be created only once in OnCreate then you should update data with adapter.NotifyDataSetChanged()
what is the correct way of fixing this problem?
This is my activity code
public class MainActivity extends Activity {
JSONParser jsonParser = new JSONParser();
ItemsAdapter adapter;
ListView list;
ListView list2;
HashMap<String, String> map;
ProgressDialog myPd_bar;
static String img_url;
private String strJson1 = "";
private String url = "http://www.*************************************************";
String img_test_url = "http://*************************************************";
ImageView imageView;
String bName;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
list = (ListView) findViewById(R.id.listView1);
list2 = (ListView) findViewById(R.id.listView2);
accessWebService();
}
// Async Task to access the web
private class LoadData extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
myPd_bar = new ProgressDialog(MainActivity.this);
myPd_bar.setMessage("Loading....");
myPd_bar.setTitle(null);
myPd_bar.show();
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(params[0]);
try {
HttpResponse response = httpclient.execute(httppost);
strJson1 = inputStreamToString(
response.getEntity().getContent()).toString();
}
catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private StringBuilder inputStreamToString(InputStream is) {
String rLine = "";
StringBuilder answer = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
try {
while ((rLine = rd.readLine()) != null) {
answer.append(rLine);
}
}
catch (IOException e) {
// e.printStackTrace();
Toast.makeText(getApplicationContext(),
"Error..." + e.toString(), Toast.LENGTH_LONG).show();
}
return answer;
}
#Override
protected void onPostExecute(String result) {
getImageData();
myPd_bar.dismiss();
}
}// end async task
public void accessWebService() {
LoadData task = new LoadData();
// passes values for the urls string array
task.execute(new String[] { url });
}
// build hash set for list view
public void getImageData() {
map = new HashMap<String, String>();
ArrayList<Pair<String,String>> listData = new ArrayList<Pair<String,String>>();
try {
JSONObject jsonResponse = new JSONObject(strJson1);
JSONArray jsonMainNode = jsonResponse.optJSONArray("bank");
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
img_url = jsonChildNode.optString("logo");
String test1 = img_test_url + img_url;
bName = jsonChildNode.optString("id");
//map.put(bName, test1);
listData.add(new Pair<String,String>(bName,test1 ));
}
ItemsAdapter adapter = new ItemsAdapter(getApplicationContext(),listData);
list.setAdapter(adapter);
} catch (JSONException e) {
Toast.makeText(getApplicationContext(), "Connection Error...",
Toast.LENGTH_LONG).show();
}
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
#SuppressWarnings("unchecked")
Pair<String, String> item = (Pair<String, String>)arg0.getItemAtPosition(arg2);
String id = item.first;
Log.d("Bank Name", id);
List<String> cards_name = new ArrayList<String>();
try {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("Bank_Name", id));
Log.d("request!", "starting");
JSONObject jsonResponse = jsonParser.makeHttpRequest("http://*************************************************", "POST", params);
Log.d("Credite Cards", jsonResponse.toString());
JSONArray jsonMainNode = jsonResponse.optJSONArray("creditcards");
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
String card = jsonChildNode.optString("name");
Log.d("Card_name", card);
cards_name.add(card);
}
ArrayAdapter adapter2 = new ArrayAdapter(MainActivity.this, android.R.layout.simple_list_item_1, cards_name);
list2.setAdapter(adapter2);
} catch (JSONException e) {
Toast.makeText(getApplicationContext(), "Error..." + e.toString(),
Toast.LENGTH_LONG).show();
}
}
});
}
}
I guess this where you go wrong
JSONObject jsonResponse = jsonParser.makeHttpRequest("http://*************************************************", "POST", params);
In onPostExecute you have
getImageData();
In getImageData() you have listview item click listener
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
..// rest of the code
JSONObject jsonResponse = jsonParser.makeHttpRequest("http://*************************************************", "POST", params);
// network operation on main thread
This getting json object must be doen in a background thread
Also you cannot update ui from background thread
Toast.makeText(getApplicationContext(),
"Error..." + e.toString(), Toast.LENGTH_LONG).show();
Must be removed
JSONObject jsonResponse = jsonParser.makeHttpRequest("http://*************************************************", "POST", params);
//this should be in a separate non ui thread
For the http request in android the better way to use the following library which is manage all the auto setting for the request there are simple few line code
Check the following link.
http://loopj.com/android-async-http/
download the jar file and paste in the lib folder and then just write few lines like for simple get methods
});
import com.loopj.android.http.*;
AsyncHttpClient client = new AsyncHttpClient();
client.get("http://www.google.com", new AsyncHttpResponseHandler() {
#Override
public void onSuccess(String response) {
System.out.println(response);
}
});