parse Xml data like json parse - android

I am developing android application and I got a error When I parse XML data like Json.I confused how many array has this data? I share code at below. can anyone help me or sharing example code like this xml data?
public class MainActivity extends Activity implements OnRefreshListener,
OnClickListener {
// Declare Variables
JSONObject jsonobject;
JSONArray jsonarray;
JSONArray jsonarray2;
ListView listview;
ListViewAdapter adapter;
ProgressDialog mProgressDialog;
ArrayList<HashMap<String, String>> arraylist;
static String RANK = "rank";
static String COUNTRY = "country";
static String POPULATION = "population";
static String FLAG = "flag";
Button btngeri;
static Integer[] imageId = { R.drawable.enveloppe, R.drawable.enveloppe,
R.drawable.enveloppe, R.drawable.enveloppe, R.drawable.enveloppe,
R.drawable.enveloppe, R.drawable.enveloppe };
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get the view from listview_main.xml
setContentView(R.layout.listview_main);
btngeri = (Button) findViewById(R.id.btn_geri);
btngeri.setOnClickListener(this);
// Execute DownloadJSON AsyncTask
new DownloadJSON().execute();
}
// DownloadJSON AsyncTask
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
mProgressDialog = new ProgressDialog(MainActivity.this);
// Set progressdialog title
mProgressDialog.setTitle("Mail Kutusu");
// Set progressdialog message
mProgressDialog.setMessage("Güncelleme Yapılıyor...");
mProgressDialog.setIndeterminate(false);
// Show progressdialog
mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
// Create an array
arraylist = new ArrayList<HashMap<String, String>>();
// Retrieve JSON Objects from the given URL address
jsonobject = JSONfunctions
.getJSONfromURL("http://78.186.62.169:8210/AnketServis.asmx/Message");
try {
// Locate the array name in JSON
jsonarray = jsonobject.getJSONArray("MessageVO");
for (int i = 0; i < jsonarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
jsonobject = jsonarray.getJSONObject(i);
// Retrive JSON Objects
// map.put("rank", jsonobject.getString("rank"));
map.put("country", jsonobject.getString("Konu"));
// map.put("population",
// jsonobject.getString("population"));
// map.put("flag", jsonobject.getString("flag"));
// Set the JSON Objects into the array
arraylist.add(map);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void args) {
// Locate the listview in listview_main.xml
listview = (ListView) findViewById(R.id.listview);
// Pass the results into ListViewAdapter.java
adapter = new ListViewAdapter(MainActivity.this, arraylist, imageId);
// Set the adapter to the ListView
listview.setAdapter(adapter);
// Close the progressdialog
mProgressDialog.dismiss();
}
}

Yo cannot parse xml file like json. You have to use xml parser. There are two parse method. SAX and Dom. Yo can see the versus about them.
What is the difference between SAX and DOM?
And You can see the an xml parser sample in android.
http://www.androidhive.info/2011/11/android-xml-parsing-tutorial/

Related

feed xml to json using googleapi

