Android: ListView from MySQL only display the last element - android

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()

Related

How do i get the right content in Single Item View

After Clicking an Item in my List view, my Single Item View should appear. Unfortunately every time i click on one of the two items just the same content appears. How can i fix the problem and the right content will be shown?
First i get parse data in my Main Activity:
public class MainActivity extends AppCompatActivity implements AdapterView.OnItemClickListener {
ArrayList<productforloc> arrayList;
ListView lv;
private String TAG = MainActivity.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;
String image;
String street;
String postalcode;
String musicstyle;
String musicsecond;
String entry;
String opening;
String agegroup;
String urlbtn;
String Fsk;
String city;
// URL to get contacts JSON
private static String url = "http://partypeople.bplaced.net/maptest.json";
ArrayList<HashMap<String, String>> contactList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
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 Button popbutton = (Button) findViewById(R.id.popbutton);
popbutton.setOnClickListener(new View.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
#Override
public void onClick(View v) {
if (i == 1) {
if (popbutton.isPressed()) {
popbutton.setBackground(getResources().getDrawable(R.drawable.secondbg));
arrayList.clear();
url = "http://partypeople.bplaced.net/justpop.json";
runOnUiThread(new Runnable() {
#Override
public void run() {
new ReadJSON().execute(url);
}
});
i = i + 1;
}
} else {
if (popbutton.isPressed()) {
popbutton.setBackground(getResources().getDrawable(R.drawable.bg_popbutton));
arrayList.clear();
url = "http://partypeople.bplaced.net/maptest.json";
runOnUiThread(new Runnable() {
#Override
public void run() {
new ReadJSON().execute(url);
}
});
i = i - 1;
}
}
}
});
}
class ReadJSON extends AsyncTask<String,Integer,String>{
#Override
protected String doInBackground(String... params) {
return readURL(params[0]);
}
#Override
protected void onPostExecute(String content) {
if (pDialog.isShowing())
pDialog.dismiss();
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(
image= po.getString("imageurl"),
name = po.getString("name"),
street = po.getString("street"),
postalcode = po.getString("postalcode"),
musicstyle = po.getString("musicstyle"),
musicsecond = po.getString("musicsecond"),
entry = po.getString("entry"),
opening = po.getString("opening"),
agegroup = po.getString("agegroup"),
urlbtn = po.getString("urlbtn"),
Fsk = po.getString("Fsk"),
city = po.getString("city")
));
}
} catch (JSONException e) {
e.printStackTrace();
}
CustomListAdapterforloc adapter = new CustomListAdapterforloc(getApplicationContext(),R.layout.model,arrayList);
lv.setAdapter(adapter);
}
}
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) {
Intent intent = new Intent();
intent.setClass(this,DetailActivity.class);
intent.putExtra("name",name);
intent.putExtra("imageurl",image);
intent.putExtra("street",street);
intent.putExtra("postalcode",postalcode);
intent.putExtra("musicstyle",musicstyle);
intent.putExtra("musicsecond",musicsecond);
intent.putExtra("entry",entry);
intent.putExtra("opening",opening);
intent.putExtra("agegroup",agegroup);
intent.putExtra("urlbtn",urlbtn);
intent.putExtra("Fsk",Fsk);
intent.putExtra("city",city);
startActivity(intent);
Toast.makeText(getApplicationContext(),street,Toast.LENGTH_LONG).show();
}
/**
* Async task class to get json by making HTTP call
}
*/
}
Then as you can see in the bottom the content will be sent to the detailactivity, but i always get the content from the second item in my json even if i click on the first item.
Change your onItemClick method to get the right object from your list.
Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
productforloc pForloc = arrayList.get(positon);
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("urlbtn",pForloc.getUrlbtn());
intent.putExtra("Fsk",pForloc.getFsk());
intent.putExtra("city",pForloc.getCity());
startActivity(intent);
Toast.makeText(getApplicationContext(),street,Toast.LENGTH_LONG).show();
}

Button click action not working in android listview

