get the data from the webservice IOException - android

`the next code should pars data from the baseurl(web service) to textView
Problem:
*it gives IOException .. I'm sure from the webservice but the program still gives error any one help to get the data from the webservice??*
public class NewParsActivity extends Activity {
/** Called when the activity is first created. */
static final String baseUrl="http://www.androidpeople.com/wp-content/uploads/2010/06/example.xml";
TextView tv;
EditText ed,ed2;
Button b;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tv=(TextView)findViewById(R.id.text);
ed=(EditText)findViewById(R.id.edt);
b=(Button) findViewById(R.id.button1);
ed2=(EditText) findViewById(R.id.editText1);
try{
SAXParserFactory spf=SAXParserFactory.newInstance();
SAXParser sp=spf.newSAXParser();
XMLReader xr=sp.getXMLReader();
URL link=new URL(baseUrl);
handlXml doingWork=new handlXml();
xr.setContentHandler(doingWork);
xr.parse(new InputSource(link.openStream()));
String information=doingWork.getInformation();
tv.setText(information);
}catch(Exception e){
tv.setText("Error");
}
//
public class handlXml extends DefaultHandler {
One item=new One();
public String getInformation(){
return item.DataToString();
}
#Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
// TODO Auto-generated method stub
if(localName.equals("website")){
String uniN=attributes.getValue("category");
item.setName(uniN);
}
}
}
//
<i>
public class One {
String UName;
public void setName(String n){
UName=n;
}
public String DataToString()
{
return "In"+UName;
}
}
<i>

Same example with API working fine for me.
XMLParsingExample.java
public class XMLParsingExample extends Activity {
/** Create Object For SiteList Class */
SitesList sitesList = null;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
/** Create a new layout to display the view */
LinearLayout layout = new LinearLayout(this);
layout.setOrientation(1);
/** Create a new textview array to display the results */
TextView name[];
TextView website[];
TextView category[];
try {
/** Handling XML */
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
/** Send URL to parse XML Tags */
URL sourceUrl = new URL(
"http://www.androidpeople.com/wp-content/uploads/2010/06/example.xml");
/** Create handler to handle XML Tags ( extends DefaultHandler ) */
MyXMLHandler myXMLHandler = new MyXMLHandler();
xr.setContentHandler(myXMLHandler);
xr.parse(new InputSource(sourceUrl.openStream()));
} catch (Exception e) {
System.out.println("XML Pasing Excpetion = " + e);
}
/** Get result from MyXMLHandler SitlesList Object */
sitesList = MyXMLHandler.sitesList;
/** Assign textview array lenght by arraylist size */
name = new TextView[sitesList.getName().size()];
website = new TextView[sitesList.getName().size()];
category = new TextView[sitesList.getName().size()];
/** Set the result text in textview and add it to layout */
for (int i = 0; i < sitesList.getName().size(); i++) {
name[i] = new TextView(this);
name[i].setText("Name = "+sitesList.getName().get(i));
website[i] = new TextView(this);
website[i].setText("Website = "+sitesList.getWebsite().get(i));
category[i] = new TextView(this);
category[i].setText("Website Category = "+sitesList.getCategory().get(i));
layout.addView(name[i]);
layout.addView(website[i]);
layout.addView(category[i]);
}
/** Set the layout view to display */
setContentView(layout);
}
}
XMLParsing Sample Project
Here's my output Window -

have a look at this tutorial there is a good guide about xml parsing in android.i hope this will solve ur query
here i am putting that tutrial content
say we need to parse this xml file
http://api.androidhive.info/pizza/?format=xml
and here is a class for parsing this xml
public class AndroidXMLParsingActivity extends ListActivity {
// All static variables
static final String URL = "http://api.androidhive.info/pizza/?format=xml";
// XML node keys
static final String KEY_ITEM = "item"; // parent node
static final String KEY_ID = "id";
static final String KEY_NAME = "name";
static final String KEY_COST = "cost";
static final String KEY_DESC = "description";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();
XMLParser parser = new XMLParser();
String xml = parser.getXmlFromUrl(URL); // getting XML
Document doc = parser.getDomElement(xml); // getting DOM element
NodeList nl = doc.getElementsByTagName(KEY_ITEM);
// looping through all item nodes <item>
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(KEY_ID, parser.getValue(e, KEY_ID));
map.put(KEY_NAME, parser.getValue(e, KEY_NAME));
map.put(KEY_COST, "Rs." + parser.getValue(e, KEY_COST));
map.put(KEY_DESC, parser.getValue(e, KEY_DESC));
// adding HashList to ArrayList
menuItems.add(map);
}
// Adding menuItems to ListView
ListAdapter adapter = new SimpleAdapter(this, menuItems,
R.layout.list_item,
new String[] { KEY_NAME, KEY_DESC, KEY_COST }, new int[] {
R.id.name, R.id.desciption, R.id.cost });
setListAdapter(adapter);
// selecting single ListView item
ListView lv = getListView();
// listening to single listitem click
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String name = ((TextView) view.findViewById(R.id.name)).getText().toString();
String cost = ((TextView) view.findViewById(R.id.cost)).getText().toString();
String description = ((TextView) view.findViewById(R.id.desciption)).getText().toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(), SingleMenuItemActivity.class);
in.putExtra(KEY_NAME, name);
in.putExtra(KEY_COST, cost);
in.putExtra(KEY_DESC, description);
startActivity(in);
}
});
}
}
and complete guide about this can be found from this link
http://www.androidhive.info/2011/11/android-xml-parsing-tutorial/

Related

Filter ListView data

I am working on an App where data is read from XML, then based on the data, It creates an ListView and clicking on any item in ListView it opens another activity with details. I am trying to implement search functionality in the ListView, below is my code, I don't know how ti implement Search, I tried many ways but none of them worked. Any help is highly appreciated. Thanks in advance.
public class BrowseActors extends Activity {
private static final String TAG = "QuizListActivity";
private ImageView bannerImageView; // displays a Image
// Search EditText
private EditText inputSearch;
// XML node keys
static final String KEY_TAG = "ActorData"; // parent node
static final String KEY_ID = "id";
static final String KEY_NAME = "name";
static final String KEY_ICON = "icon";
String position;
String sourceFile;
// List items
ListView list;
//BinderActorData adapter = null;
List<HashMap<String, String>> actorDataCollection;
ArrayAdapter<HashMap<String, String>> adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE); // Remove title
setContentView(R.layout.browse_actor);
bannerImageView = (ImageView) findViewById(R.id.topImageView);
try {
// Get Category to filter
Intent in = getIntent();
this.position = in.getStringExtra("position");
sourceFile="BaseData.xml"
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory
.newInstance();
DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
Document doc = docBuilder.parse(getAssets().open(sourceFile));
actorDataCollection = new ArrayList<HashMap<String, String>>();
// normalize text representation
doc.getDocumentElement().normalize();
NodeList quizList = doc.getElementsByTagName("ActorData");
HashMap<String, String> map = null;
for (int i = 0; i < quizList.getLength(); i++) {
map = new HashMap<String, String>();
Node firstQuestionNode = quizList.item(i);
if (firstQuestionNode.getNodeType() == Node.ELEMENT_NODE) {
Element firstAircraftElement = (Element) firstQuestionNode;
// 1.-------
NodeList idList = firstAircraftElement
.getElementsByTagName(KEY_ID);
Element firstIdElement = (Element) idList.item(0);
NodeList textIdList = firstIdElement.getChildNodes();
// --id
map.put(KEY_ID, textIdList.item(0).getNodeValue()
.trim());
// 2.-------
NodeList nameList = firstAircraftElement
.getElementsByTagName(KEY_NAME);
Element firstNameElement = (Element) nameList.item(0);
NodeList textNameList = firstNameElement
.getChildNodes();
// --name
map.put(KEY_NAME, textNameList.item(0).getNodeValue()
.trim());
// 3.-------
NodeList iconList = firstAircraftElement
.getElementsByTagName(KEY_ICON);
Element firstIconElement = (Element) iconList.item(0);
NodeList textIconList = firstIconElement
.getChildNodes();
// -- Image Icon
map.put(KEY_ICON, textIconList.item(0).getNodeValue()
.trim());
// Add to the Arraylist
actorDataCollection.add(map);
}
}
BinderActorData bindingData = new BinderActorData(this,
actorDataCollection);
// Adding items to listview
list = (ListView) findViewById(R.id.list);
// Adding items to listview
inputSearch = (EditText) findViewById(R.id.inputSearch);
list.setAdapter(bindingData);
/**
* Enabling Search Filter
* */
inputSearch.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2,
int arg3) {
// When user changed the Text
//BrowseActors.this.bindingData.getFilter().filter(cs);
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1,
int arg2, int arg3) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
}
});
// Click event for single list row
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent i = new Intent();
i.setClass(BrowseActors.this, ViewActor.class);
// parameters
i.putExtra("position", String.valueOf(position + 1));
/*
* selected item parameters
*/
i.putExtra("name",
actorDataCollection.get(position).get(KEY_NAME));
i.putExtra("icon",
actorDataCollection.get(position).get(KEY_ICON));
// start the sample activity
startActivity(i);
}
});
}
catch (IOException ex) {
Log.e("Error", ex.getMessage());
} catch (Exception ex) {
Log.e("Error", "Loading exception");
}
}
}
Search will be implemented on original data source, it could be XML/JSON/database or anything else.
You're using "position" parameter for search, I think you can use the View view parameter.
Just keep a hidden field in the ListView row, and map it with some sort of primary key.
When OnClick event occurs, you can then get the row layout from view and do a findViewByID() call to get your hidden control. From the value of that control, you can call a back-end web service or run an x-path query or anything you want.

Parsing XML node having different attribute value in Android

I have following XML data,
<RESPONSE>
<param name="Type">NBFundTransfer</param>
<param name="Id">3213</param>
<param name="Token">26&ffr$5%877</param>
<param name="Stage">1</param>
</RESPONSE>
I want to fetch the node by its name.I use following method to fetch data,
NodeList nl = doc.getElementsByTagName("RESPONSE");
String[] Agreement = new String[nl.getLength()];
for (int i = 0; i < nl.getLength(); i++) {
Node item = nl.item(i);
if (item.getNodeType() == Node.ELEMENT_NODE) {
Element ielem = (Element) item;
NodeList id = ielem.getElementsByTagName("param");
Data[i] = id.item(0).getChildNodes().item(0).getNodeValue();
}
}
But the problem is, Iam only getting the data "NBFundTransfer" from first node which is names as "Type" .I want to fetch the data from all other nodes(Id,Token etc).Please someone help me to get a solution.Thank you..
public class XMLParsingExample extends Activity {
/** Create Object For SiteList Class */
SitesList sitesList = null;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
/** Create a new layout to display the view */
LinearLayout layout = new LinearLayout(this);
layout.setOrientation(1);
/** Create a new textview array to display the results */
TextView name[];
TextView website[];
TextView category[];
try {
/** Handling XML */
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
/** Send URL to parse XML Tags */
URL sourceUrl = new URL(
"http://www.androidpeople.com/wp-content/uploads/2010/06/example.xml");
/** Create handler to handle XML Tags ( extends DefaultHandler ) */
MyXMLHandler myXMLHandler = new MyXMLHandler();
xr.setContentHandler(myXMLHandler);
xr.parse(new InputSource(sourceUrl.openStream()));
} catch (Exception e) {
System.out.println("XML Pasing Excpetion = " + e);
}
/** Get result from MyXMLHandler SitlesList Object */
sitesList = MyXMLHandler.sitesList;
/** Assign textview array lenght by arraylist size */
name = new TextView[sitesList.getName().size()];
website = new TextView[sitesList.getName().size()];
category = new TextView[sitesList.getName().size()];
/** Set the result text in textview and add it to layout */
for (int i = 0; i < sitesList.getName().size(); i++) {
name[i] = new TextView(this);
name[i].setText("Name = "+sitesList.getName().get(i));
website[i] = new TextView(this);
website[i].setText("Website = "+sitesList.getWebsite().get(i));
category[i] = new TextView(this);
category[i].setText("Website Category = "+sitesList.getCategory().get(i));
layout.addView(name[i]);
layout.addView(website[i]);
layout.addView(category[i]);
}
/** Set the layout view to display */
setContentView(layout);
}
}

Android DOM Parser - retrieving image link from description tag

I'm using DOM Parser to parse this XML feed: http://loc.grupolusofona.pt/index.php/?format=feed
I got the Parser working fine for all tags, i'm just missing ideas to be able to retrieve the image from within the description tag.
The description tag on the feed looks like this:
<description><![CDATA[<div class="K2FeedIntroText"><p><img style="margin: 10px;"
alt="joana soares rostos" src="http://loc.grupolusofona.pt/images/stories/varios/joana%20soares%20rostos.jpg"
height="110" width="120" />Quis ser veterinária mas deixou-se seduzir pela magia
de retratar o real. Joana Soares frequenta o primeiro ano do curso de Fotografia
da Lusófona e descreve a sua paixão pelas fotos como «inexplicável».</p>
</div>]]></description>
And i wanted to retrieve the image link:
http://loc.grupolusofona.pt/images/stories/varios/joana%20soares%20rostos.jpg
My Parser :
public class XMLParser {
// constructor
public XMLParser() {
}
/**
* Getting XML from URL making HTTP request
* #param url string
* */
public String getXmlFromUrl(String url) {
String xml = null;
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
xml = EntityUtils.toString(httpEntity);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// return XML
return xml;
}
/**
* Getting XML DOM element
* #param XML string
* */
public Document getDomElement(String xml){
Document doc = null;
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(xml));
doc = db.parse(is);
} catch (ParserConfigurationException e) {
Log.e("Error: ", e.getMessage());
return null;
} catch (SAXException e) {
Log.e("Error: ", e.getMessage());
return null;
} catch (IOException e) {
Log.e("Error: ", e.getMessage());
return null;
}
return doc;
}
/** Getting node value
* #param elem element
*/
public final String getElementValue( Node elem ) {
if( elem != null){
return elem.getTextContent();
}
return "";
}
/**
* Getting node value
* #param Element node
* #param key string
* */
public String getValue(Element item, String str) {
NodeList n = item.getElementsByTagName(str);
return this.getElementValue(n.item(0));
}
}
And my Main Activity:
public class Noticias extends ListActivity {
// All static variables
static final String URL = "http://loc.grupolusofona.pt/index.php/?format=feed";
// XML node keys
static final String KEY_ITEM = "item"; // parent node
static final String KEY_ID = "id";
static final String KEY_TITLE = "title";
static final String KEY_DESC = "description";
static final String KEY_LINK = "link";
static final String KEY_PUBDATE = "pubDate";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_noticias);
ArrayList<HashMap<String, Spanned>> menuItems = new ArrayList<HashMap<String, Spanned>>();
XMLParser parser = new XMLParser();
String xml = parser.getXmlFromUrl(URL); // getting XML
Document doc = parser.getDomElement(xml); // getting DOM element
NodeList nl = doc.getElementsByTagName(KEY_ITEM);
// looping through all item nodes <item>
for (int i = 0; i < nl.getLength(); i++) {
// creating new HashMap
HashMap<String, Spanned> map = new HashMap<String, Spanned>();
Element e = (Element) nl.item(i);
// adding each child node to HashMap key => value
map.put(KEY_ID, Html.fromHtml(parser.getValue(e, KEY_ID)));
map.put(KEY_TITLE, Html.fromHtml(parser.getValue(e, KEY_TITLE)));
map.put(KEY_DESC, Html.fromHtml(parser.getValue(e, KEY_DESC)));
map.put(KEY_PUBDATE, Html.fromHtml(parser.getValue(e, KEY_PUBDATE)));
map.put(KEY_LINK, Html.fromHtml(parser.getValue(e, KEY_LINK)));
// adding HashList to ArrayList
menuItems.add(map);
}
// Adding menuItems to ListView
ListAdapter adapter = new SimpleAdapter(this, menuItems,
R.layout.linha_feed,
new String[] { KEY_TITLE, KEY_DESC, KEY_PUBDATE, KEY_LINK }, new int[] {
R.id.title, R.id.desc, R.id.pub, R.id.link});
setListAdapter(adapter);
// selecting single ListView item
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
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 description = ((TextView) view.findViewById(R.id.desc)).getText().toString();
String pub = ((TextView) view.findViewById(R.id.pub)).getText().toString();
String link = ((TextView) view.findViewById(R.id.link)).getText().toString();
// Starting new intent
System.out.println("Title: " + title);
System.out.println("Link: " + link);
System.out.println("Description:" + description);
System.out.println("Pubdate: " + pub);
Intent in = new Intent(Intent.ACTION_VIEW);
in.setData(Uri.parse(link));
startActivity(in);
}
});
}
}
Any ideas ?
Thanks for your time.
Use RegEx with a simple pattern like this:
<\s*img\s*[^>]+src\s*=\s*(['"]?)(.*?)\1
Here use these functions:
public static String getMatch(String patternString, String text, int groupIndex){
Pattern pattern = Pattern.compile(patternString, Pattern.CASE_INSENSITIVE | Pattern.DOTALL );
return RegEx.getMatch(pattern, text, groupIndex);
}
public static String getMatch(Pattern pattern, String text, int groupIndex){
if(text!=null){
Matcher matcher = pattern.matcher(text);
String match = null;
while(matcher.find()){
match = matcher.group(groupIndex);
break;
}
return match;
}else{
return null;
}
}
Then you can plug in that pattern like this:
String imageSource = getMatch("<\\s*img\\s*[^>]+src\\s*=\\s*(['\"]?)(.*?)\\1", description, 2);

Android listview header

i have an app that is showing data in listview ,but i want first row to be inflated by diferent layout , and i did that but since there is gona be a big number of listitems , i want to optimize listview and there is issue. i cant optimize listview when iam filling listview on that way , so how can i put content that should go in fist row inside listview header witch is inflated by some layout ,here is the code of Adapter
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.main);
LinearLayout content = (LinearLayout) findViewById(R.id.content);
LinearLayout refLayout = (LinearLayout) findViewById(R.id.refLayout);
refLayout.setVisibility(View.GONE);
mBtnNaslovnica = (Button) findViewById(R.id.mBtnNaslovnica);
mBtnNaslovnica.setSelected(true);
TextView txtView=(TextView) findViewById(R.id.scroller);
txtView.setSelected(true);
loadPage();
ImageButton mBtnRefresh = (ImageButton) findViewById(R.id.btnRefresh);
mBtnRefresh.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
new LoadingTask().execute(URL);
}
});
}
public void loadPage(){
ArrayList<HashMap<String, String>> homeList = new ArrayList<HashMap<String, String>>();
JSONObject jsonobj;
try {
jsonobj = new JSONObject(getIntent().getStringExtra("json"));
JSONObject datajson = jsonobj.getJSONObject("data");
JSONArray news = datajson.getJSONArray(TAG_NEWS);
JSONArray actual = datajson.getJSONArray("actual");
for(int i = 0; i < news.length(); i++){
JSONObject c = news.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_ID);
String title = c.getString(TAG_TITLE);
String story = c.getString(TAG_STORY);
String shorten = c.getString(TAG_SH_STORY);
String author = c.getString(TAG_AUTHOR);
String datetime = c.getString(TAG_DATETIME);
String img = c.getString(TAG_IMG);
String big_img = c.getString(TAG_BIG_IMG);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_ID, id);
map.put(TAG_TITLE, title);
map.put(TAG_STORY, story);
map.put(TAG_IMG, img);
map.put(TAG_BIG_IMG, big_img);
map.put(TAG_DATETIME, datetime);
map.put(TAG_AUTHOR, author);
// adding HashList to ArrayList
homeList.add(map);}
for(int i = 0; i < actual.length(); i++){
JSONObject c = actual.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_ACT_TIME);
String body = c.getString(TAG_ACT_BODY);
String anews = " | "+ id+ " " + body;
String cur_anews = ((TextView) findViewById(R.id.scroller)).getText().toString();
String complete = anews + cur_anews;
TextView anewstv = (TextView) findViewById(R.id.scroller);
anewstv.setText(complete);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
list=(ListView)findViewById(R.id.list);
// Getting adapter by passing xml data ArrayList
adapter=new LazyAdapter(this, homeList);
list.setAdapter(adapter);
// Click event for single list row
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
String cur_title = ((TextView) view.findViewById(R.id.title)).getText().toString();
String cur_story = ((TextView) view.findViewById(R.id.einfo2)).getText().toString();
String cur_author = ((TextView) view.findViewById(R.id.einfo1)).getText().toString();
String cur_datetime = ((TextView) view.findViewById(R.id.tVdatetime)).getText().toString();
String cur_actual = ((TextView) findViewById(R.id.scroller)).getText().toString();
ImageView cur_img = (ImageView) view.findViewById(R.id.list_image);
String cur_img_url = (String) cur_img.getTag();
Intent i = new Intent("com.example.androidhive.CURENTNEWS");
i.putExtra("CUR_TITLE", cur_title);
i.putExtra("CUR_STORY", cur_story);
i.putExtra("CUR_AUTHOR", cur_author);
i.putExtra("CUR_DATETIME", cur_datetime);
i.putExtra("CUR_IMG_URL", cur_img_url);
i.putExtra("CUR_ACTUAL", cur_actual);
startActivity(i);
}
});
}
public void reloadPage(String jsonstring){
ArrayList<HashMap<String, String>> homeList = new ArrayList<HashMap<String, String>>();
JSONObject jsonobj;
try {
jsonobj = new JSONObject(jsonstring);
JSONObject datajson = jsonobj.getJSONObject("data");
JSONArray news = datajson.getJSONArray(TAG_NEWS);
JSONArray actual = datajson.getJSONArray("actual");
for(int i = 0; i < news.length(); i++){
JSONObject c = news.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_ID);
String title = c.getString(TAG_TITLE);
String story = c.getString(TAG_STORY);
String shorten = c.getString(TAG_SH_STORY);
String author = c.getString(TAG_AUTHOR);
String datetime = c.getString(TAG_DATETIME);
String img = c.getString(TAG_IMG);
String big_img = c.getString(TAG_BIG_IMG);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_ID, id);
map.put(TAG_TITLE, title);
map.put(TAG_STORY, story);
map.put(TAG_IMG, img);
map.put(TAG_BIG_IMG, big_img);
map.put(TAG_DATETIME, datetime);
map.put(TAG_AUTHOR, author);
// adding HashList to ArrayList
homeList.add(map);}
for(int i = 0; i < actual.length(); i++){
JSONObject c = actual.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_ACT_TIME);
String body = c.getString(TAG_ACT_BODY);
String anews = " | "+ id+ " " + body;
String cur_anews = ((TextView) findViewById(R.id.scroller)).getText().toString();
String complete = anews + cur_anews;
TextView anewstv = (TextView) findViewById(R.id.scroller);
anewstv.setText(complete);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
list=(ListView)findViewById(R.id.list);
// Getting adapter by passing xml data ArrayList
adapter=new LazyAdapter(this, homeList);
list.setAdapter(adapter);
// Click event for single list row
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
String cur_title = ((TextView) view.findViewById(R.id.title)).getText().toString();
String cur_story = ((TextView) view.findViewById(R.id.einfo2)).getText().toString();
String cur_author = ((TextView) view.findViewById(R.id.einfo1)).getText().toString();
String cur_datetime = ((TextView) view.findViewById(R.id.tVdatetime)).getText().toString();
String cur_actual = ((TextView) findViewById(R.id.scroller)).getText().toString();
ImageView cur_img = (ImageView) view.findViewById(R.id.list_image);
String cur_img_url = (String) cur_img.getTag();
Intent i = new Intent("com.example.androidhive.CURENTNEWS");
i.putExtra("CUR_TITLE", cur_title);
i.putExtra("CUR_STORY", cur_story);
i.putExtra("CUR_AUTHOR", cur_author);
i.putExtra("CUR_DATETIME", cur_datetime);
i.putExtra("CUR_IMG_URL", cur_img_url);
i.putExtra("CUR_ACTUAL", cur_actual);
startActivity(i);
}
});
}
public void startNewActivity(){
}
public class LoadingTask extends AsyncTask<String, Object, Object>{
XMLParser parser = new XMLParser();
JSONParser jParser = new JSONParser();
LinearLayout content = (LinearLayout) findViewById(R.id.content);
LinearLayout refLayout = (LinearLayout) findViewById(R.id.refLayout);
protected void onPreExecute(){
content.setClickable(false);
refLayout.setVisibility(View.VISIBLE);
}
#Override
protected Object doInBackground(String... params) {
// TODO Auto-generated method stub
String URL = params[0];
JSONObject json = jParser.getJSONFromUrl(URL);
//String xml = parser.getXmlFromUrl(URL); // getting XML from URL
// getting DOM element
return json;
}
protected void onPostExecute(Object result){
String json;
json = result.toString();
reloadPage(json);
refLayout.setVisibility(View.GONE);
}
}
}
If I got your point - you can go with 2 approaches:
Add headerView to the list. That is just easy as inflate your View and pass it to
addHeaderView(View) of your List. Note: you must add this view before setting the adapter, or it will throw the exception.
However, as your 'header' is representing the same data as all other items, but has different layout - I suggest not to use Header here. Instead, try to implement getItemViewType() in your adapter. http://developer.android.com/reference/android/widget/BaseAdapter.html#getItemViewType(int)
If you'll do - you'll have ability to check which type of layout to return in getView() method. And Android will take care of optimizing and reusing your inflated Views for you, so you can be sure that convertView, passed to your getView will be of the right type and layout.
Please let me know if I should explain with more details.
You can do it like this:
...
convertView.setOnClickListener(new OnItemClick(position));
...
public class OnItemClick implements OnClickListener {
private final int index;
public OnItemClick(int _index) {
this.index = _index;
}
#Override
public void onClick(View v) {
//dosomething
}
}

showing xml data into gridview in android

I am trying to display data from xml file in to grid view in android, but this page is showing one error,can any one please make me clear.....
GridviewSample.java
public class GridviewSample extends Activity
{
// All static variables
static final String URL = "http://54.251.60.177/StudentWebService/StudentDetail.asmx/GetTMSOrders";
// XML node keys
static final String KEY_TABLE = "Table"; // parent node
static final String KEY_CUST = "Cust_Name";
static final String KEY_ORDER = "Order_No";
static final String KEY_FREIGHT = "Freight_Rate";
static final String KEY_STATION1 = "Station_Name";
static final String KEY_STATION2 = "Station_Name1";
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
GridView gv = (GridView)findViewById(R.id.gridView1);
ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();
XMLParser parser = new XMLParser();
String xml = parser.getXmlFromUrl(URL); // getting XML
Document doc = parser.getDomElement(xml); // getting DOM element
NodeList nl = doc.getElementsByTagName(KEY_TABLE);
// looping through all item nodes <item>
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(KEY_CUST, parser.getValue(e, KEY_CUST));
map.put(KEY_ORDER, parser.getValue(e, KEY_ORDER));
map.put(KEY_FREIGHT, parser.getValue(e, KEY_FREIGHT));
map.put(KEY_STATION1, parser.getValue(e, KEY_STATION1));
map.put(KEY_STATION2, parser.getValue(e, KEY_STATION2));
// adding HashList to ArrayList
menuItems.add(map);
}
// Adding menuItems to ListView
SimpleAdapter adapter = new SimpleAdapter(this, menuItems,R.layout.grid_item,
new String[] { KEY_CUST, KEY_ORDER, KEY_FREIGHT,KEY_STATION1,KEY_STATION2 }, new int[]
{
R.id.cust, R.id.order, R.id.freight,R.id.statio1,R.id.station2 });
gv.setAdapter(adapter);
gv.setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView<?> Table, View v,int position, long id)
{
// getting values from selected GridItem
String cust = ((TextView) v.findViewById(R.id.cust)).getText().toString();
String order = ((TextView) v.findViewById(R.id.order)).getText().toString();
String freight = ((TextView) v.findViewById(R.id.freight)).getText().toString();
String station1 = ((TextView) v.findViewById(R.id.statio1)).getText().toString();
String station2 = ((TextView) v.findViewById(R.id.station2)).getText().toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(), Single_gridview_item.class);
in.putExtra(KEY_CUST, cust);
in.putExtra(KEY_ORDER, order);
in.putExtra(KEY_FREIGHT, freight);
in.putExtra(KEY_STATION1, station1);
in.putExtra(KEY_STATION2, station2);
startActivity(in);
}
});
}}
Thanks for you time!..
You should use an AsyncTask to perform the connection because otherwise the main thread can get stuck and Android will exit your application.

Categories

Resources