I am using google api to convert feed xml to json, but when I use it on my android app it says that "03-10 22:32:08.045: E/log_tag(1456): Error parsing data org.json.JSONException: Value of type java.lang.String cannot be converted to JSONObject", this is part of my code where I am converting xml into json, can somebody help me? Thanks.
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
mProgressDialog = new ProgressDialog(NoticiasMia.this);
// Set progressdialog title
//mProgressDialog.setTitle("Android JSON Parse Tutorial");
// Set progressdialog message
mProgressDialog.setMessage("Actualizando...");
mProgressDialog.setIndeterminate(false);
// Show progressdialog
mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
// Create an array
arraylist = new ArrayList<HashMap<String, String>>();
// Retrieve JSON Objects from the given URL address
jsonobject = JSONfunctions
.getJSONfromURL("http://ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=10&q=myfeedurl");
try {
// Locate the array name in JSON
if(jsonobject == null)
return null;
JSONObject subObjuno = jsonobject.getJSONObject("responseData");
JSONObject subObjdos = subObjuno.getJSONObject("feed");
jsonarray = subObjdos.getJSONArray("entries");
for (int i = 0; i < jsonarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
jsonobjecttres = jsonarray.getJSONObject(i);
// Retrive JSON Objects
map.put("title", jsonobjecttres.getString("title"));
map.put("link", jsonobjecttres.getString("link"));
map.put("publishedDate", jsonobjecttres.getString("publishedDate"));
map.put("contentSnippet", jsonobjecttres.getString("contentSnippet"));
arraylist.add(map);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void args) {
if(arraylist == null || arraylist.size() == 0){
new DownloadJSON().execute();
mProgressDialog.dismiss();
return;
}
// Locate the listview in listview_main.xml
listview = (ListView) NoticiasMia.this.findViewById(R.id.lista_faltas_cometidas);
// Pass the results into ListViewAdapter.java
adapter = new LazyAdapterNoticiasMias(NoticiasMia.this, arraylist, "fonts/Roboto-Thin.ttf", "fonts/Roboto-Medium.ttf");
// Set the adapter to the ListView
listview.setAdapter(adapter);
// Close the progressdialog
mProgressDialog.dismiss();
}
}

How to create a listview to get text from web and image from folder

I make list that show text from database but the image near items. I need images that get from drawable folder in Android. It means in listview text from database and image from Android.
Code is:
public class Category extends Activity {
// progress dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> categoryList;
private static String url_books = "http://10.0.2.2/project/category.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_CATEGORY = "category";
private static final String TAG_CATEGORY_ID = "category_id";
private static final String TAG_CATEGORY_NAME = "category_name";
private static final String TAG_MESSAGE = "massage";
// category JSONArray
JSONArray category = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.category);
Typeface font1 = Typeface.createFromAsset(getAssets(),
"font/bnazanin.TTF");
// Hashmap for ListView
categoryList = new ArrayList<HashMap<String, String>>();
new LoadCategory().execute();
ListView imagelist=(ListView) findViewById(R.id.list_image);
imagelist.setAdapter(new imageview(this));
}
/**
* Background Async Task to Load category by making HTTP Request
* */
class LoadCategory extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Category.this);
pDialog.setMessage("Loading products. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_books, "GET", params);
// Check your log cat for JSON reponse
Log.d("category: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// Getting Array of category
category = json.getJSONArray(TAG_CATEGORY);
for (int i = 0; i < category.length(); i++) {
JSONObject c = category.getJSONObject(i);
// Storing each json item in variable
String category_id = c.getString(TAG_CATEGORY_ID);
String category_name = c.getString(TAG_CATEGORY_NAME);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_CATEGORY_ID,category_id);
map.put(TAG_CATEGORY_NAME, category_name);
// adding HashList to ArrayList
categoryList.add(map);
}
return json.getString(TAG_MESSAGE);
} else {
System.out.println("no category found");
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
ListView lv=(ListView)findViewById(R.id.list_view);
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
Category.this,categoryList,
R.layout.category_item, new String[] { TAG_CATEGORY_NAME},
new int[] { R.id.category_name });
// updating listview
// setListAdapter(adapter);
lv.setAdapter(adapter);
}
});
}
}
In my code, i have text but no image. Any help?
Create a pojo for your needs in list items,You can set pojos values from web or local, then use custom listadapter override getView method according to ur needs. A good explanation here!

can't create multiple choice listview

