How I can parse this json array?
{"1":
{"0":"3","id_disc":"3","1":"Дослідження і проектування компютерних систем","name":"Дослідження і проектування компютерних систем","2":"ДПКМС ","s_name":"ДПКМС "}
,"2":
{"0":"5","id_disc":"5","1":"Цивільний захист і охорона праці в галузі","name":"Цивільний захист і охорона праці в галузі","2":"ЦЗ і ОП","s_name":"ЦЗ і ОП"}
,"3":
{"0":"1","id_disc":"1","1":"Дослідження і проектування інтелектуальних систем (Лекція)","name":"Дослідження і проектування інтелектуальних систем (Лекція)","2":"ДіПІС","s_name":"ДіПІС"}
}
I was trying this method, but I always have null result.
String[] sA = new String[100];
try {
JSONArray cast = getDisc(paraaams).getJSONArray(" ");
for (int i=0; i<cast.length(); i++) {
JSONObject disc = cast.getJSONObject(i);
sA[i-1] = disc.getString("name");
}
}catch (JSONException e){}
// sA[0]=getDisc(paraaams).toString();
ArrayAdapter<String> adapter = new ArrayAdapter<>(getActivity(),
android.R.layout.simple_list_item_1, sA);
listView.setAdapter(adapter);
public JSONArray getDisc(Object params[]){
HTTPWorker httpWorker=new HTTPWorker();
JSONArray mjson =new JSONArray();
String s = httpWorker.doInBackground(params);
try {
mjson = new JSONArray(s);
Log.e("JSONinClass ",mjson.toString());
}catch (JSONException e){}
return mjson;
I think i try to parse it like json object, but i don't know how correct work with json arrays.
Thanks for help:)
my ListFragment:
public class MyFilesActivity extends android.app.Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_myfiles, null);
ListView listView = (ListView) rootView.findViewById(R.id.listView);
String[] sA = new String[100];
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject(getDisc(paraaams).toString());
} catch (JSONException e) {
e.printStackTrace();
}
int i =0;
Iterator<String> iterator = jsonObject.keys();
while (iterator.hasNext()) {
String key = iterator.next();
try {
if (jsonObject.has(key)) {
JSONObject value = jsonObject.getJSONObject(key);
// value is another JSONObject where you can get the "name" from
String name = value.getString("name");
sA[i]=name;
Log.e("value= ", name);
i+=1;
}
} catch (JSONException e) {
// Something went wrong!
e.printStackTrace();
}
}
// sA[0]=getDisc(paraaams).toString();
ArrayAdapter<String> adapter = new ArrayAdapter<>(getActivity(),
android.R.layout.simple_list_item_1, sA);
listView.setAdapter(adapter);
return rootView;
}
I cut it a bit, removed it is not important for the question :)
Try this for your Response to Parse
May Help you
try{
JSONObject jsonObject = new JSONObject(response);
List<String> keyList = getAllKeys(jsonObject);
for(String key : keyList){
JSONObject innerObject = jsonObject.getJSONObject(key);
List<String> innerKeyList = getAllKeys(innerObject);
for(String innerKey: innerKeyList){
System.out.println(innerObject.getString(innerKey));
}
}
}catch(Exception e){
e.printStackTrace();
}
This method will return keys
private List<String> getAllKeys(JSONObject jsonObject) throws JSONException{
List<String> keys = new ArrayList<String>();
Iterator<?> iterator = jsonObject.keys();
while( iterator.hasNext() ) {
String key = (String)iterator.next();
keys.add(key);
}
return keys;
}
try this:
please check below changes replace array to arraylist
public class MyFilesActivity extends android.app.Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_myfiles, null);
ListView listView = (ListView) rootView.findViewById(R.id.listView);
ArrayList<String> sA = new ArrayList<>();
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject(getDisc(paraaams).toString());
} catch (JSONException e) {
e.printStackTrace();
}
Iterator<String> iterator = jsonObject.keys();
while (iterator.hasNext()) {
String key = iterator.next();
try {
if (jsonObject.has(key)) {
JSONObject value = jsonObject.getJSONObject(key);
// value is another JSONObject where you can get the "name" from
String name = value.getString("name");
sA.add(name);
Log.e("value= ", name);
}
} catch (JSONException e) {
// Something went wrong!
e.printStackTrace();
}
}
// sA[0]=getDisc(paraaams).toString();
ArrayAdapter<String> adapter = new ArrayAdapter<>(getActivity(),
android.R.layout.simple_list_item_1, sA);
listView.setAdapter(adapter);
return rootView;
}
Here is a tested code to parse json.
try {
JSONObject json = new JSONObject(json);
int jsonLength = json.length();
for(int i=1; i<=jsonLength; i++){
JSONObject jObject = json.getJSONObject(""+i);
String data = jObject.getString("0");
}
} catch (JSONException e) {
e.printStackTrace();
}
It is just a plain JSONObject not an JSONArray, so you have to cast it to a JSONObject first
JSONObject json = new JSONObject(jsonString);
To loop through it
for (Iterator<String> iter = json.keys(); iter.hasNext();) {
String key = iter.next();
JSONObject value = (JSONObject) json.getJSONObject(key);
String name = value.getString("name");
}
Related
Json File:
{
"Iraq":["Baghdad","Karkh","Sulaymaniyah","Kirkuk","Erbil","Basra","Bahr","Tikrit","Najaf","Al Hillah","Mosul","Haji Hasan","Al `Amarah","Basere","Manawi","Hayat"],
"Lebanon":["Beirut","Zgharta","Bsalim","Halba","Ashrafiye","Sidon","Dik el Mehdi","Baalbek","Tripoli","Baabda","Adma","Hboub","Yanar","Dbaiye","Aaley","Broummana","Sarba","Chekka"]
}
I need to display country name in first spinner and city name in second spinner as per selected countries of spinner.
How to code it android?
My Code:
public class Search_for_room extends Activity {
JSONObject jsonobject;
JSONArray jsonarray;
ProgressDialog mProgressDialog;
ArrayList<String> worldlist;
ArrayList<CollegeList> world;
String value,key;
List<String> al;
ArrayAdapter<String> adapter;
HashMap<String, String> m_li = new HashMap<String, String>();
public ArrayList<SpinnerModel> CustomListViewValuesArr = new ArrayList<SpinnerModel>();
CustomAdapterStatus customAdapter;
Search_for_room activity = null;
Spinner spinner;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search_for_room);
activity = this;
ArrayList<String> items=getCountries("countriesToCities.json");
spinner=(Spinner)findViewById(R.id.spCountry);
spinnerCity=(Spinner)findViewById(R.id.spCity);
}
private ArrayList<String> getCountries(String fileName){
JSONArray jsonArray=null;
ArrayList<String> cList=new ArrayList<String>();
try {
InputStream is = getResources().getAssets().open(fileName);
int size = is.available();
byte[] data = new byte[size];
is.read(data);
is.close();
String json = new String(data, "UTF-8");
JSONObject jsonObj = new JSONObject(json);
// JSONObject resultObject = jsonObj.getJSONObject("result");
System.out.print("======Key: "+jsonObj);
Iterator<String> stringIterator = jsonObj.keys();
while(stringIterator.hasNext()) {
key = stringIterator.next();
value = jsonObj.getString(key);
System.out.println("------------"+key);
m_li.put(key,value);
al = new ArrayList<String>(m_li.keySet());
final SpinnerModel sched = new SpinnerModel();
/******* Firstly take data in model object ******/
sched.setCountryName(value);
// sched.setImage(key);
sched.setStates(key);
/******** Take Model Object in ArrayList **********/
CustomListViewValuesArr.add(sched);
Resources res = getResources();
customAdapter = new CustomAdapterStatus(activity, R.layout.spinner_item, CustomListViewValuesArr,res);
spinner.setAdapter(adapter);
}
}catch (JSONException ex){
ex.printStackTrace();
/*jsonArray=new JSONArray(json);
if (jsonArray != null) {
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jobj = jsonArray.getJSONObject(i);
System.out.pri
//cList.add(String.valueOf(jobj.keys()));
}
}*/
}catch (IOException e){
e.printStackTrace();
}
return cList;
}
}
try this code it can help you
try {
// load json from assets
JSONObject obj = new JSONObject(loadJSONFromAsset());
// than get your both json array
JSONArray IraqArray = obj.getJSONArray("Iraq");
JSONArray LebanonArray = obj.getJSONArray("Lebanon");
// declare your array to store json array value
String Iraq[] = new String[IraqArray.length()];
String Lebanon[] = new String[LebanonArray.length()];
//get json array of Iraq
for (int i = 0; i < IraqArray.length(); i++) {
Iraq[i] = IraqArray.getString(i);
}
//get json array of Lebanon
for (int i = 0; i < LebanonArray.length(); i++) {
Lebanon[i] = LebanonArray.getString(i);
}
} catch (JSONException e) {
e.printStackTrace();
}
ask me in case of any query
add menu item in spinner
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="#+id/spinner"
android:title="Select Week"
app:actionViewClass="android.widget.Spinner"
android:textColor="#android:color/white"
android:textSize="11dp"
app:showAsAction="always" />
</menu>
add your json to array list
public void onPostExecute(String response) {
try {
list.clear();
MatchData vid = null;
Gson gson = new Gson();
JSONObject object = new JSONObject(response);
JSONArray array = object.getJSONArray("items");
for (int i = 0; i < array.length(); i++) {
vid = gson.fromJson(array.getJSONObject(i).toString(), MatchData.class);
list.add(vid);
}
matchDataAdapter = new MatchDataAdapter(MainActivity.this, list);
mRecyclerView.setAdapter(matchDataAdapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
finally set adapter to spinner
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.android_action_bar_spinner_menu, menu);
MenuItem item = menu.findItem(R.id.spinner);
Spinner spinner = (Spinner) MenuItemCompat.getActionView(item);
**ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, lists);**
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(dataAdapter);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String selected = (String) parent.getSelectedItem();
Toast.makeText(getApplicationContext(),selected,Toast.LENGTH_LONG).show();
week = Integer.parseInt(selected);
requestforinfo();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
return true;
}
You had done everything correct uptil now. Just make my suggestion and you are good to go with long list of JSON data.
First make the JSON Response of file accessible to whole activity/fragment by declaring at top.
Added following function to retrieve cityList of particular country:
private ArrayList<String> getCityList(String countryName){
ArrayList<String> cityList = new ArrayList<>();
//Here jsonObj is the your JSON response from the file.
try {
JSONArray jArray =jsonObj.getJSONArray(countryName);
for(int i=0;i<jArray.length();i++){
cityList.add(jArray.getString(i));
}
} catch (JSONException e) {
e.printStackTrace();
}
return cityList;
}
Then add on spinnerItemSelected call the below function:
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String selected = ((SpinnerModel) parent.getSelectedItem()).getCountryName();
//For sake of your answer I had used String Array and ArrayAdapter. You can modify as you want.
ArrayAdapter<String> cityAdapter = new ArrayAdapter<String>(YourActivity.this, R.layout.single_textview,getCityList(selected));
spinnerCity.setAdapter(cityAdapter);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
I am getting below JSON response and I have to store both the data in spinner but when I select Alabama the "AL" in toast message should be used. How can I do this?
{
"status" : "success",
"data" : {
"AL" : "Alabama",
"AK" : "Alaska"
}
}
Try
JSONObject jsonObject = new JSONObject(jsonString);
String status = jsonObject.getString("status");
List<String> data = new ArrayList<String>();
JSONArray array = jsonObject.getJSONArray("data");
Iterator<String> keys = jsonObject.keys();
while (keys.hasNext()) {
String key = keys.next();
String value = jsonObject.getString(key);
}
Try this my friend
JSONObject jsonObject = new JSONObject(response);
Iterator<String> keys = jsonObject.keys();
while (keys.hasNext()) {
String key = keys.next();
String value = jsonObject.getString(key);
Log.v("**********", "**********");
Log.v("category key", key);
Log.v("category value", value);
String firstChar = String.valueOf(value.charAt(0));
if (firstChar.equalsIgnoreCase("{")) {
JSONObject innerJObject = jsonObject.getJSONObject(key);
Iterator<String> innerkeys = innerJObject.keys();
String innerkey = innerkeys.next();
String innervalue = innerJObject.getString(innerkey);
Log.v("**********", "**********");
Log.v("inner key", innerkey);
Log.v("inner value", innervalue);
}
}
Hello Try this if it helps
public class MainActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
List<City>cityList= new ArrayList<>();
List<String> cityListName= new ArrayList<>();
Spinner spnCity;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
spnCity=(Spinner)findViewById(R.id.spnCity);
String response="{\"status\":\"success\",\"data\":{\"AL\":\"Alabama\",\"AK\":\"Alaska\"}}";
try {
JSONObject iObject=new JSONObject(response);
JSONObject data=iObject.getJSONObject("data");
Iterator<String> iter = data.keys();
while (iter.hasNext()) {
String key = iter.next();
try {
Object value = data.get(key);
cityListName.add(value.toString());
cityList.add(new City(key,value.toString()));
} catch (JSONException e) {
}
}
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, cityListName);
// Drop down layout style - list view with radio button
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
spnCity.setAdapter(dataAdapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
String item = adapterView.getItemAtPosition(i).toString();
for (int j = 0; j < cityList.size(); j++) {
if(cityList.get(j).getCityName().equals(item)){
Toast.makeText(adapterView.getContext(), "Selected: " + item +" "+cityList.get(j).getCityName(), Toast.LENGTH_LONG).show();
}
}
// Showing selected spinner item
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
}
I am beginner to android app. I am facing trouble how to parse json object and json array to listview in android. Here is my json output
UPDATED WITH JSON CORRECTION
{status: "ok", listUsers: [{"id":2,"username":"myusername","name":"myname","email":"myemail","password":"mypassword","groupid":1,"type":"mytype"},{"id":3,"username":"myusername","name":"myname","email":"myemail2","password":"mypassword2","groupid":1,"type":"mytype"},{"id":4,"username":"username1","name":"name1","email":"email1","password":"pass1","groupid":1,"type":"type1"},{"id":5,"username":"username1","name":"name1","email":"email1","password":"pass1","groupid":1,"type":"type1"},{"id":6,"username":"username1","name":"name1","email":"email1","password":"pass1","groupid":1,"type":"type1"},{"id":7,"username":"username1","name":"name1","email":"email1","password":"pass1","groupid":1,"type":"type1"},{"id":8,"username":"username1","name":"name1","email":"email1","password":"pass1","groupid":1,"type":"type1"},{"id":9,"username":"username1","name":"name1","email":"email1","password":"pass1","groupid":1,"type":"type1"},{"id":10,"username":"username1","name":"name1","email":"email1","password":"pass1","groupid":1,"type":"type1"},{"id":11,"username":"username1","name":"name1","email":"email1","password":"pass1","groupid":1,"type":"1"},{"id":12,"username":"username1","name":"name1","email":"email1","password":"pass1","groupid":1,"type":"type1"},{"id":13,"username":"yuwah","name":"yu","email":"mail#gmail.com","password":"pass1","groupid":1,"type":"type1"},{"id":14,"username":"myusername","name":"myname","email":"myemail2","password":"mypassword2","groupid":1,"type":"mytype"}] }
Can anyone explain me how to do it. I am searching all over the topics but I still can't get it. Thanks.
Here is my code block
public class MainActivity extends ListActivity {
String url = "http://staging.workberryplus.com/mobile/listUsers/1";
ProgressDialog PD;
ArrayList<String> listUsers;
ArrayAdapter<String> adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
listUsers = new ArrayList<String>();
PD = new ProgressDialog(this);
PD.setMessage("Loading.....");
PD.setCancelable(false);
adapter = new ArrayAdapter(this, R.layout.items, R.id.tv, listUsers);
setListAdapter(adapter);
MakeJsonArrayReq();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
}
private void MakeJsonArrayReq() {
PD.show();
//JsonArrayRequest jr=new JsonArrayRequest(url, listener, errorListener)
final StringRequest jreq = new StringRequest(url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
for (int i = 0; i < response.length(); i++) {
try {
Log.d("Response","->"+response);
JSONObject jo = new JSONObject(response);
JSONArray jarray = jo.getJSONArray("listUsers");
JSONObject jo2 = jarray.getJSONObject(i);
String name = jo2.getString("name");
listUsers.add(name);
} catch (JSONException e) {
e.printStackTrace();
}
}
PD.dismiss();
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
MyApplication.getInstance().addToReqQueue(jreq, "jreq");
}
}
try {
JSONObject jo = new JSONObject(response);
JSONArray jarray =jo.getJSONArray("listUsers");
for (int i = 0; i < jarray.length(); i++){
JSONObject jo2 = jarray.getJSONObject(i);
String name = jo2.getString("name");
listUsers.add(name);
}
} catch (JSONException e) {
e.printStackTrace();
}
Convert your String which is response to Json Object
JSONObject jsonObj = new JSONObject(response);
Then do the following
try {
if (jsonObj != null) {
if (jsonObj.optString("status").equals("ok")) {
JSONArray jsonArray = jsonObj.optJSONArray("listUsers");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.optJSONObject(i);
if (jsonObject != null) {
//Do work here
}
}
}
}
}catch (Exception e1) {
e1.printStackTrace();
}
try this and make changes accordingly and let me know if it work for you or not
JSONObject jo2 = jarray.getJSONObject(i);
You are iterating over the length of the response (a string). You should iterate over the length of jarray
How can display the selected item first in spinner list?
Assume Rainy was retrieved from MySQL and now it should display the Rainy item first. How do I achieve this ?
Spinner Weather;
private void showEmployee(String json){
try {
JSONObject jsonObject = new JSONObject(json);
JSONArray result = jsonObject.getJSONArray(Config.TAG_JSON_ARRAY);
JSONObject c = result.getJSONObject(0);
String weather = c.getString(Config.TAG_WEATHER);
RetrieveWeather(weather);
// what should add here
} catch (JSONException e) {
e.printStackTrace();
}
}
public void RetrieveWeather(String a)
{
String[] arr = new String[]{"Sunny","Cloudy","Rainy","Thunderstorm"};
List<String> list = new ArrayList<String>();
String weather = a;
list.add(weather);
for(String s:arr){
if(!list.contains(s)){
list.add(s);
}
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_dropdown_item, list);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
Weather.setAdapter(adapter);
}
Try the following:
Spinner Weather;
String weather;
int pos = 0;
String[] arr = new String[]{"Sunny","Cloudy","Rainy","Thunderstorm"};
private void showEmployee(String json){
try {
JSONObject jsonObject = new JSONObject(json);
JSONArray result = jsonObject.getJSONArray(Config.TAG_JSON_ARRAY);
JSONObject c = result.getJSONObject(0);
weather = c.getString(Config.TAG_WEATHER);
RetrieveWeather(weather);
// what should add here
Weather.setSelection(pos);
} catch (JSONException e) {
e.printStackTrace();
}
}
public void RetrieveWeather(String a)
{
List<String> list = new ArrayList<String>();
String weather = a;
list.add(weather);
for(String s:arr){
if(!list.contains(s)){
list.add(s);
}
}
for(int i=0;i<list.size();i++)
{
if(weather.equals(list.get(i)))
{
pos = i;
}
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_dropdown_item, list);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
Weather.setAdapter(adapter);
}
I want to get data from php, then show in listview. But I do not know not to tell the listview update the data I have got for php. I have try to use notifyDataSetChanged();, but I do know where should it put.
public class List_View extends ListFragment{
private String result;
private ListView listView;
private ArrayList<String> items = new ArrayList<String>();
final String uri = "http://localhost/userinfo.php";
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View rootView = inflater.inflate(R.layout.list, container, false);
setListAdapter(new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, items));
return rootView;
}
class sendPostRunnable implements Runnable{
#Override
public void run(){
result = sendPostDataToInternet();
String temp = "Not result.";
try {
JSONTokener jsonTokener = new JSONTokener(result);
JSONObject jsonObject = (JSONObject) jsonTokener.nextValue();
JSONArray jarray = jsonObject.getJSONArray("response");
for (int i = 0; i < jarray.length(); i++) {
temp = "";
JSONObject jobject = jarray.getJSONObject(i);
temp += "name: "+jobject.getString("name")+"\n";
temp += "email: "+jobject.getString("email");
items.add(temp);
temp = "";
}
if(jarray.length() < 1){
items.add(temp);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private String sendPostDataToInternet(){
HttpPost httpRequest = new HttpPost(uri);
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("uid", "u1"));
try{
httpRequest.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
HttpResponse httpResponse = new DefaultHttpClient().execute(httpRequest);
if (httpResponse.getStatusLine().getStatusCode() == 200){
String strResult = EntityUtils.toString(httpResponse.getEntity());
return strResult;
}
} catch (Exception e){
e.printStackTrace();
}
return null;
}
}
You should collect all arrived data in other collection (other than used in list adapter) in separate thread and then replace the list colletion source and right after than you should call notifyDataSetChanged().
public class List_View extends ListFragment{
private String result;
private ListView listView;
protected List newData;
protected ArrayAdapter listAdapter;
private ArrayList<String> items = new ArrayList<String>();
final String uri = "http://localhost/userinfo.php";
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View rootView = inflater.inflate(R.layout.list, container, false);
listAdapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, items);
setListAdapter(listAdapter );
return rootView;
}
class sendPostRunnable implements Runnable{
#Override
public void run(){
result = sendPostDataToInternet();
String temp = "Not result.";
// a new collection to fill from response
newData = new ArrayList<String>();
try {
JSONTokener jsonTokener = new JSONTokener(result);
JSONObject jsonObject = (JSONObject) jsonTokener.nextValue();
JSONArray jarray = jsonObject.getJSONArray("response");
for (int i = 0; i < jarray.length(); i++) {
temp = "";
JSONObject jobject = jarray.getJSONObject(i);
temp += "name: "+jobject.getString("name")+"\n";
temp += "email: "+jobject.getString("email");
//here you should create a corresponding object from JSON
// and add it to newData List
newData .add(temp);
temp = "";
}
if(jarray.length() < 1){
items.add(temp);
}
// here you will have a newData List filled so you should
// replace or add data from this List to ListView's used
items.add(newData);
listAdapter.notifyDataSetChanged();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private String sendPostDataToInternet(){
HttpPost httpRequest = new HttpPost(uri);
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("uid", "u1"));
try{
httpRequest.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
HttpResponse httpResponse = new DefaultHttpClient().execute(httpRequest);
if (httpResponse.getStatusLine().getStatusCode() == 200){
String strResult = EntityUtils.toString(httpResponse.getEntity());
return strResult;
}
} catch (Exception e){
e.printStackTrace();
}
return null;
}
}