I am developing an android app which functions like as follows
Admin creates the data and saves it into database then user access the same data through app when it comes down to showing the data to user i fetch the data from the database which admin has already saved i show the data in listview, and listview having buttons in each row when user click on button it dose not goes to next activity.When user will click on button in listview the activity should pass to next activity.How do i do this?
//java activity
public class MainActivity extends ActionBarActivity {
String myJSON;
SimpleAdapter adapter;
Button btn;
private static final String TAG_RESULTS = "result";
private static final String TAG_NAME = "sname";
private static final String TAG_PRICE = "sprice";
JSONArray peoples = null;
ArrayList<HashMap<String, String>> personList;
// ArrayList<HashMap<String, String>> personList = new ArrayList<HashMap<String, String>>();
ListView list, listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
list = (ListView) findViewById(R.id.listView_search);
btn = (Button) findViewById(R.id.button3_book);
personList = new ArrayList<HashMap<String, String>>();
getData();
// Listview on item click listener
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent zoom=new Intent(parent.getContext(), Details.class);
parent.getContext().startActivity(zoom);
}
});
}
protected void showList(){
try {
JSONObject jsonObj = new JSONObject(myJSON);
peoples = jsonObj.getJSONArray(TAG_RESULTS);
for(int i=0;i<peoples.length();i++){
JSONObject c = peoples.getJSONObject(i);
String sname = c.getString(TAG_NAME);
String sprice = c.getString(TAG_PRICE);
HashMap<String,String> persons = new HashMap<String,String>();
persons.put(TAG_NAME,sname);
persons.put(TAG_PRICE,sprice);
personList.add(persons);
}
ListAdapter adapter = new SimpleAdapter(
MainActivity.this, personList, R.layout.search_item,
new String[]{TAG_NAME,TAG_PRICE},
new int[]{ R.id.textView8_sellernm, R.id.textView19_bprice}
);
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent i=new Intent(MainActivity.this,Details.class);
startActivity(i);
}
});
} catch (JSONException e) {
e.printStackTrace();
}
}
public void getData(){
class GetDataJSON extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
HttpPost httppost = new HttpPost("http://example.com/User/reg/listview.php");
// Depends on your web service
httppost.setHeader("Content-type", "application/json");
InputStream inputStream = null;
String result = null;
try {
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
inputStream = entity.getContent();
// json is UTF-8 by default
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
result = sb.toString();
} catch (Exception e) {
// Oops
}
finally {
try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
}
return result;
}
#Override
protected void onPostExecute(String result){
myJSON=result;
showList();
}
}
GetDataJSON g = new GetDataJSON();
g.execute();
}
}

Android - Display data from Adapter in Listview

