I can't retrieve data using JSON parsing - android

{
"user": {
"name": ["bineesh", "Administrator", "binu", "binu", "bijith", "prem"]
},
"email": ["bineesh256#gmail.com", "erpadmin#gmail.com", "binu245#gmail.com", "binu245#gmail.com", "bijith256#gmail.com", "toast#gmail.com"],
"phone": ["7293553814", "12345", "0", "0", "0", "9046567239"]
}
I can't parse this response:
Object(result);
// JSONObject jObject;
// jObject= new JSONObject(result);
JSONArray ja = new JSONArray(result);
for (int i = 0; i < ja.length(); i++) {
JSONObject jo = (JSONObject) ja.get(i);
System.out.println(jo.getString("name"));
}
How can I see this response in listview?

Sample code:
public class HomeActivity extends ListActivity {
/** Called when the activity is first created. */
#SuppressWarnings({ "rawtypes", "unchecked" })
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setListAdapter(new ArrayAdapter(this, android.R.layout.simple_list_item_1, this.fetchTwitterPublicTimeline()));
}
public ArrayList<String> fetchTwitterPublicTimeline()
{
ArrayList<String> listItems = new ArrayList<String>();
try {
URL twitter = new URL(
"http://twitter.com/statuses/public_timeline.json");
URLConnection tc = twitter.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(
tc.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
JSONArray ja = new JSONArray(line);
for (int i = 0; i < ja.length(); i++) {
JSONObject jo = (JSONObject) ja.get(i);
listItems.add(jo.getString("text"));
}
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return listItems;
}
}

sample code :
public void parse(String s){
try {
JSONObject jsonObject = new JSONObject(s);
JSONObject namejObj = jsonObject.getJSONObject("user");
JSONArray nameArray = namejObj.getJSONArray("name");
for(int i =0;i<nameArray.length();i++){
Log.i("System out","name : "+nameArray.getString(i).toString());
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

You can use below method to parse JSON file
JSONObject obj = new JSONObject(result);
JSONObject objUser = obj.getJSONObject("user");
JSONArray arrUser = objUser.getJSONArray("name");
for(int i=0;i<arrUser.length();i++)
{
String name = arrUser.getString(i);
}
JSONArray arrEmail = objUser.getJSONArray("email");
for(int i=0;i<arrEmail.length();i++)
{
String email = arrEmail.getString(i);
}
JSONArray arrPhone = objUser.getJSONArray("phone");
for(int i=0;i<arrPhone.length();i++)
{
String phone = arrPhone.getString(i);
}

Related

How to put json array in json object

This is code which I'm using:
#Override
protected String doInBackground(String... arg0) {
String yourJsonStringUrl = "GetCalender_Events";
JsonParser jParser = new JsonParser();
json = jParser.getJSONFromUrlArray(yourJsonStringUrl);
return null;
}
#Override
protected void onPostExecute(String strFromDoInBg) {
for (int i = 0; i < json.length(); i++) {
try {
JSONObject c = json.getJSONObject(i);
ldatosAgenda.add(new DatosAgenda(c.getString("Event_Name"), c.getString("Event_Name"),
sdf5.format(sdf1.parse(c.getString("Column1"))), sdf6.format(sdf1.parse(c.getString("Column1"))),
c.getString("Description")));
} catch (JSONException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
}
}
How to put my JSON Array into JSON object? Can anyone please help me, this is my first try with JSON Array.
My array looks like this:
{
"ContactList": [
{
"Column1": "22-05-2017",
"Event_Name": "Garba Compition",
"Description": "School organized garba compition"
},
{
"Column1": "24-05-2017",
"Event_Name": "Mahendi Compition",
"Description": "Mahendi compition"
}
]
}
#. Seems you are getting JSONObject as response. So you have to parse JSONObject first from sever response:
JSONObject json = jParser.getJSONFromUrlObject(yourJsonStringUrl);
#. Then parse ContactList and its item as below:
#Override
protected void onPostExecute(String strFromDoInBg) {
JSONArray jsonArray = json.getJSONArray("ContactList");
for (int i = 0; i < jsonArray.length(); i++) {
try
{
JSONObject c = jsonArray.getJSONObject(i);
ldatosAgenda.add(new DatosAgenda(c.getString("Event_Name"),c.getString("Event_Name"), sdf5.format(sdf1.parse(c.getString("Column1"))), sdf6.format(sdf1.parse(c.getString("Column1"))),c.getString("Description")));
} catch (JSONException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
}
}
JSONArray jsonarray = new JSONArray();
JSONObject jsonObject = new JSONObject();
try{
jsonObject.put(jsonarray);
} catch(JSONException e){
e.printStackTrace();
}
You get the values
JSONArray songobj = json.getJSONArray("ContactList");
Log.d(TAG, "List Length" + songobj.length());
for (int i = 0; i < songobj.length(); i++) {
JSONObject song = songobj.getJSONObject(i);
String column=song.getString("Column1");
String name=song.getString("Event_Name");
String desc=song.getString("Description");
ldatosAgenda.add(new DatosAgenda(column,name,desc));
}
}

how to parse JsonArray and set value on Textview in Android

Below is my Json response from getting when Hit on Url with parsing parameter strlogid=101
[
{
"earnpoints": 411,
"type": "C"
},
{
"earnpoints": 1600,
"type": "G"
},
{
"earnpoints": 13540,
"type": "I"
}
]
Below is my code-To show Points on 3 different textview
private class PointTask extends AsyncTask<String, Void, Boolean> {
protected Boolean doInBackground(final String... args) {
JSONParse jParser = new JSONParse();
HashMap<String, String> hMap = new HashMap<>();
hMap.put("strlogid", "101");
JSONArray jsonarray = jParser.getJSONFromUrl(url,hMap);
// get JSON data from URL
for (int i = 0; i < jsonarray.length(); i++) {
try {
JSONObject c = (JSONObject) jsonarray.get(i);
c_point=c.getString("points");
g_point=c.getString("points");
i_point=c.getString("points");
t_point = cpoint+gpoint+ipoint;
} catch (JSONException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(final Boolean success) {
txtTotalPoints.setText(t_point);
txtOwnPoints.setText(g_point);
txtClubPoints.setText(c_point);
txtVoucherPoints.setText(i_point);
}
}
TotalPoints,OwnPoints,ClubPoints,VoucherPoints are show on Textview respectively
Try this
protected Boolean doInBackground(final String... args) {
JSONParse jParser = new JSONParse();
HashMap<String, String> hMap = new HashMap<>();
hMap.put("strlogid", "101");
JSONArray jsonarray = jParser.getJSONFromUrl(url,hMap);
// get JSON data from URL
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject c = (JSONObject) jsonarray.get(i);
if (c.getString("type").toString().equalsIgnoreCase("C")) {
c_point = c.getInt("earnpoints");
} else if (c.getString("type").toString().equalsIgnoreCase("G")) {
g_point = c.getInt("earnpoints");
} else if (c.getString("type").toString().equalsIgnoreCase("I")) {
i_point = c.getInt("earnpoints");
}
}
t_point = cpoint + gpoint + ipoint;
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(final Boolean success) {
txtTotalPoints.setText(t_point);
txtOwnPoints.setText(g_point);
txtClubPoints.setText(c_point);
txtVoucherPoints.setText(i_point);
}
}
Dont use async task for json parsing. I would reccomend you to use volley.
Here is the link\
http://www.androidhive.info/2014/05/android-working-with-volley-library-1/
#Override
public void onPostSuccess(String result, int id, boolean isSucess) {
// Log.e("re<><><><>", result);
try {
JSONArray ja = new JSONArray(result);
for (int arr = 0; arr < ja.length(); arr++) {
JSONObject json1 = ja.getJSONObject(arr);
Log.e("length", "" + ja.length());
// Getting JSON Array node
String earnpoints= json1.getString("earnpoints");
String type = json1.getString("type");
}
catch (JSONException e) {
e.printStackTrace();
Toast.makeText(LoginPage.this, "Please try again later", Toast.LENGTH_SHORT).show();
}
}

how to parse json object and json array in listview android

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 to Parse the JSON response which contains the two arraylist

I am having the response of one of webservice to get the feeds list and in that response i am getting the two array with the same name.
The problem is that i am not able get the details of the inner array i.e. "ProfileName", "ImageUrl" etc..
I have tried the json parsing.
Below is the response of JSON:
{"Status":true,
"result":
[
{"result": [
{"ProfileName":"followers5","ImageUrl":"http:\/\/192.168.0.1\/webservice2\/uploads\/81.png","Likes":3,"Hearts":2},
{"ProfileName":"followers5","VideoUrl":"http:\/\/192.168.0.1\/webservice2\/uploads\/81.mp4","Likes":0,"Hearts":0}
]}
,{"result":[
{"ProfileName":"followers6","ImageUrl":"http:\/\/192.168.0.1\/webservice2\/uploads\/82.png","Likes":0,"Hearts":2},
{"ProfileName":"followers6","VideoUrl":"http:\/\/192.168.0.1\/webservice2\/uploads\/82.mp4","Likes":0,"Hearts":0}
]}
]
}
I have tried as below:
class feedtask extends AsyncTask<String, Integer, String> {
#Override
protected String doInBackground(String... params) {
Httputils getmethod = new Httputils();
try {
result = getmethod.Getrequest("feeds.php?uid=76");
System.out.println("Feeds Result--->" + result);
JSONObject jobj = new JSONObject(result);
JSONArray ja = jobj.getJSONArray("result");
for (int i = 0; i < ja.length(); i++) {
for (int j = 0; j <= i; j++) {
JSONObject jo = ja.getJSONObject(j);
abcd.add(jo.getString("ProfileName"));
System.out.println("Profile Name--->"
+ jo.getString("ProfileName"));
}
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
}
Please help me out to get the details of the second array.
Any help will be appreciated.
Thank you.
try
{
JSONObject _JSONResponse=new JSONObject(response);
String status=_JSONResponse.getString("Status");
JSONArray _ArrayResponse=_JSONResponse.getJSONArray("result");
for(int i=0;i<_ArrayResponse.length();i++)
{
JSONArray object=_ArrayResponse.getJSONObject(i).getJSONArray("result");
for(int j=0;j<object.length();j++)
{
JSONObject jObject=object.getJSONObject(j);
ProfileName=jObject.getString("ProfileName") ;
VideoUrl=jObject.optString("VideoUrl") ;
Likes=jObject.optString("Likes") ;
Hearts=jObject.optString("Hearts") ;
Log.i(TAG,ProfileName +" "+VideoUrl +" "+Likes+" " +Hearts);
}
}
}
catch(JSONException e){Log.e(TAG,e.toString());}
try{
JSONObject responseJson = new JSONObject(response);
if(responseJson.has("result")){
JSONArray resultJsonArr = responseJson.getJSONArray("result");
for(int i=0; i<resultJsonArr.length(); i++){
JSONObject resultInstanceJson = resultJsonArr.getJSONObject(i);
if(resultInstanceJson.has("result")){
JSONArray resultArr = resultInstanceJson.getJSONArray("result");
for(int j=0; j<resultArr.length(); j++){
JSONObject jsonResult = resultArr.getJSONObject(j);
String profileNAme = jsonResult.getString("ProfileName");
String imageUrl = "", videoUrl = "";
//image url
if(jsonResult.has("ImageUrl")){
imageUrl = jsonResult.getString("ImageUrl");
}
//video url
if(jsonResult.has("VideoUrl")){
videoUrl = jsonResult.getString("VideoUrl");
}
}
}
}
}
}catch(Exception e){
e.printStackTrace();
}
try this way
for (int i = 0; i < ja.length(); i++) {
JSONObject jo = ja.getJSONObject(i);
JSONArray innerResult = jo.getJSONArray("result");
int size = innerResult.legth();
for (int j = 0; j < size; j++) {
JSONObject innerJo = innerResult.getJSONObject(j);
abcd.add(innerJo.getString("ProfileName"));
}
}
Edit:
public class InfoHolder {
public String profileName;
public String imageUrl;
public String videUrl;
}
for (int j = 0; j < size; j++) {
InfoHolder holder = new InfoHolder();
JSONObject innerJo = innerResult.getJSONObject(j);
// the same for imageUrl and videoUrl
holder.profileName = innerJo.getString("ProfileName");
abcd.add(holder);
}
of course you have to change from String to InfoHolder your abcd collectio
Try this:
try {
result = getmethod.Getrequest("feeds.php?uid=76");
System.out.println("Feeds Result--->" + result);
JSONObject jobj = new JSONObject(result);
JSONArray ja = jobj.getJSONArray("result");
for (int i = 0; i < ja.length(); i++) {
for (int j = 0; j < i; j++) {
JSONObject jo = ja.getJSONObject(j);
JSONArray resultJA = jo.getJSONArray("result");
for(int k=0;k< resultJA.length();k++){
JSONObject jo_inside = resultJA.getJSONObject(k);
String profileName = jo_inside.getString("ProfileName");
//use optString on JSONOBject. it will return empty String if that key does not exists or else the value u want. it won't give any exceptions.
String ImageURL = jo_inside.optString("ImageUrl");
String VideoURL = jo_inside.optString("VideoUrl");
}
}
}
}
catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
}
You do
for (int i = 0; i < ja.length(); i++) {
ok for the first array now you need to get the array inside each cells of the first
For example :
JSONObject jo = ja.getJSONObject(i);
JSONArray ja2 = jo.getJSONArray("result");
then and only then you do the second loop
Maybe this answer isn't complete but the idea is here

Android App: JSON array from web to listview

I'm just trying to get a simple JSON array in the following format: ["Country1","Country2","Country3"] from the web and then use that array as a listview in my android app. I'm not stuck on how to make this JSON array, i'm just confused on how to get it into a listview in the app.
I have tried a few different tutorials, but none of them are using the same layout as such as mine.
My app is using a viewflipper, to keep a tabbased layout in view at all times throughout the app, therefore none of the tutorials seem to be working with my layout.
Any help is much appreciated.
EDIT:
Here's some code, yes i want to parse it from a web service and display it in a listview.
public class Activity extends TabActivity implements OnClickListener {
Button doSomething;
TabHost tabHost;
ViewFlipper flipper;
ListView listview;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tablayout_1);
doSomething = (Button) findViewById(R.id.btn_do_something);
doSomething.setOnClickListener(this);
flipper = (ViewFlipper) findViewById(R.id.layout_tab_one);
listview = (ListView) findViewById(R.id.listview);
#SuppressWarnings("unchecked")
ListAdapter adapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1,fetchTwitterPublicTimeline());
//ListAdapter adapter = new SimpleAdapter(this, this.fetchTwitterPublicTimeline() , R.layout.main, new int[] { R.id.item_title, R.id.item_subtitle });
listview.setAdapter(adapter);
flipper.setOnClickListener(this);
String tabname1 = getString(R.string.tabexample_tab1);
String tabname2 = getString(R.string.tabexample_tab2);
String tabname3 = getString(R.string.tabexample_tab3);
String tabname4 = getString(R.string.tabexample_tab4);
tabHost = getTabHost();
tabHost.addTab(tabHost.newTabSpec("tab1").setContent(R.id.layout_tab_one).setIndicator(tabname1));
tabHost.addTab(tabHost.newTabSpec("tab2").setContent(R.id.layout_tab_two).setIndicator(tabname2));
tabHost.addTab(tabHost.newTabSpec("tab3").setContent(R.id.layout_tab_three).setIndicator(tabname3));
tabHost.addTab(tabHost.newTabSpec("tab4").setContent(R.id.layout_tab_four).setIndicator(tabname4));
tabHost.setCurrentTab(0);
listview.setOnItemClickListener(new OnItemClickListener(){
public void onItemClick(AdapterView<?> a, View v, int position, long id) {
flipper.showNext();
}});
}
public ArrayList<String> fetchTwitterPublicTimeline()
{
ArrayList<String> listItems = new ArrayList<String>();
try {
URL twitter = new URL(
"JSON.php");
URLConnection tc = twitter.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(
tc.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
JSONArray ja = new JSONArray(line);
for (int i = 0; i < ja.length(); i++) {
JSONObject jo = (JSONObject) ja.get(i);
listItems.add(jo.getString(""));
}
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return listItems;
}
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
}
}
UPDATE: I still can't get it working, any ideas what's wrong in the code below?
public class Activity extends TabActivity implements OnClickListener {
Button doSomething;
TabHost tabHost;
ViewFlipper flipper;
ListView listview;
HttpResponse re;
String json;
JSONObject j;
#SuppressWarnings("deprecation")
#Override
protected void onCreate(Bundle savedInstanceState) {
//final String TAG = "MainActivity";
//final String URL = "JSON.php";
super.onCreate(savedInstanceState);
setContentView(R.layout.tablayout_1);
final String[] listItems = new String[] { };
/*========================================
// JSON object to hold the information, which is sent to the server
JSONObject jsonObjSend = new JSONObject();
try {
// Add key/value pairs
jsonObjSend.put("key_1", "value_1");
jsonObjSend.put("key_2", "value_2");
// Add a nested JSONObject (e.g. for header information)
JSONObject header = new JSONObject();
header.put("deviceType","Android"); // Device type
header.put("deviceVersion","2.0"); // Device OS version
header.put("language", "es-es"); // Language of the Android client
jsonObjSend.put("header", header);
// Output the JSON object we're sending to Logcat:
Log.i(TAG, jsonObjSend.toString(2));
} catch (JSONException e) {
e.printStackTrace();
}
// Send the HttpPostRequest and receive a JSONObject in return
JSONObject jsonObjRecv = HTTPClient.SendHttpPost(URL, jsonObjSend);
String temp = jsonObjRecv.toString();
/*==============================================*/
doSomething = (Button) findViewById(R.id.btn_do_something);
doSomething.setOnClickListener(this);
flipper = (ViewFlipper) findViewById(R.id.layout_tab_one);
listview = (ListView) findViewById(R.id.listview);
/* try {
JSONArray array = jsonObjRecv.getJSONArray(""); //(JSONArray) new JSONTokener(json).nextValue();
String[] stringarray = new String[array.length()];
for (int i = 0; i < array.length(); i++) {
stringarray[i] = array.getString(i);
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, stringarray);
listview.setAdapter(adapter);
} catch (JSONException e) {
// handle JSON parsing exceptions...
}*/
//#SuppressWarnings("unchecked")
ListAdapter adapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1,fetchTwitterPublicTimeline());
//ListAdapter adapter = new SimpleAdapter(this, this.fetchTwitterPublicTimeline() , R.layout.main, new int[] { R.id.item_title, R.id.item_subtitle });
listview.setAdapter(adapter);
flipper.setOnClickListener(this);
String tabname1 = getString(R.string.tabexample_tab1);
String tabname2 = getString(R.string.tabexample_tab2);
String tabname3 = getString(R.string.tabexample_tab3);
String tabname4 = getString(R.string.tabexample_tab4);
tabHost = getTabHost();
tabHost.addTab(tabHost.newTabSpec("tab1").setContent(R.id.layout_tab_one).setIndicator(tabname1));
tabHost.addTab(tabHost.newTabSpec("tab2").setContent(R.id.layout_tab_two).setIndicator(tabname2));
tabHost.addTab(tabHost.newTabSpec("tab3").setContent(R.id.layout_tab_three).setIndicator(tabname3));
tabHost.addTab(tabHost.newTabSpec("tab4").setContent(R.id.layout_tab_four).setIndicator(tabname4));
tabHost.setCurrentTab(0);
listview.setOnItemClickListener(new OnItemClickListener(){
public void onItemClick(AdapterView<?> a, View v, int position, long id) {
flipper.showNext();
}});
}
public ArrayList<String> fetchTwitterPublicTimeline()
{
ArrayList<String> listItems = new ArrayList<String>();
try {
URL twitter = new URL(
"JSON.php");
URLConnection tc = twitter.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(
tc.getInputStream()));
String line = null;
//make sure youe String line is completely filled after that..
if (!line.equals(null) && !line.equals("") && line.startsWith("["))
{
JSONArray jArray = new JSONArray(line);
for (int i = 0; i < jArray.length(); i++)
{
JSONObject jobj = jArray.getJSONObject(i);
// also make sure you get the value from the jsonObject using some key
// like, jobj.getString("country");
listItems.add(jobj.getString(""));
}
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return listItems;
}
/* public ArrayList<String> fetchTwitterPublicTimeline()
{
ArrayList<String> listItems = new ArrayList<String>();
try {
URL twitter = new URL(
"JSON.php");
URLConnection tc = twitter.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(
tc.getInputStream()));
//make sure youe String line is completely filled after that..
if (!line.equals(null) && !line.equals("") && line.startsWith("["))
{
JSONArray jArray = new JSONArray(line);
for (int i = 0; i < jArray.length(); i++)
{
JSONObject jobj = jArray.getJSONObject(i);
// also make sure you get the value from the jsonObject using some key
// like, jobj.getString("country");
listItems.add(jobj.getString(""));
}
}
/* String line;
while ((line = in.readLine()) != null) {
JSONArray ja = new JSONArray(line);
for (int i = 0; i < ja.length(); i++) {
JSONObject jo = (JSONObject) ja.get(i);
listItems.add(jo.getString(""));
}
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return listItems;
}*/
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
}
}
Update, here are the values of jArray as reported by Logcat:
08-26 16:49:07.246: VERBOSE/app(472): jarray value: ["Country1","Country2","Country3"]
These are the correct values!
This works in a simple test app I just created...
ListView list = (ListView) findViewById(...);
String json = "[\"Country1\",\"Country2\",\"Country3\"]";
try {
JSONArray array = (JSONArray) new JSONTokener(json).nextValue();
String[] stringarray = new String[array.length()];
for (int i = 0; i < array.length(); i++) {
stringarray[i] = array.getString(i);
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, stringarray);
list.setAdapter(adapter);
} catch (JSONException e) {
// handle JSON parsing exceptions...
}

Categories

Resources