This is my code i can't create the multiple choice mode listview.
Data is fetched by jason and set in the listview.
I want to multiple selection choice mode on the list view
public class ExamView extends ListActivity{
private ProgressDialog pDialog;
Intent activity;
// URL to get contacts JSON
// JSON Node names
private static final String TAG_USERMST = "products";
private static final String TAG_QID = "que_id";
private static final String TAG_QUE = "question";
private static final String TAG_QANS = "ans";
JSONArray products = null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> contactList;
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.user_activity_lv);
contactList = new ArrayList<HashMap<String, String>>();
ListView lv = getListView();
new GetContacts().execute();
}
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(ExamView.this);
pDialog.setMessage("Exam Paper is downloading...");
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
products = jsonObj.getJSONArray(TAG_USERMST);
// looping through All Contacts
for (int i = 0; i < products.length(); i++) {
JSONObject c = products.getJSONObject(i);
String queid = c.getString(TAG_QID);
String que = c.getString(TAG_QUE);
String queans = c.getString(TAG_QANS);
// tmp hashmap for single contact
HashMap<String, String> product = new HashMap<String, String>();
// adding each child node to HashMap key => value
product.put(TAG_QID,queid);
product.put(TAG_QUE, que);
product.put(TAG_QANS, queans);
// adding contact to contact list
contactList.add(product);
}
} 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(
ExamView.this, contactList,
R.layout.user_list_item_lbl, new String[] { TAG_QID, TAG_QUE,
TAG_QANS }, new int[] { R.id.name,
R.id.email, R.id.mobile });
setListAdapter(adapter);
}
}
getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
setListAdapter(new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_list_item_multiple_choice, array_sort));
Use this code its working for me.
Here array_sort is an arraylist i.e. list of all the items to be displayed.
Multiple items can be selected with this.

parsing xml data from url

how can i parse and retrieve the data from the following xml?
<?xml version="1.0" encoding="iso-8859-7"?>
<PRODUCT id='107230' name='WESTERN DIGITAL 2TB WD20EZRX [SATA 3 - 64MB]' price='89.00' photo='http://www.priveshop.gr/products/WD20EZRX_A.jpg'></PRODUCT>
public class MainActivity extends Activity {
// Declare Variables
ListView listview;
ListViewAdapter adapter;
ProgressDialog mProgressDialog;
ArrayList<HashMap<String, String>> arraylist;
static String PRODUCT = "PRODUCT";
static String RANK = "id";
static String COUNTRY = "name";
static String POPULATION = "price";
//static String FLAG = "photo";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get the view from listview_main.xml
setContentView(R.layout.listview_main);
// Execute DownloadJSON AsyncTask
new DownloadXML().execute();
}
// DownloadJSON AsyncTask
private class DownloadXML extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
mProgressDialog = new ProgressDialog(MainActivity.this);
// Set progressdialog title
mProgressDialog.setTitle("XtronLabs");
// Set progressdialog message
mProgressDialog.setMessage(" xtron searchin your web.............wait.");
mProgressDialog.setIndeterminate(false);
// Show progressdialog
mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
// Create the array
arraylist = new ArrayList<HashMap<String, String>>();
XMLParser parser = new XMLParser();
// Retrive nodes from the given website URL in XMLParser.class
String xml = parser.getXmlFromUrl("http://www.priveshop.gr/exte/android/xml_listing.php?key=12121212&id=1072");
// Retrive DOM element
Document doc = parser.getDomElement(xml);
NodeList nl = doc.getElementsByTagName(PRODUCT);
// try {
// Locate the NodeList name
// Toast.makeText(MainActivity.this,PRODUCT , Toast.LENGTH_SHORT).show();
for (int i = 0; i < nl.getLength(); i++) {
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
Element e = (Element) nl.item(i);
// adding each child node to HashMap key => value
//map.put(PRODUCT, parser.getValue(e, PRODUCT));
map.put(RANK, parser.getValue(e, RANK));
map.put(COUNTRY, parser.getValue(e, COUNTRY));
map.put(POPULATION, parser.getValue(e, POPULATION));
// map.put(FLAG, parser.getValue(e, FLAG));
// adding HashList to ArrayList
arraylist.add(map);
}
// } catch (Exception e) {
// Log.e("Error", e.getMessage());
//e.printStackTrace();
// }
// Toast.makeText(MainActivity.this, "button" +" "+ PRODUCT, Toast.LENGTH_SHORT).show();
return null;
}
#Override
protected void onPostExecute(Void args) {
// Locate the listview in listview_main.xml
listview = (ListView) findViewById(R.id.listview);
// Pass the results into ListViewAdapter.java
adapter = new ListViewAdapter(MainActivity.this, arraylist);
// Binds the Adapter to the ListView
listview.setAdapter(adapter);
// Close the progressdialog
mProgressDialog.dismiss();
}
}
}
We can only get the length from the XML not the actual data... can anyone tell me what went wrong?