I've currently got an application that pulls data from a mysql database and displays it in raw JSON format. I'm currently working on pushing this data into a String variable and displaying it on a Listview on a specific activity.
Problem is, when trying to display this data, my Listview is not populating; I'm sure the variable is not empty as the if statement would have captured this.
Here is snippet of MainActivity code:
//Methods to grab information from abhandym_DB database
public void getJSON(View view){
new BackgroundTask().execute();
}
public void parseJSON(View view){
if(JSON_String==null){
Toast.makeText(getApplicationContext(), "First Get Json", Toast.LENGTH_LONG).show();
}else{
Intent intent = new Intent(this,Test.class);
intent.putExtra("JSON_Data",JSON_String);
startActivity(intent);
}
}
class BackgroundTask extends AsyncTask<Void,Void,String>{
String json_url;
#Override
protected void onPreExecute() {
json_url = "http://abhandyman.x10host.com/json_get_data.php";
}
#Override
protected String doInBackground(Void... params) {
try {
URL url = new URL(json_url);
HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
InputStream inputSteam = httpURLConnection.getInputStream();
BufferedReader buffereredReader = new BufferedReader(new InputStreamReader(inputSteam));
StringBuilder stringBuilder = new StringBuilder();
while((JSON_String = buffereredReader.readLine())!=null){
stringBuilder.append(JSON_String+"\n");
}
buffereredReader.close();
inputSteam.close();
httpURLConnection.disconnect();
return stringBuilder.toString().trim();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(String result) {
TextView textView = (TextView)findViewById(R.id.fragment1_textview_JSONAPPEAR);
textView.setText(result);
JSON_String = result;
}
}
Here is the code for my Test.java
public class Test extends AppCompatActivity {
String JSON_String;
JSONObject jsonObject;
JSONArray jsonArray;
DataAdapter dataAdapter;
ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test_layout);
listView = (ListView)findViewById(R.id.test_listView);
dataAdapter = new DataAdapter(this, R.layout.row_layout);
listView.setAdapter(dataAdapter);
JSON_String = getIntent().getExtras().getString("JSON_Data");
try {
jsonObject = new JSONObject(JSON_String);
jsonArray = jsonObject.getJSONArray("server_response");
int count = 0;
String jobid,problem,resolution;
while(count<jsonObject.length()){
JSONObject JO = jsonArray.getJSONObject(count);
jobid = JO.getString("jobid");
problem = JO.getString("problem");
resolution = JO.getString("resolution");
Data data = new Data(jobid,problem,resolution);
dataAdapter.add(data);
count++;
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Here is the code for my DataAdapter:
public class DataAdapter extends ArrayAdapter{
List list = new ArrayList();
public DataAdapter(Context context, int resource) {
super(context, resource);
}
public void add(Data object) {
super.add(object);
list.add(object);
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int position) {
return list.get(position);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row;
row = convertView;
DataHolder dataHolder;
if(row == null){
LayoutInflater layoutInflater = (LayoutInflater)this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = layoutInflater.inflate(R.layout.row_layout,parent,false);
dataHolder = new DataHolder();
dataHolder.tx_jobid = (TextView) row.findViewById(R.id.tx_jobid);
dataHolder.tx_problem = (TextView) row.findViewById(R.id.tx_problem);
dataHolder.tx_resolution = (TextView) row.findViewById(R.id.tx_resolution);
row.setTag(dataHolder);
}else{
dataHolder = (DataHolder)row.getTag();
}
Data data = (Data)this.getItem(position);
dataHolder.tx_jobid.setText(data.getJobid());
dataHolder.tx_problem.setText(data.getProblem());
dataHolder.tx_resolution.setText(data.getResolution());
return row;
}
static class DataHolder{
TextView tx_jobid,tx_problem,tx_resolution;
}
}
and here is what it displays when clicking on "Parse JSON" button.
listView empty after population
Any help or advise on why its not displaying would be much appreciated!
Thanks in advance!
your problem seems to be here :
while(count<jsonObject.length()){
you're not looping using the number of array elements but using the number of mapped key:value object which is one (the "server_response") , you have to change this line to :
while(count<jsonArray.length()){
,
you have just the first element showing because jsonObject.length() will return 1 since it have just one element.
from the doc, JSONObject, length() method:
Returns the number of name/value mappings in this object.
and in your case you have just one name/value mapped ("server_response":[array items...])
Check in Test.java. I think You are setting the adapter to the listview before adding data to it
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test_layout);
listView = (ListView)findViewById(R.id.test_listView);
dataAdapter = new DataAdapter(this, R.layout.row_layout);
JSON_String = getIntent().getExtras().getString("JSON_Data");
try {
jsonObject = new JSONObject(JSON_String);
jsonArray = jsonObject.getJSONArray("server_response");
int count = 0;
String jobid,problem,resolution;
while(count<jsonObject.length()){
JSONObject JO = jsonArray.getJSONObject(count);
jobid = JO.getString("jobid");
problem = JO.getString("problem");
resolution = JO.getString("resolution");
Data data = new Data(jobid,problem,resolution);
dataAdapter.add(data);
count++;
}
} catch (JSONException e) {
e.printStackTrace();
}
listView.setAdapter(dataAdapter); //change effected
}

how to Get selected spinner item's Id from JSON response?

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);

How to update listview after changing data in JSON?

Hello everyone and happy new year
I have JSON class where I retrieve some data that are retrieve from a database. The format of this JSON file is
{"people":[{"id":"15","first_name":"Theo","last_name":"Tziomakas","bio":"Hello from
Theo!!!","created":"2015-01-11 21:48:51"},
{"id":"16","first_name":"Jim","last_name":"Chytas","bio":"Hello from Chytas","created":"2015-01-11
21:53:42"}]}.
The idea is to retrieve the "first_name" and "second_name" in a listview. The "bio" should appear in another activity,but I don't know how to do that:(.
Here is my code.
public class MainActivity extends ActionBarActivity {
ListView list;
TextView fname;
TextView lname;
ArrayList<HashMap<String, String>> oslist = new ArrayList<HashMap<String, String>>();
//URL to get JSON Array
private static String url = "http://xxxxxxx/tutorials/index.php";
//JSON Node Names
private static final String TAG_OS = "people";
private static final String TAG_FIRST_NAME = "first_name";
private static final String TAG_SECOND_NAME = "last_name";
//private static final String TAG_BIO = "bio";
JSONArray android = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
oslist = new ArrayList<HashMap<String, String>>();
new JSONParse().execute();
}
private class JSONParse extends AsyncTask<String, String, JSONObject> {
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
fname = (TextView)findViewById(R.id.first_name);
lname = (TextView)findViewById(R.id.last_name);
//abio = (TextView)findViewById(R.id.bio);
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Getting Data ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected JSONObject doInBackground(String... args) {
JSONParser jParser = new JSONParser();
// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrl(url);
return json;
}
#Override
protected void onPostExecute(JSONObject json) {
pDialog.dismiss();
try {
// Getting JSON Array from URL
android = json.getJSONArray(TAG_OS);
for(int i = 0; i < android.length(); i++){
JSONObject c = android.getJSONObject(i);
// Storing JSON item in a Variable
String first_name = c.getString(TAG_FIRST_NAME);
String last_name = c.getString(TAG_SECOND_NAME);
//String bio = c.getString(TAG_BIO);
// Adding value HashMap key => value
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_FIRST_NAME, first_name);
map.put(TAG_SECOND_NAME, last_name);
//map.put(TAG_BIO, bio);
oslist.add(map);
list=(ListView)findViewById(R.id.list);
ListAdapter adapter = new SimpleAdapter(MainActivity.this, oslist,
R.layout.list_v,
new String[] { TAG_FIRST_NAME,TAG_SECOND_NAME }, new int[] {
R.id.first_name,R.id.last_name});
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String bio = ((TextView) view.findViewById(R.id.bio))
.getText().toString();
switch (position) {
case 0:
Intent i = new Intent(MainActivity.this, SingleActivity.class);
i.putExtra("bio", bio);
startActivity(i);
break;
}
}
});
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
And finally I have the SecondActivity class,but nothing is shown when I click the first row of list.
public class SingleActivity extends ActionBarActivity {
TextView text;
JSONArray android = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_single);
text = (TextView)findViewById(R.id.text);
String bio = getIntent().getStringExtra("bio");
try {
JSONObject profileJSON = new JSONObject(bio);
android = profileJSON.getJSONArray(bio);
text.setText(""+android);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Thank you.
EDIT:The problem I had is fixed. Now I want to do something else. Let us suppose that we update the data in an existing row by changing "first_name,"last_name" and finally bio. It is done very easily in phpmyadmin tool. The problem is that the updated row is not shown in the listview. I have to reinstall the app in order to see it. Any ideas in that?
try this ,
replace onPostExecute with this
protected void onPostExecute(JSONObject json) {
pDialog.dismiss();
try {
list=(ListView)findViewById(R.id.list);
// Getting JSON Array from URL
android = json.getJSONArray(TAG_OS);
for(int i = 0; i < android.length(); i++){
JSONObject c = android.getJSONObject(i);
// Storing JSON item in a Variable
String first_name = c.getString(TAG_FIRST_NAME);
String last_name = c.getString(TAG_SECOND_NAME);
//String bio = c.getString(TAG_BIO);
// Adding value HashMap key => value
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_FIRST_NAME, first_name);
map.put(TAG_SECOND_NAME, last_name);
map.put(TAG_BIO, bio);
oslist.add(map);
}
ListAdapter adapter = new SimpleAdapter(MainActivity.this, oslist,
R.layout.list_v,
new String[] { TAG_FIRST_NAME,TAG_SECOND_NAME }, new int[] {
R.id.first_name,R.id.last_name});
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String bio =oslist.get(position).get(TAG_BIO);
// switch (position) {
// case 0:
Intent i = new Intent(MainActivity.this, SingleActivity.class);
i.putExtra("bio", bio);
startActivity(i);
break;
//}
}
});
} catch (JSONException e) {
e.printStackTrace();
}
}
and SingleActivity
text = (TextView)findViewById(R.id.text);
String bio = getIntent().getStringExtra("bio");
text.setText(bio );
Pay attention to what you put in the intent.
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String bio = ((TextView) view.findViewById(R.id.bio))
.getText().toString();
switch (position) {
case 0:
Intent i = new Intent(MainActivity.this, SingleActivity.class);
i.putExtra("bio", bio);
startActivity(i);
break;
}
}
notice that you take the text from a text view and add it to and intent.
When you retreive it use it as if its a json object.
If you want the bio string, you could put that in a variable, and then send it to an intent with just the string.
for example
ListAdapter adapter = new SimpleAdapter(MainActivity.this, oslist,
R.layout.list_v,
new String[] { TAG_FIRST_NAME,TAG_SECOND_NAME }, new int[] {
R.id.first_name,R.id.last_name});
list.setAdapter(adapter);
String bio = c.getString("bio");
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
switch (position) {
case 0:
Intent i = new Intent(MainActivity.this, SingleActivity.class);
i.putExtra("bio", bio);
startActivity(i);
break;
}
}
});
when retrieving it its easier to just do it with
public class SingleActivity extends ActionBarActivity {
TextView text;
JSONArray android = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_single);
text = (TextView)findViewById(R.id.text);
String bio = getIntent().getStringExtra("bio");
text.settext(bio)
}
}
now there is prob some bugs in these example, since i have not java or android sdk installed on my computer

Categories

Resources