I am parsing json data and i have 2 array. I have successfully parse the 1st json array "item" ,now i have no idea how i can parse 2nd "img".
Here is my code :
{
"item": [
{
"description": "بافت عالی با قاب",
"price": "11000000000000",
"country": "ايران",
"address": "کوچه مهران یک پلاک7",
"region": "البرز",
"city": "کرج",
"mobile": null,
"cat": "حیوانات و مناظر طبیعی",
"img": [
"http://tajerfarsh.com/oc-content/themes/tgsh/images/slider/slider11.jpg",
"http://tajerfarsh.com/oc-content/themes/tgsh//images/categorys/109.jpg",
"http://tajerfarsh.com/oc-content/themes/tgsh//images/categorys/125.jpg"
]
}
]
}
and here is android side code :
public class ParseJSON1 {
public static String[] ids;
public static String[] descriptions;
public static String[] email;
public static String[] country;
public static String[] address;
public static String[] region;
public static String[] city;
public static String[] cat;
public static String[] image;
public static String[] mobiles;
public static final String JSON_ARRAY = "item";
public static final String KEY_ID = "id";
public static final String DESCCRIPTION = "description";
public static final String EMAIL = "emails";
public static final String COUNTRY = "country";
public static final String ADDRESS = "address";
public static final String REGION = "region";
public static final String CITY = "city";
public static final String CATEGORY = "cat";
public static final String IMAGE = "img";
public static final String MOBILE = "mobile";
private JSONArray users = null;
private String json;
public ParseJSON1(String json){
this.json = json;
}
protected void parseJSON1(){
JSONObject jsonObject=null;
try {
jsonObject = new JSONObject(json);
users = jsonObject.getJSONArray(JSON_ARRAY);
ids = new String[users.length()];
descriptions = new String[users.length()];
country = new String[users.length()];
address = new String[users.length()];
region = new String[users.length()];
city = new String[users.length()];
cat = new String[users.length()];
email = new String[users.length()];
mobiles = new String[users.length()];
for(int i=0;i<users.length();i++){
JSONObject jo = users.getJSONObject(i);
ids[i] = jo.getString(KEY_ID);
descriptions[i] = jo.getString(DESCCRIPTION);
email[i] = jo.getString(EMAIL);
country[i] = jo.getString(COUNTRY);
address[i] = jo.getString(ADDRESS);
region[i] = jo.getString(REGION);
city[i] = jo.getString(CITY);
cat[i] = jo.getString(CATEGORY);
// image[i] = jo.getString(IMAGE);
mobiles[i] = jo.getString(MOBILE);
JSONArray img = jsonObject.getJSONArray("img");
image = new String[img.length()];
for (int j=0;j<img.length();j++){
image[i] = jo.getString(IMAGE);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
How to resolve it?
Parse it like this:
JSONArray img = jo.getJSONArray("img");
image = new String[img.length()];
for (int j=0;j<img.length();j++){
image[j] = img.getString(j);
}
Moreover, it's better to use a library like GSON for parsing.
Try implement the code below, this use List instead of arrays, it's less likely to have erros (like an Index of Bounds)
try {
jsonObject = new JSONObject(json);
users = jsonObject.getJSONArray(JSON_ARRAY);
List<String> ids = new ArrayList<>();
List<String> descriptions = new ArrayList<>();
List<String> country = new ArrayList<>();
List<String> address = new ArrayList<>();
List<String> region = new ArrayList<>();
List<String> city = new ArrayList<>();
List<String> cat = new ArrayList<>();
List<String> email = new ArrayList<>();
List<String> mobiles = new ArrayList<>();
List<String[]> img = new ArrayList<>();
for(int i=0;i<users.length();i++){
JSONObject jo = users.getJSONObject(i);
ids.add(jo.getString(KEY_ID));
// Do te rest of the "add"
JSONArray imgs = jo.getJSONArray(IMAGE)
image = new String[imgs.length()];
for (int j=0;j<imgs.length();j++){
image = jo.getString(j);
img .add(image);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
Related
// JSON Node names
private static final String TAG_CONTACTS = "contacts";
private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";
private static final String TAG_EMAIL = "email";
private static final String TAG_ADDRESS = "address";
private static final String TAG_GENDER = "gender";
private static final String TAG_PHONE = "phone";
private static final String TAG_PHONE_MOBILE = "mobile";
private static final String TAG_PHONE_HOME = "home";
private static final String TAG_PHONE_OFFICE = "office";
// contacts JSONArray
JSONArray contacts = null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> contactList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search_list);
contactList = new ArrayList<HashMap<String, String>>();
ListView lv = getListView();
// Listview on item click listener
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
int itemPosition = position;
String name = ((TextView) view.findViewById(R.id.name))
.getText().toString();
String cost = ((TextView) view.findViewById(R.id.email))
.getText().toString();
// String add = ((TextView) view.findViewById(R.id.address))
// .getText().toString();
String description = ((TextView) view.findViewById(R.id.mobile))
.getText().toString();
String price =((TextView) view.findViewById(R.id.price)).getText().toString();
String amount=((TextView) view.findViewById(R.id.mobile_labels)).getText().toString();
//String sweet = ((TextView) view.findViewById(R.id.home))
// .getText().toString();
// Starting single contact activity
Intent in = new Intent(SearchActivity.this,
SingleContactActivity.class);
in.putExtra(TAG_NAME, name);
in.putExtra(TAG_EMAIL, cost);
//in.putExtra(TAG_PHONE_MOBILE,description);
//in.putExtra(TAG_PHONE_HOME,price);
// in.putExtra(TAG_PHONE_OFFICE,amount);
//in.putExtra(TAG_ADDRESS,add);
//in.putExtra(TAG_PHONE_MOBILE, description);
// in.putExtra(TAG_PHONE_HOME,sweet);
startActivity(in);
}
});
// Calling async task to get json
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(SearchActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
contacts = jsonObj.getJSONArray(TAG_CONTACTS);
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String email = c.getString(TAG_EMAIL);
// String add = c.getString(TAG_ADDRESS);
String gender = c.getString(TAG_GENDER);
// Phone node is JSON Object
JSONObject phone = c.getJSONObject(TAG_PHONE);
String mobile = phone.getString(TAG_PHONE_MOBILE);
String home = phone.getString(TAG_PHONE_HOME);
String office = phone.getString(TAG_PHONE_OFFICE);
// tmp hashmap for single contact
HashMap<String, String> contact = new HashMap<String, String>();
// adding each child node to HashMap key => value
contact.put(TAG_ID, id);
contact.put(TAG_NAME, name);
contact.put(TAG_EMAIL, email);
// contact.put(TAG_ADDRESS,add);
contact.put(TAG_PHONE_MOBILE, mobile);
contact.put(TAG_PHONE_HOME,home);
contact.put(TAG_PHONE_OFFICE,office);
// adding contact to contact list
contactList.add(contact);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
SearchActivity.this, contactList,
R.layout.list_item, new String[] { TAG_NAME, TAG_EMAIL,
TAG_PHONE_MOBILE ,TAG_PHONE_HOME,TAG_PHONE_OFFICE }, new int[] { R.id.name,
R.id.email, R.id.mobile,R.id.price ,R.id.mobile_labels});
setListAdapter(adapter);
}
}
}
Here is the list. In this I am getting name,email and mobile number. In the list when I select a name in the list open a new activity in that activity I need name, email, phone, address, gender, office. How should I pass this in next activity.
Here is the next activity code.
private static final String TAG_NAME = "name";
private static final String TAG_EMAIL = "email";
private static final String TAG_PHONE_MOBILE = "mobile";
private static final String TAG_PHONE_HOME = "home";
private static final String TAG_PHONE_OFFICE = "office";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_single_contact);
// getting intent data
Intent in = getIntent();
// Get JSON values from previous intent
String name = in.getStringExtra(TAG_NAME);
String email = in.getStringExtra(TAG_EMAIL);
String mobile = in.getStringExtra(TAG_PHONE_MOBILE);
String home = in.getStringExtra(TAG_PHONE_HOME);
String office= in.getStringExtra(TAG_PHONE_OFFICE);
// Displaying all values on the screen
TextView lblName = (TextView) findViewById(R.id.name_label);
TextView lblEmail = (TextView) findViewById(R.id.email_label);
TextView lblMobile = (TextView) findViewById(R.id.mobile_label);
TextView lblMobiles = (TextView) findViewById(R.id.mobile_labels);
TextView lblOffice = (TextView) findViewById(R.id.mobile_office);
lblName.setText(name);
lblEmail.setText(email);
lblMobile.setText(mobile);
lblMobiles.setText(home);
lblOffice.setText(office);
}
}
It's better if I have only a name in the listview. On selecting the name in the list further details should be displayed, for instance: name, phone, email, address, gender.
Pass them through the intent you used to start the new activity. When you generate the intent you can bundle some information and pass it as an extra. Then all the information should be in the bundle when your new activity starts. That's probably the easiest way.
There's lots of information in those links, and google has tutorials on how to use intents as well.
Hope that helps!
private static final String TAG_CONTACTS = "contacts";
private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";
private static final String TAG_EMAIL = "email";
private static final String TAG_ADDRESS = "address";
private static final String TAG_GENDER = "gender";
private static final String TAG_PHONE = "phone";
private static final String TAG_PHONE_MOBILE = "mobile";
private static final String TAG_PHONE_HOME = "home";
private static final String TAG_PHONE_OFFICE = "office";
// contacts JSONArray
JSONArray contacts = null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> contactList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search_list);
contactList = new ArrayList<HashMap<String, String>>();
ListView lv = getListView();
// Listview on item click listener
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
int itemPosition = position;
String name = ((TextView) view.findViewById(R.id.name))
.getText().toString();
String cost = ((TextView) view.findViewById(R.id.email))
.getText().toString();
// String add = ((TextView) view.findViewById(R.id.address))
// .getText().toString();
// String description = ((TextView) view.findViewById(R.id.mobile))
//.getText().toString();
//String sweet = ((TextView) view.findViewById(R.id.home))
// .getText().toString();
// Starting single contact activity
Intent in = new Intent(SearchActivity.this,
SingleContactActivity.class);
in.putExtra(TAG_NAME, name);
in.putExtra(TAG_EMAIL, cost);
//in.putExtra(TAG_ADDRESS,add);
//in.putExtra(TAG_PHONE_MOBILE, description);
// in.putExtra(TAG_PHONE_HOME,sweet);
startActivity(in);
}
});
// Calling async task to get json
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(SearchActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
contacts = jsonObj.getJSONArray(TAG_CONTACTS);
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String email = c.getString(TAG_EMAIL);
// String add = c.getString(TAG_ADDRESS);
String gender = c.getString(TAG_GENDER);
// Phone node is JSON Object
JSONObject phone = c.getJSONObject(TAG_PHONE);
String mobile = phone.getString(TAG_PHONE_MOBILE);
String home = phone.getString(TAG_PHONE_HOME);
String office = phone.getString(TAG_PHONE_OFFICE);
// tmp hashmap for single contact
HashMap<String, String> contact = new HashMap<String, String>();
// adding each child node to HashMap key => value
contact.put(TAG_ID, id);
contact.put(TAG_NAME, name);
contact.put(TAG_EMAIL, email);
// contact.put(TAG_ADDRESS,add);
contact.put(TAG_PHONE_MOBILE, mobile);
contact.put(TAG_PHONE_HOME,home);
// adding contact to contact list
contactList.add(contact);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
SearchActivity.this, contactList,
R.layout.list_item, new String[] { TAG_NAME, TAG_EMAIL,
TAG_PHONE_MOBILE ,TAG_PHONE_HOME }, new int[] { R.id.name,
R.id.email, R.id.mobile,R.id.home });
setListAdapter(adapter);
}
}
}
I have a list activity in the list it display the name,email,phone number on select an item in the list open a new activity and display the same name, email,number but i need others details in nextactivity including addrees,gender,home, office
In the nextactivity i displaying this items
private static final String TAG_NAME = "name";
private static final String TAG_EMAIL = "email";
private static final String TAG_PHONE_MOBILE = "mobile";
private static final String TAG_PHONE_HOME = "home";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_single_contact);
// getting intent data
Intent in = getIntent();
// Get JSON values from previous intent
String name = in.getStringExtra(TAG_NAME);
String email = in.getStringExtra(TAG_EMAIL);
String mobile = in.getStringExtra(TAG_PHONE_MOBILE);
String home = in.getStringExtra(TAG_PHONE_HOME);
// Displaying all values on the screen
TextView lblName = (TextView) findViewById(R.id.name_label);
TextView lblEmail = (TextView) findViewById(R.id.email_label);
TextView lblMobile = (TextView) findViewById(R.id.mobile_label);
TextView lblMobiles = (TextView) findViewById(R.id.mobile_labels);
lblName.setText(name);
lblEmail.setText(email);
lblMobile.setText(mobile);
lblMobiles.setText(home);
}
}
Inclusignthsi i want to display address,home,office .
private static final String TAG_NAME = "name";
private static final String TAG_EMAIL = "email";
private static final String TAG_PHONE_MOBILE = "mobile";
private static final String TAG_PHONE_HOME = "home";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_single_contact);
// getting intent data
Intent in = getIntent();
// Get JSON values from previous intent
String name = in.getStringExtra(TAG_NAME);
String email = in.getStringExtra(TAG_EMAIL);
String mobile = in.getStringExtra(TAG_PHONE_MOBILE);
String home = in.getStringExtra(TAG_PHONE_HOME);
// Displaying all values on the screen
TextView lblName = (TextView) findViewById(R.id.name_label);
TextView lblEmail = (TextView) findViewById(R.id.email_label);
TextView lblMobile = (TextView) findViewById(R.id.mobile_label);
TextView lblMobiles = (TextView) findViewById(R.id.mobile_labels);
lblName.setText(name);
lblEmail.setText(email);
lblMobile.setText(mobile);
lblMobiles.setText(home);
}
#subhas i have updated th other activity code
I am populating listview with separate item file with json string here...
item file is ticket_items
listview file is ticktsfr
Tickets.php:
<?php
if($_SERVER['REQUEST_METHOD']=='GET'){
$user_id = $_GET['user_id'];
require_once('db_configuration.php');
$sql = "SELECT * FROM (SELECT a.event_name, b.ticket_name,b.ticket_quantity,
b.ticket_description, b.ticket_channel, b.ticket_start_date,
b.ticket_end_date,b.user_id FROM event a, ticket b WHERE a.event_id =
b.event_id and a.user_id = b.user_id) AS T WHERE user_id='"$user_id"'";
$res = mysqli_query($con,$sql);
$result = array();
while($row = mysqli_fetch_array($res))
{
array_push($result,array
(
"event_name"=>$row[0],
"ticket_name"=>$row[1],
"ticket_quantity"=>$row[2],
"ticket_description"=>$row[3],
"ticket_channel"=>$row[4],
"ticket_start_date"=>$row[5],
"ticket_end_date"=>$row[6],
"user_id"=>$row[7]
)
);
}
echo json_encode(array("result"=>$result));
mysqli_close($con);
}
Tickets.java:(Activity)
public class Tickets extends Fragment {
//boolean variable to check user is logged in or not
//initially it is false
boolean loggedIn = false;
private ListView listView;
private static final String JSON_URL =
"http://myip/eevento/tickets.php?user_id=";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.ticketsfr, null);
listView = (ListView) view.findViewById(R.id.list3);
sendRequest();
return view;
}
private void sendRequest(){
String url = JSON_URL+Loginhandler.USER_ID;
StringRequest stringRequest = new StringRequest(url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
showJSON(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error){
Toast.makeText(getActivity(),error.getMessage(),Toast.LENGTH_LONG).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
requestQueue.add(stringRequest);
}
private void showJSON(String json) {
Ticketshandler2 pj = new Ticketshandler2(json);
pj.parseJSON();
Ticketshandler cl = new Ticketshandler(getActivity(),
Ticketshandler2.event_name, Ticketshandler2.ticket_name,
Ticketshandler2.ticket_quantity, Ticketshandler2.ticket_description,
Ticketshandler2.ticket_channel, Ticketshandler2.ticket_start_date,
Ticketshandler2.ticket_end_date, Ticketshandler2.user_id);
listView.setAdapter(cl);
}
}
Ticketshandler.java:(Class)
public class Ticketshandler extends ArrayAdapter<String> {
TextView namme;
ProgressDialog loading;
private String[] event_name;
private String[] ticket_name;
private String[] ticket_quantity;
private String[] ticket_description;
private String[] ticket_channel;
private String[] ticket_start_date;
private String[] ticket_end_date;
private String[] user_id;
private Activity context;
public Ticketshandler(Activity context, String[] event_name, String[]
ticket_name,String[] ticket_quantity,String[] ticket_description,String[]
ticket_channel,String[] ticket_start_date,String[] ticket_end_date,String[]
user_id) {
super(context, R.layout.tickets_item, event_name);
this.context = context;
this.event_name = event_name;
this.ticket_name = ticket_name;
this.ticket_quantity = ticket_quantity;
this.ticket_description = ticket_description;
this.ticket_channel = ticket_channel;
this.ticket_start_date = ticket_start_date;
this.ticket_end_date = ticket_end_date;
this.user_id = user_id;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View listViewItem = inflater.inflate(R.layout.tickets_item, null, true);
TextView event_topic_description = (TextView)
listViewItem.findViewById(R.id.titem);
String output = "" + event_name[position] + "\n" + ticket_name[position]
+ "\n" + ticket_quantity[position] + "\n" + ticket_description[position] +
"\n"
+ ticket_channel[position] + "\n" + ticket_start_date[position] + "\n" +
ticket_end_date[position];
// String output = "" +event_name[position];
event_topic_description.setText(output);
System.out.println(output);
return listViewItem;
}
}
Ticketshandler2.java:(Class)
public class Ticketshandler2 {
public static String[] event_name;
public static String[] ticket_name;
public static String[] ticket_quantity;
public static String[] ticket_description;
public static String[] ticket_channel;
public static String[] ticket_start_date;
public static String[] ticket_end_date;
public static String[] user_id;
public static final String JSON_ARRAY = "result";
public static final String EVENT_NAME = "event_name";
public static final String TICKET_NAME = "ticket_name";
public static final String TICKET_QUANTITY = "ticket_quantity";
public static final String TICKET_DESCRIPTION = "ticket_description";
public static final String TICKET_CHANNEL = "ticket_channel";
public static final String TICKET_START_DATE = "ticket_start_date";
public static final String TICKET_END_DATE = "ticket_end_date";
public static final String USER_ID = "user_id";
private JSONArray users = null;
private String json;
public Ticketshandler2(String json){
this.json = json;
}
protected void parseJSON(){
JSONObject jsonObject=null;
try {
jsonObject = new JSONObject(json);
users = jsonObject.getJSONArray(JSON_ARRAY);
System.out.println(users);
event_name = new String[users.length()];
ticket_name = new String[users.length()];
ticket_quantity = new String[users.length()];
ticket_description = new String[users.length()];
ticket_channel = new String[users.length()];
ticket_start_date = new String[users.length()];
ticket_end_date = new String[users.length()];
user_id = new String[users.length()];
for(int i=0;i<users.length();i++){
JSONObject jo = users.getJSONObject(i);
event_name[i] = jo.getString(EVENT_NAME);
ticket_name[i] = jo.getString(TICKET_NAME);
ticket_quantity[i] = jo.getString(TICKET_QUANTITY);
ticket_description[i] = jo.getString(TICKET_DESCRIPTION);
ticket_channel[i] = jo.getString(TICKET_CHANNEL);
ticket_start_date[i] = jo.getString(TICKET_START_DATE);
ticket_end_date[i] = jo.getString(TICKET_END_DATE);
user_id[i] = jo.getString(USER_ID);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Log:
"12-09 12:00:17.750 31591-31591/com.example.dell.evento W/System.err:
org.json.JSONException: Value <br of type java.lang.String cannot be
converted to JSONObject"
I think my query has some issues, but it is working perfectly in wamp mysql separately..I dont understand what is the issue,, help...
Your response code might be not escape from htmlentities.
you need to first escape html string to proper character code.because java default not took any character code.
I am using listview to display items obtained from json response. Currently 10 items are displaying, as i scroll down more items must load but it is not happening. Following is my code can anyone help me? Answers will be appreciated.
public class MainActivity extends ListActivity {
ListView list;
LazyAdapter adapter;
JSONArray posts;
// All static variables
static final String URL = "http://site.org/";
static final String KEY_POSTS = "posts";
static final String KEY_ID = "id";
static final String KEY_TITLE = "title";
static final String KEY_DATE = "date";
static final String KEY_CONTENT = "content";
static final String KEY_AUTHOR = "author";
static final String KEY_NAME = "name";
static final String KEY_ATTACHMENTS = "attachments";
static final String KEY_SLUG = "slug";
static final String KEY_THUMB_URL = "thumbnail";
static final String KEY_IMAGES = "images";
static final String KEY_URL = "url";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Handler handler = new Handler();
Runnable runable = new Runnable() {
#Override
public void run() {
//call the function
LoadData();
//also call the same runnable
handler.postDelayed(this, 40000);
}
};
handler.postDelayed(runable, 10);
}public void LoadData(){
ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>();
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(URL);
try {
JSONArray posts = json.getJSONArray(KEY_POSTS);
// looping through all song nodes <song>
for(int i = 0; i < posts.length(); i++){
JSONObject c = posts.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(KEY_ID);
String title = c.getString(KEY_TITLE);
String date = c.getString(KEY_DATE);
String content = c.getString(KEY_CONTENT);
// to remove all <P> </p> and <br /> and replace with ""
content = content.replace("<br />", "");
content = content.replace("<p>", "");
content = content.replace("</p>", "");
//authornumber is agin JSON Object
JSONObject author = c.getJSONObject(KEY_AUTHOR);
String name = author.getString(KEY_NAME);
String url = null;
String slug = null;
try {
JSONArray atta = c.getJSONArray("attachments");
for(int j = 0; j < atta.length(); j++){
JSONObject d = atta.getJSONObject(j);
slug = d.getString(KEY_SLUG);
JSONObject images = d.getJSONObject(KEY_IMAGES);
JSONObject thumbnail = images.getJSONObject(KEY_THUMB_URL);
url = thumbnail.getString(KEY_URL);
}
} catch (Exception e) {
e.printStackTrace();
}
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(KEY_ID, id);
map.put(KEY_TITLE, title);
map.put(KEY_DATE, date);
map.put(KEY_NAME, name);
map.put(KEY_CONTENT, content);
map.put(KEY_SLUG, slug);
map.put(KEY_URL, url);
// adding HashList to ArrayList
songsList.add(map);
}
}catch (JSONException e) {
e.printStackTrace();
}
// Getting adapter by passing json data ArrayList
adapter=new LazyAdapter(this, songsList);
adapter.notifyDataSetChanged();
ListView list=(ListView)findViewById(android.R.id.list);
list.setAdapter(adapter);
// Launching new screen on Selecting Single ListItem
list.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String title = ((TextView) view.findViewById(R.id.title)).getText().toString();
String date = ((TextView) view.findViewById(R.id.date)).getText().toString();
String name = ((TextView) view.findViewById(R.id.name)).getText().toString();
String content = ((TextView) view.findViewById(R.id.content)).getText().toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(),SampleDesp.class);
in.putExtra(KEY_TITLE, title);
in.putExtra(KEY_DATE, date);
in.putExtra(KEY_NAME, name);
in.putExtra(KEY_CONTENT, content);
startActivity(in);
}
});
list.setOnScrollListener(new OnScrollListener(){
#Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
// TODO Auto-generated method stub
}
#Override
public void onScrollStateChanged(AbsListView view,
int scrollState) {
// TODO Auto-generated method stub
}
});
}
}
I have the following JSON
[{"name":"Games","id":1,"thumbnail":"https:\/\/lh5.ggpht.com\/_nl17ca8wUp0BbiD9J7mTBSO1o42KpdK2IolG3NjF22o1KbhIZ6ga5e_cXPp42fNUjA=w78","image_medium":"https:\/\/lh5.ggpht.com\/_nl17ca8wUp0BbiD9J7mTBSO1o42KpdK2IolG3NjF22o1KbhIZ6ga5e_cXPp42fNUjA=w78","image_large":"https:\/\/lh5.ggpht.com\/_nl17ca8wUp0BbiD9J7mTBSO1o42KpdK2IolG3NjF22o1KbhIZ6ga5e_cXPp42fNUjA=w78"},{"name":"Sports","id":2,"thumbnail":"https:\/\/lh4.ggpht.com\/yvn4iHEzWN7NmwVkw08ufwSS86mYPpK2Z8WgYkwkQqojMTPsTs28tIiz4v780KGQfrA=w78","image_medium":"https:\/\/lh4.ggpht.com\/yvn4iHEzWN7NmwVkw08ufwSS86mYPpK2Z8WgYkwkQqojMTPsTs28tIiz4v780KGQfrA=w78","image_large":"https:\/\/lh4.ggpht.com\/yvn4iHEzWN7NmwVkw08ufwSS86mYPpK2Z8WgYkwkQqojMTPsTs28tIiz4v780KGQfrA=w78"}]
The following is the code snippet to read the above json
private static final String TAG_CATEGORY_NAME = "name";
private static final String TAG_CATEGORY_ID = "id";
private static final String TAG_CATEGORY_THUMBNAIL = "thumbnail";
private static final String TAG_CATEGORY_IMAGE_MEDIUM = "image_medium";
private static final String TAG_CATEGORY_IMAGE_LARGE = "image_large";
try
{
//Getting Array of Categories
**categories = json.getJSONArray(name);** //Line 1
for(int i=0; i < categories.length(); i++)
{
JSONObject c = categories.getJSONObject(i);
String cname = c.getString(TAG_CATEGORY_NAME);
String cid = c.getString(TAG_CATEGORY_ID);
String cThumbNail = c.getString(TAG_CATEGORY_THUMBNAIL);
String cImageMedium = c.getString(TAG_CATEGORY_IMAGE_MEDIUM);
String cImageLarge = c.getString(TAG_CATEGORY_IMAGE_LARGE);
}
}
catch(JSONException e)
{
e.printStackTrace();
}
As there is no name given to represent each array in the json, Can anyone please tell me the right way to write way to write line 1 in this scenario.