Setonitemclicklistener with AsyncTask gives NullPointerException

Need your help!!!
I have activity, where I get some data in JSON format and put it ListView. Everything works fine. But I want to define what item was clicked in list with Setonitemclicklistener. I tried to use it in onPostExecuted() method of my inner Connection class,which extends AsyncTask, but I've got NullPoinerException
public class ConnectionActivity extends ListActivity{
JsonParser jsonParser = new JsonParser();
private ListView listView;
JSONArray inbox = null;
private ProgressDialog pDialog;
private static final String TAG_ID = "ID";
private static final String TAG_NAME = "Date";
private static final String TAG_DATE = "Name";
private static final String TAG_PRICE = "Price";
ArrayList<HashMap<String,String>> resultList;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
resultList = new ArrayList<HashMap<String,String>> ();
new Connection().execute();
new ListHandler().execute();
}
class Connection extends AsyncTask<String,String,String>
{
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(ConnectionActivity.this);
pDialog.setMessage("Не базарь и жди пока загрузиться!!!!");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected String doInBackground(String... args) {
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
String json = jsonParser.makeHttpRequest();
Log.d("Outbox JSON",json.toString());
try{
JSONArray jArray = new JSONArray(json);
for (int i=0;i<jArray.length();i++) {
JSONObject c = jArray.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_ID);
String name= c.getString(TAG_NAME);
String date = c.getString(TAG_DATE);
String price = c.getString(TAG_PRICE);
// creating new HashMap
HashMap<String, String> hashmap = new HashMap<String, String>();
// adding each child node to HashMap key => value
hashmap.put(TAG_ID, id);
hashmap.put(TAG_NAME, name);
hashmap.put(TAG_DATE, date);
hashmap.put(TAG_PRICE, price);
// adding HashList to ArrayList
resultList.add(hashmap);
}
}
catch(JSONException e){
Log.e("log_tag", "Error parsing data "+e.toString());
}
return null;
}
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
ConnectionActivity.this, resultList,
R.layout.connect_item, new String[] { TAG_ID, TAG_NAME, TAG_DATE, TAG_PRICE },
new int[] { R.id.order_id, R.id.order_date, R.id.order_name, R.id.order_price });
// updating listview
setListAdapter(adapter);
listView = (ListView) findViewById(R.id.list);
listView.setOnItemClickListener(new ListClickListener());
}
});
}
}
I think that problem is with using of one thread, so I created one more inner class in my ConnectionActivity like this^
class ListHandler extends AsyncTask<Void,Void,Void>
{
protected void onPreExecute ()
{
}
#Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
return null;
}
protected void onPostExecute()
{
listView = (ListView) findViewById(R.id.list);
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> adapter, View view, int position, long arg) {
Log.d("Click on the item","!!!!!!!!!!!!!!!!!!!!!");
Toast toast = Toast.makeText(getApplicationContext(),
"Пора покормить кота!", Toast.LENGTH_SHORT);
toast.show();
}
});
}
}
But it doesn't work. I mean that I cannot get the Toast when I clicked on the item , but there's no exception. I tried to handle setonitemclicklistener in void onResume() method of the Activity, but I've got NullPointerException. Also I handled this in OnPreExecute() method of the ListHandler class - same result...
Help please with it...
where is setContentView(R.layout.yourxml) ? i think you forgot it in oncreate Method.
So your listView is null and gives NPE.
AND
onPostExecute method have runonUiThread,Remove it no need it.Its already run in UI Thread.
Problem solved with extending from Activity instead of ListActivity and using setContentView().

Categories

Resources